]> arthur.barton.de Git - bup.git/blobdiff - lib/bup/_helpers.c
Find SC_ARG_MAX via C sysconf().
[bup.git] / lib / bup / _helpers.c
index 64b2194483e07fbb9c00fc3107e125a5d8e6d291..ea49c0e7571045484a35c73a7e07344607f822eb 100644 (file)
@@ -1,8 +1,12 @@
 #define _LARGEFILE64_SOURCE 1
+#define PY_SSIZE_T_CLEAN 1
 #undef NDEBUG
 #include "../../config/config.h"
-#include "bupsplit.h"
+
+// According to Python, its header has to go first:
+//   http://docs.python.org/2/c-api/intro.html#include-files
 #include <Python.h>
+
 #include <assert.h>
 #include <errno.h>
 #include <fcntl.h>
@@ -10,6 +14,7 @@
 #include <stdint.h>
 #include <stdlib.h>
 #include <stdio.h>
+#include <sys/mman.h>
 
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #ifdef HAVE_SYS_IOCTL_H
 #include <sys/ioctl.h>
 #endif
-#ifdef HAVE_LINUX_EXT2_FS_H
-#include <linux/ext2_fs.h>
-#endif
 
-#if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) \
-    && defined(HAVE_LINUX_EXT2_FS_H)
+#include "bupsplit.h"
+
+#if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
 #define BUP_HAVE_FILE_ATTRS 1
 #endif
 
 
 static int istty2 = 0;
 
+// At the moment any code that calls INTGER_TO_PY() will have to
+// disable -Wtautological-compare for clang.  See below.
+
+#define INTEGER_TO_PY(x) \
+    (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
+
+
+static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
+                                const char *name)
+{
+    const long tmp = PyInt_AsLong(py);
+    if (tmp == -1 && PyErr_Occurred())
+    {
+        if (PyErr_ExceptionMatches(PyExc_OverflowError))
+            PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
+                         name);
+        return 0;
+    }
+    if (tmp < 0)
+    {
+        PyErr_Format(PyExc_OverflowError,
+                     "negative %s cannot be converted to unsigned long", name);
+        return 0;
+    }
+    *x = tmp;
+    return 1;
+}
+
+
+static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
+{
+    if (PyInt_Check(py))
+        return bup_ulong_from_pyint(x, py, name);
+
+    if (!PyLong_Check(py))
+    {
+        PyErr_Format(PyExc_TypeError, "expected integer %s", name);
+        return 0;
+    }
+
+    const unsigned long tmp = PyLong_AsUnsignedLong(py);
+    if (PyErr_Occurred())
+    {
+        if (PyErr_ExceptionMatches(PyExc_OverflowError))
+            PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
+                         name);
+        return 0;
+    }
+    *x = tmp;
+    return 1;
+}
+
+
+static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
+{
+    unsigned long tmp;
+    if (!bup_ulong_from_py(&tmp, py, name))
+        return 0;
+
+    if (tmp > UINT_MAX)
+    {
+        PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
+        return 0;
+    }
+    *x = tmp;
+    return 1;
+}
+
+static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
+                              const char *name)
+{
+    if (PyInt_Check(py))
+    {
+        unsigned long tmp;
+        if (bup_ulong_from_pyint(&tmp, py, name))
+        {
+            *x = tmp;
+            return 1;
+        }
+        return 0;
+    }
+
+    if (!PyLong_Check(py))
+    {
+        PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
+        return 0;
+    }
+
+    const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
+    if (tmp == (unsigned long long) -1 && PyErr_Occurred())
+    {
+        if (PyErr_ExceptionMatches(PyExc_OverflowError))
+            PyErr_Format(PyExc_OverflowError,
+                         "%s too big for unsigned long long", name);
+        return 0;
+    }
+    *x = tmp;
+    return 1;
+}
+
+
 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
 #if __WIN32__ || __CYGWIN__
 
@@ -114,10 +218,12 @@ static PyObject *blobbits(PyObject *self, PyObject *args)
 static PyObject *splitbuf(PyObject *self, PyObject *args)
 {
     unsigned char *buf = NULL;
-    int len = 0, out = 0, bits = -1;
+    Py_ssize_t len = 0;
+    int out = 0, bits = -1;
 
     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
        return NULL;
+    assert(len <= INT_MAX);
     out = bupsplit_find_ofs(buf, len, &bits);
     if (out) assert(bits >= BUP_BLOBBITS);
     return Py_BuildValue("ii", out, bits);
@@ -127,8 +233,9 @@ static PyObject *splitbuf(PyObject *self, PyObject *args)
 static PyObject *bitmatch(PyObject *self, PyObject *args)
 {
     unsigned char *buf1 = NULL, *buf2 = NULL;
-    int len1 = 0, len2 = 0;
-    int byte, bit;
+    Py_ssize_t len1 = 0, len2 = 0;
+    Py_ssize_t byte;
+    int bit;
 
     if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
        return NULL;
@@ -146,6 +253,7 @@ static PyObject *bitmatch(PyObject *self, PyObject *args)
        }
     }
     
+    assert(byte <= (INT_MAX >> 3));
     return Py_BuildValue("i", byte*8 + bit);
 }
 
@@ -153,7 +261,7 @@ static PyObject *bitmatch(PyObject *self, PyObject *args)
 static PyObject *firstword(PyObject *self, PyObject *args)
 {
     unsigned char *buf = NULL;
-    int len = 0;
+    Py_ssize_t len = 0;
     uint32_t v;
 
     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
@@ -169,66 +277,66 @@ static PyObject *firstword(PyObject *self, PyObject *args)
 
 #define BLOOM2_HEADERLEN 16
 
-typedef struct {
-    uint32_t high;
-    unsigned char low;
-} bits40_t;
-
-static void to_bloom_address_bitmask4(const bits40_t *buf,
+static void to_bloom_address_bitmask4(const unsigned char *buf,
        const int nbits, uint64_t *v, unsigned char *bitmask)
 {
     int bit;
+    uint32_t high;
     uint64_t raw, mask;
 
+    memcpy(&high, buf, 4);
     mask = (1<<nbits) - 1;
-    raw = (((uint64_t)ntohl(buf->high)) << 8) | buf->low;
+    raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
     bit = (raw >> (37-nbits)) & 0x7;
     *v = (raw >> (40-nbits)) & mask;
     *bitmask = 1 << bit;
 }
 
-static void to_bloom_address_bitmask5(const uint32_t *buf,
+static void to_bloom_address_bitmask5(const unsigned char *buf,
        const int nbits, uint32_t *v, unsigned char *bitmask)
 {
     int bit;
+    uint32_t high;
     uint32_t raw, mask;
 
+    memcpy(&high, buf, 4);
     mask = (1<<nbits) - 1;
-    raw = ntohl(*buf);
+    raw = ntohl(high);
     bit = (raw >> (29-nbits)) & 0x7;
     *v = (raw >> (32-nbits)) & mask;
     *bitmask = 1 << bit;
 }
 
-#define BLOOM_SET_BIT(name, address, itype, otype) \
-static void name(unsigned char *bloom, const void *buf, const int nbits)\
+#define BLOOM_SET_BIT(name, address, otype) \
+static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
 {\
     unsigned char bitmask;\
     otype v;\
-    address((itype *)buf, nbits, &v, &bitmask);\
+    address(buf, nbits, &v, &bitmask);\
     bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
 }
-BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
-BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
+BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
+BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
 
 
-#define BLOOM_GET_BIT(name, address, itype, otype) \
-static int name(const unsigned char *bloom, const void *buf, const int nbits)\
+#define BLOOM_GET_BIT(name, address, otype) \
+static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
 {\
     unsigned char bitmask;\
     otype v;\
-    address((itype *)buf, nbits, &v, &bitmask);\
+    address(buf, nbits, &v, &bitmask);\
     return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
 }
-BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
-BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
+BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
+BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
 
 
 static PyObject *bloom_add(PyObject *self, PyObject *args)
 {
     unsigned char *sha = NULL, *bloom = NULL;
     unsigned char *end;
-    int len = 0, blen = 0, nbits = 0, k = 0;
+    Py_ssize_t len = 0, blen = 0;
+    int nbits = 0, k = 0;
 
     if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
        return NULL;
@@ -254,13 +362,14 @@ static PyObject *bloom_add(PyObject *self, PyObject *args)
        return NULL;
 
 
-    return Py_BuildValue("i", len/20);
+    return Py_BuildValue("n", len/20);
 }
 
 static PyObject *bloom_contains(PyObject *self, PyObject *args)
 {
     unsigned char *sha = NULL, *bloom = NULL;
-    int len = 0, blen = 0, nbits = 0, k = 0;
+    Py_ssize_t len = 0, blen = 0;
+    int nbits = 0, k = 0;
     unsigned char *end;
     int steps;
 
@@ -302,10 +411,13 @@ static uint32_t _extract_bits(unsigned char *buf, int nbits)
     v = (v >> (32-nbits)) & mask;
     return v;
 }
+
+
 static PyObject *extract_bits(PyObject *self, PyObject *args)
 {
     unsigned char *buf = NULL;
-    int len = 0, nbits = 0;
+    Py_ssize_t len = 0;
+    int nbits = 0;
 
     if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
        return NULL;
@@ -320,12 +432,14 @@ static PyObject *extract_bits(PyObject *self, PyObject *args)
 struct sha {
     unsigned char bytes[20];
 };
+
+
 struct idx {
     unsigned char *map;
     struct sha *cur;
     struct sha *end;
     uint32_t *cur_name;
-    long bytes;
+    Py_ssize_t bytes;
     int name_base;
 };
 
@@ -390,19 +504,25 @@ static uint32_t _get_idx_i(struct idx *idx)
 
 static PyObject *merge_into(PyObject *self, PyObject *args)
 {
-    PyObject *ilist = NULL;
+    PyObject *py_total, *ilist = NULL;
     unsigned char *fmap = NULL;
     struct sha *sha_ptr, *sha_start = NULL;
     uint32_t *table_ptr, *name_ptr, *name_start;
     struct idx **idxs = NULL;
-    int flen = 0, bits = 0, i;
-    uint32_t total, count, prefix;
+    Py_ssize_t flen = 0;
+    int bits = 0, i;
+    unsigned int total;
+    uint32_t count, prefix;
     int num_i;
     int last_i;
 
-    if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
+    if (!PyArg_ParseTuple(args, "w#iOO",
+                          &fmap, &flen, &bits, &py_total, &ilist))
        return NULL;
 
+    if (!bup_uint_from_py(&total, py_total, "total"))
+        return NULL;
+
     num_i = PyList_Size(ilist);
     idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
 
@@ -470,30 +590,41 @@ static uint64_t htonll(uint64_t value)
     return value; // already in network byte order MSB-LSB
 }
 
-#define PACK_IDX_V2_HEADERLEN 8
 #define FAN_ENTRIES 256
 
 static PyObject *write_idx(PyObject *self, PyObject *args)
 {
-    PyObject *pf = NULL, *idx = NULL;
+    char *filename = NULL;
+    PyObject *py_total, *idx = NULL;
     PyObject *part;
-    FILE *f;
     unsigned char *fmap = NULL;
-    int flen = 0;
-    uint32_t total = 0;
+    Py_ssize_t flen = 0;
+    unsigned int total = 0;
     uint32_t count;
     int i, j, ofs64_count;
     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
+    uint64_t *ofs64_ptr;
     struct sha *sha_ptr;
 
-    if (!PyArg_ParseTuple(args, "Ow#OI", &pf, &fmap, &flen, &idx, &total))
+    if (!PyArg_ParseTuple(args, "sw#OO",
+                          &filename, &fmap, &flen, &idx, &py_total))
        return NULL;
 
-    fan_ptr = (uint32_t *)&fmap[PACK_IDX_V2_HEADERLEN];
+    if (!bup_uint_from_py(&total, py_total, "total"))
+        return NULL;
+
+    if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
+        return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
+                             FAN_ENTRIES);
+
+    const char idx_header[] = "\377tOc\0\0\0\002";
+    memcpy (fmap, idx_header, sizeof(idx_header) - 1);
+
+    fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
     crc_ptr = (uint32_t *)&sha_ptr[total];
     ofs_ptr = (uint32_t *)&crc_ptr[total];
-    f = PyFile_AsFile(pf);
+    ofs64_ptr = (uint64_t *)&ofs_ptr[total];
 
     count = 0;
     ofs64_count = 0;
@@ -508,26 +639,38 @@ static PyObject *write_idx(PyObject *self, PyObject *args)
        for (j = 0; j < plen; ++j)
        {
            unsigned char *sha = NULL;
-           int sha_len = 0;
-           uint32_t crc = 0;
-           uint64_t ofs = 0;
-           if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
-                                 &sha, &sha_len, &crc, &ofs))
+           Py_ssize_t sha_len = 0;
+            PyObject *crc_py, *ofs_py;
+           unsigned int crc;
+            unsigned PY_LONG_LONG ofs_ull;
+           uint64_t ofs;
+           if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
+                                 &sha, &sha_len, &crc_py, &ofs_py))
                return NULL;
+            if(!bup_uint_from_py(&crc, crc_py, "crc"))
+                return NULL;
+            if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
+                return NULL;
+            assert(crc <= UINT32_MAX);
+            assert(ofs_ull <= UINT64_MAX);
+           ofs = ofs_ull;
            if (sha_len != sizeof(struct sha))
                return NULL;
            memcpy(sha_ptr++, sha, sizeof(struct sha));
            *crc_ptr++ = htonl(crc);
            if (ofs > 0x7fffffff)
            {
-               uint64_t nofs = htonll(ofs);
-               if (fwrite(&nofs, sizeof(uint64_t), 1, f) != 1)
-                   return PyErr_SetFromErrno(PyExc_OSError);
+                *ofs64_ptr++ = htonll(ofs);
                ofs = 0x80000000 | ofs64_count++;
            }
            *ofs_ptr++ = htonl((uint32_t)ofs);
        }
     }
+
+    int rc = msync(fmap, flen, MS_ASYNC);
+    if (rc != 0)
+       return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
+
     return PyLong_FromUnsignedLong(count);
 }
 
@@ -664,7 +807,7 @@ static PyObject *fadvise_done(PyObject *self, PyObject *args)
 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
 {
     int rc;
-    unsigned long attr;
+    unsigned int attr;
     char *path;
     int fd;
 
@@ -684,20 +827,25 @@ static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
     }
 
     close(fd);
-    return Py_BuildValue("k", attr);
+    return Py_BuildValue("I", attr);
 }
 #endif /* def BUP_HAVE_FILE_ATTRS */
 
 
+
 #ifdef BUP_HAVE_FILE_ATTRS
 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
 {
     int rc;
-    unsigned long orig_attr, attr;
+    unsigned int orig_attr, attr;
     char *path;
+    PyObject *py_attr;
     int fd;
 
-    if (!PyArg_ParseTuple(args, "sk", &path, &attr))
+    if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
+        return NULL;
+
+    if (!bup_uint_from_py(&attr, py_attr, "attr"))
         return NULL;
 
     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
@@ -734,161 +882,168 @@ static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
 #endif /* def BUP_HAVE_FILE_ATTRS */
 
 
-#if defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES) || defined(HAVE_LUTIMES)
+#ifndef HAVE_UTIMENSAT
+#ifndef HAVE_UTIMES
+#error "cannot find utimensat or utimes()"
+#endif
+#ifndef HAVE_LUTIMES
+#error "cannot find utimensat or lutimes()"
+#endif
+#endif
+
 
-static int bup_parse_xutime_args(char **path,
-                                 long *access,
-                                 long *access_ns,
-                                 long *modification,
-                                 long *modification_ns,
-                                 PyObject *self, PyObject *args)
+#define INTEGRAL_ASSIGNMENT_FITS(dest, src)                             \
+    ({                                                                  \
+        *(dest) = (src);                                                \
+        *(dest) == (src) && (*(dest) < 1) == ((src) < 1);               \
+    })
+
+
+#define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
+    ({                                                     \
+        int result = 0;                                                 \
+        *(overflow) = 0;                                                \
+        const long long lltmp = PyLong_AsLongLong(pylong);              \
+        if (lltmp == -1 && PyErr_Occurred())                            \
+        {                                                               \
+            if (PyErr_ExceptionMatches(PyExc_OverflowError))            \
+            {                                                           \
+                const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
+                if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
+                {                                                       \
+                    if (PyErr_ExceptionMatches(PyExc_OverflowError))    \
+                    {                                                   \
+                        PyErr_Clear();                                  \
+                        *(overflow) = 1;                                \
+                    }                                                   \
+                }                                                       \
+                if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp))           \
+                    result = 1;                                         \
+                else                                                    \
+                    *(overflow) = 1;                                    \
+            }                                                           \
+        }                                                               \
+        else                                                            \
+        {                                                               \
+            if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp))                \
+                result = 1;                                             \
+            else                                                        \
+                *(overflow) = 1;                                        \
+        }                                                               \
+        result;                                                         \
+        })
+
+
+#ifdef HAVE_UTIMENSAT
+
+static PyObject *bup_utimensat(PyObject *self, PyObject *args)
 {
-    if (!PyArg_ParseTuple(args, "s((ll)(ll))",
-                          path,
-                          access, access_ns,
-                          modification, modification_ns))
-        return 0;
+    int rc;
+    int fd, flag;
+    char *path;
+    PyObject *access_py, *modification_py;
+    struct timespec ts[2];
 
-    if (isnan(*access))
-    {
-        PyErr_SetString(PyExc_ValueError, "access time is NaN");
-        return 0;
-    }
-    else if (isinf(*access))
+    if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
+                          &fd,
+                          &path,
+                          &access_py, &(ts[0].tv_nsec),
+                          &modification_py, &(ts[1].tv_nsec),
+                          &flag))
+        return NULL;
+
+    int overflow;
+    if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
     {
-        PyErr_SetString(PyExc_ValueError, "access time is infinite");
-        return 0;
+        if (overflow)
+            PyErr_SetString(PyExc_ValueError,
+                            "unable to convert access time seconds for utimensat");
+        return NULL;
     }
-    else if (isnan(*modification))
+    if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
     {
-        PyErr_SetString(PyExc_ValueError, "modification time is NaN");
-        return 0;
+        if (overflow)
+            PyErr_SetString(PyExc_ValueError,
+                            "unable to convert modification time seconds for utimensat");
+        return NULL;
     }
-    else if (isinf(*modification))
-    {
-        PyErr_SetString(PyExc_ValueError, "modification time is infinite");
+    rc = utimensat(fd, path, ts, flag);
+    if (rc != 0)
+        return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
+
+    return Py_BuildValue("O", Py_None);
+}
+
+#endif /* def HAVE_UTIMENSAT */
+
+
+#if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
+
+static int bup_parse_xutimes_args(char **path,
+                                  struct timeval tv[2],
+                                  PyObject *args)
+{
+    PyObject *access_py, *modification_py;
+    long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
+
+    if (!PyArg_ParseTuple(args, "s((OL)(OL))",
+                          path,
+                          &access_py, &access_us,
+                          &modification_py, &modification_us))
         return 0;
-    }
 
-    if (isnan(*access_ns))
+    int overflow;
+    if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
     {
-        PyErr_SetString(PyExc_ValueError, "access time ns is NaN");
+        if (overflow)
+            PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
         return 0;
     }
-    else if (isinf(*access_ns))
+    if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
     {
-        PyErr_SetString(PyExc_ValueError, "access time ns is infinite");
+        PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
         return 0;
     }
-    else if (isnan(*modification_ns))
+    if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
     {
-        PyErr_SetString(PyExc_ValueError, "modification time ns is NaN");
+        if (overflow)
+            PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
         return 0;
     }
-    else if (isinf(*modification_ns))
+    if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
     {
-        PyErr_SetString(PyExc_ValueError, "modification time ns is infinite");
+        PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
         return 0;
     }
-
     return 1;
 }
 
-#endif /* defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMES)
-          || defined(HAVE_LUTIMES) */
-
-
-#ifdef HAVE_UTIMENSAT
-
-static PyObject *bup_xutime_ns(PyObject *self, PyObject *args,
-                               int follow_symlinks)
-{
-    int rc;
-    char *path;
-    long access, access_ns, modification, modification_ns;
-    struct timespec ts[2];
-
-    if (!bup_parse_xutime_args(&path, &access, &access_ns,
-                               &modification, &modification_ns,
-                               self, args))
-       return NULL;
-
-    ts[0].tv_sec = access;
-    ts[0].tv_nsec = access_ns;
-    ts[1].tv_sec = modification;
-    ts[1].tv_nsec = modification_ns;
-    rc = utimensat(AT_FDCWD, path, ts,
-                   follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
-    if (rc != 0)
-        return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
-
-    return Py_BuildValue("O", Py_None);
-}
-
-
-#define BUP_HAVE_BUP_UTIME_NS 1
-static PyObject *bup_utime_ns(PyObject *self, PyObject *args)
-{
-    return bup_xutime_ns(self, args, 1);
-}
-
-
-#define BUP_HAVE_BUP_LUTIME_NS 1
-static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
-{
-    return bup_xutime_ns(self, args, 0);
-}
-
-
-#else /* not defined(HAVE_UTIMENSAT) */
+#endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
 
 
 #ifdef HAVE_UTIMES
-#define BUP_HAVE_BUP_UTIME_NS 1
-static PyObject *bup_utime_ns(PyObject *self, PyObject *args)
+static PyObject *bup_utimes(PyObject *self, PyObject *args)
 {
-    int rc;
     char *path;
-    long access, access_ns, modification, modification_ns;
     struct timeval tv[2];
-
-    if (!bup_parse_xutime_args(&path, &access, &access_ns,
-                               &modification, &modification_ns,
-                               self, args))
-       return NULL;
-
-    tv[0].tv_sec = access;
-    tv[0].tv_usec = access_ns / 1000;
-    tv[1].tv_sec = modification;
-    tv[1].tv_usec = modification_ns / 1000;
-    rc = utimes(path, tv);
+    if (!bup_parse_xutimes_args(&path, tv, args))
+        return NULL;
+    int rc = utimes(path, tv);
     if (rc != 0)
         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
-
     return Py_BuildValue("O", Py_None);
 }
 #endif /* def HAVE_UTIMES */
 
 
 #ifdef HAVE_LUTIMES
-#define BUP_HAVE_BUP_LUTIME_NS 1
-static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
+static PyObject *bup_lutimes(PyObject *self, PyObject *args)
 {
-    int rc;
     char *path;
-    long access, access_ns, modification, modification_ns;
     struct timeval tv[2];
-
-    if (!bup_parse_xutime_args(&path, &access, &access_ns,
-                               &modification, &modification_ns,
-                               self, args))
-       return NULL;
-
-    tv[0].tv_sec = access;
-    tv[0].tv_usec = access_ns / 1000;
-    tv[1].tv_sec = modification;
-    tv[1].tv_usec = modification_ns / 1000;
-    rc = lutimes(path, tv);
+    if (!bup_parse_xutimes_args(&path, tv, args))
+        return NULL;
+    int rc = lutimes(path, tv);
     if (rc != 0)
         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
 
@@ -897,9 +1052,6 @@ static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
 #endif /* def HAVE_LUTIMES */
 
 
-#endif /* not defined(HAVE_UTIMENSAT) */
-
-
 #ifdef HAVE_STAT_ST_ATIM
 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
@@ -915,46 +1067,35 @@ static PyObject *bup_lutime_ns(PyObject *self, PyObject *args)
 #endif
 
 
-static PyObject *stat_struct_to_py(const struct stat *st)
-{
-    long atime_ns = BUP_STAT_ATIME_NS(st);
-    long mtime_ns = BUP_STAT_MTIME_NS(st);
-    long ctime_ns = BUP_STAT_CTIME_NS(st);
-
-    /* Enforce the current timespec nanosecond range expectations. */
-    if (atime_ns < 0 || atime_ns > 999999999)
-    {
-        PyErr_SetString(PyExc_ValueError, "invalid atime timespec nanoseconds");
-        return NULL;
-    }
-    if (mtime_ns < 0 || mtime_ns > 999999999)
-    {
-        PyErr_SetString(PyExc_ValueError, "invalid mtime timespec nanoseconds");
-        return NULL;
-    }
-    if (ctime_ns < 0 || ctime_ns > 999999999)
-    {
-        PyErr_SetString(PyExc_ValueError, "invalid ctime timespec nanoseconds");
-        return NULL;
-    }
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
 
-    return Py_BuildValue("kkkkkkkk(Ll)(Ll)(Ll)",
-                         (unsigned long) st->st_mode,
-                         (unsigned long) st->st_ino,
-                         (unsigned long) st->st_dev,
-                         (unsigned long) st->st_nlink,
-                         (unsigned long) st->st_uid,
-                         (unsigned long) st->st_gid,
-                         (unsigned long) st->st_rdev,
-                         (unsigned long) st->st_size,
-                         (long long) st->st_atime,
-                         (long) atime_ns,
-                         (long long) st->st_mtime,
-                         (long) mtime_ns,
-                         (long long) st->st_ctime,
-                         (long) ctime_ns);
+static PyObject *stat_struct_to_py(const struct stat *st,
+                                   const char *filename,
+                                   int fd)
+{
+    // We can check the known (via POSIX) signed and unsigned types at
+    // compile time, but not (easily) the unspecified types, so handle
+    // those via INTEGER_TO_PY().  Assumes ns values will fit in a
+    // long.
+    return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
+                         INTEGER_TO_PY(st->st_mode),
+                         (unsigned PY_LONG_LONG) st->st_ino,
+                         INTEGER_TO_PY(st->st_dev),
+                         INTEGER_TO_PY(st->st_nlink),
+                         INTEGER_TO_PY(st->st_uid),
+                         INTEGER_TO_PY(st->st_gid),
+                         INTEGER_TO_PY(st->st_rdev),
+                         (PY_LONG_LONG) st->st_size,
+                         INTEGER_TO_PY(st->st_atime),
+                         (long) BUP_STAT_ATIME_NS(st),
+                         INTEGER_TO_PY(st->st_mtime),
+                         (long) BUP_STAT_MTIME_NS(st),
+                         INTEGER_TO_PY(st->st_ctime),
+                         (long) BUP_STAT_CTIME_NS(st));
 }
 
+#pragma clang diagnostic pop  // ignored "-Wtautological-compare"
 
 static PyObject *bup_stat(PyObject *self, PyObject *args)
 {
@@ -968,7 +1109,7 @@ static PyObject *bup_stat(PyObject *self, PyObject *args)
     rc = stat(filename, &st);
     if (rc != 0)
         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
-    return stat_struct_to_py(&st);
+    return stat_struct_to_py(&st, filename, 0);
 }
 
 
@@ -984,7 +1125,7 @@ static PyObject *bup_lstat(PyObject *self, PyObject *args)
     rc = lstat(filename, &st);
     if (rc != 0)
         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
-    return stat_struct_to_py(&st);
+    return stat_struct_to_py(&st, filename, 0);
 }
 
 
@@ -999,7 +1140,7 @@ static PyObject *bup_fstat(PyObject *self, PyObject *args)
     rc = fstat(fd, &st);
     if (rc != 0)
         return PyErr_SetFromErrno(PyExc_OSError);
-    return stat_struct_to_py(&st);
+    return stat_struct_to_py(&st, NULL, fd);
 }
 
 
@@ -1040,13 +1181,17 @@ static PyMethodDef helper_methods[] = {
     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
       "Set the Linux attributes for the given file." },
 #endif
-#ifdef BUP_HAVE_BUP_UTIME_NS
-    { "bup_utime_ns", bup_utime_ns, METH_VARARGS,
-      "Change path timestamps with up to nanosecond precision." },
+#ifdef HAVE_UTIMENSAT
+    { "bup_utimensat", bup_utimensat, METH_VARARGS,
+      "Change path timestamps with nanosecond precision (POSIX)." },
+#endif
+#ifdef HAVE_UTIMES
+    { "bup_utimes", bup_utimes, METH_VARARGS,
+      "Change path timestamps with microsecond precision." },
 #endif
-#ifdef BUP_HAVE_BUP_LUTIME_NS
-    { "bup_lutime_ns", bup_lutime_ns, METH_VARARGS,
-      "Change path timestamps with up to nanosecond precision;"
+#ifdef HAVE_LUTIMES
+    { "bup_lutimes", bup_lutimes, METH_VARARGS,
+      "Change path timestamps with microsecond precision;"
       " don't follow symlinks." },
 #endif
     { "stat", bup_stat, METH_VARARGS,
@@ -1061,10 +1206,52 @@ static PyMethodDef helper_methods[] = {
 
 PyMODINIT_FUNC init_helpers(void)
 {
+    // FIXME: migrate these tests to configure.  Check against the
+    // type we're going to use when passing to python.  Other stat
+    // types are tested at runtime.
+    assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
+    assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
+    assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
+    assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
+    // Just be sure (relevant when passing timestamps back to Python above).
+    assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
+    assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
+
     char *e;
     PyObject *m = Py_InitModule("_helpers", helper_methods);
     if (m == NULL)
         return;
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
+#ifdef HAVE_UTIMENSAT
+    {
+        PyObject *value;
+        value = INTEGER_TO_PY(AT_FDCWD);
+        PyObject_SetAttrString(m, "AT_FDCWD", value);
+        Py_DECREF(value);
+        value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
+        PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
+        Py_DECREF(value);
+        value = INTEGER_TO_PY(UTIME_NOW);
+        PyObject_SetAttrString(m, "UTIME_NOW", value);
+        Py_DECREF(value);
+    }
+#endif
+    {
+        PyObject *value;
+        const long arg_max = sysconf(_SC_ARG_MAX);
+        if (arg_max == -1)
+        {
+            fprintf(stderr, "Cannot find SC_ARG_MAX, please report a bug.\n");
+            exit(1);
+        }
+        value = INTEGER_TO_PY(arg_max);
+        PyObject_SetAttrString(m, "SC_ARG_MAX", value);
+        Py_DECREF(value);
+    }
+#pragma clang diagnostic pop  // ignored "-Wtautological-compare"
+
     e = getenv("BUP_FORCE_TTY");
     istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
     unpythonize_argv();