1 #define _LARGEFILE64_SOURCE 1
2 #define PY_SSIZE_T_CLEAN 1
4 #include "../../config/config.h"
6 // According to Python, its header has to go first:
7 // http://docs.python.org/2/c-api/intro.html#include-files
13 #include <arpa/inet.h>
20 #ifdef HAVE_SYS_MMAN_H
23 #ifdef HAVE_SYS_TYPES_H
24 #include <sys/types.h>
26 #ifdef HAVE_SYS_STAT_H
32 #ifdef HAVE_SYS_TIME_H
36 #ifdef HAVE_LINUX_FS_H
39 #ifdef HAVE_SYS_IOCTL_H
40 #include <sys/ioctl.h>
43 #ifdef HAVE_TM_TM_GMTOFF
49 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
50 #define BUP_HAVE_FILE_ATTRS 1
54 * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
55 * pretend we don't have it.
57 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
62 // Of course, this assumes it's a bitfield value.
67 typedef unsigned char byte;
74 #if PY_MAJOR_VERSION < 3
76 # define get_state(x) (&state)
77 # define cstr_argf "s"
79 # define get_state(x) ((state_t *) PyModule_GetState(x))
80 # define cstr_argf "y"
81 #endif // PY_MAJOR_VERSION >= 3
85 // This function should technically be macro'd out if it's going to be used
86 // more than ocasionally. As of this writing, it'll actually never be called
87 // in real world bup scenarios (because our packs are < MAX_INT bytes).
88 static uint64_t htonll(uint64_t value)
90 static const int endian_test = 42;
92 if (*(char *)&endian_test == endian_test) // LSB-MSB
93 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
94 return value; // already in network byte order MSB-LSB
100 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
103 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
106 // Disabling sign-compare here should be fine since we're explicitly
107 // checking for a sign mismatch, i.e. if the signs don't match, then
108 // it doesn't matter what the value comparison says.
109 // FIXME: ... so should we reverse the order?
110 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
112 _Pragma("GCC diagnostic push"); \
113 _Pragma("GCC diagnostic ignored \"-Wsign-compare\""); \
115 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
116 _Pragma("GCC diagnostic pop"); \
121 // At the moment any code that calls INTGER_TO_PY() will have to
122 // disable -Wtautological-compare for clang. See below.
124 #define INTEGER_TO_PY(x) \
125 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
129 #if PY_MAJOR_VERSION < 3
130 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
133 const long tmp = PyInt_AsLong(py);
134 if (tmp == -1 && PyErr_Occurred())
136 if (PyErr_ExceptionMatches(PyExc_OverflowError))
137 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
143 PyErr_Format(PyExc_OverflowError,
144 "negative %s cannot be converted to unsigned long", name);
153 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
155 #if PY_MAJOR_VERSION < 3
157 return bup_ulong_from_pyint(x, py, name);
160 if (!PyLong_Check(py))
162 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
166 const unsigned long tmp = PyLong_AsUnsignedLong(py);
167 if (PyErr_Occurred())
169 if (PyErr_ExceptionMatches(PyExc_OverflowError))
170 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
179 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
182 if (!bup_ulong_from_py(&tmp, py, name))
187 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
194 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
197 #if PY_MAJOR_VERSION < 3
201 if (bup_ulong_from_pyint(&tmp, py, name))
210 if (!PyLong_Check(py))
212 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
216 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
217 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
219 if (PyErr_ExceptionMatches(PyExc_OverflowError))
220 PyErr_Format(PyExc_OverflowError,
221 "%s too big for unsigned long long", name);
229 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
231 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
232 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
235 Py_ssize_t s1_len, s2_len;
236 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
238 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
240 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
241 const int cmp = memcmp(s1, s2, n);
243 return PyLong_FromLong(cmp);
244 if (s1_len == s2_len)
245 return PyLong_FromLong(0);;
246 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
250 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
251 #if __WIN32__ || __CYGWIN__
253 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
254 static void unpythonize_argv(void) { }
256 #else // not __WIN32__
258 // For some reason this isn't declared in Python.h
259 extern void Py_GetArgcArgv(int *argc, char ***argv);
261 static void unpythonize_argv(void)
266 Py_GetArgcArgv(&argc, &argv);
268 for (i = 0; i < argc-1; i++)
270 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
272 // The argv block doesn't work the way we expected; it's unsafe
278 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
280 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
284 p = strrchr(argv[1], '/');
290 memmove(argv[0], p, len);
291 memset(arge - diff, 0, diff);
292 for (i = 0; i < argc; i++)
293 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
298 #endif // not __WIN32__ or __CYGWIN__
301 static int write_all(int fd, const void *buf, const size_t count)
304 while (written < count)
306 const ssize_t rc = write(fd, buf + written, count - written);
315 static int uadd(unsigned long long *dest,
316 const unsigned long long x,
317 const unsigned long long y)
319 const unsigned long long result = x + y;
320 if (result < x || result < y)
327 static PyObject *append_sparse_region(const int fd, unsigned long long n)
332 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
334 const off_t off = lseek(fd, new_off, SEEK_CUR);
335 if (off == (off_t) -1)
336 return PyErr_SetFromErrno(PyExc_IOError);
343 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
345 unsigned long long prev_pending,
346 const unsigned long long count)
348 // Add count additional sparse zeros to prev_pending and store the
349 // result in new_pending, or if the total won't fit in
350 // new_pending, write some of the zeros to fd sparsely, and store
351 // the remaining sum in new_pending.
352 if (!uadd(new_pending, prev_pending, count))
354 PyObject *err = append_sparse_region(fd, prev_pending);
357 *new_pending = count;
363 static byte* find_not_zero(const byte * const start, const byte * const end)
365 // Return a pointer to first non-zero byte between start and end,
366 // or end if there isn't one.
367 assert(start <= end);
368 const unsigned char *cur = start;
369 while (cur < end && *cur == 0)
375 static byte* find_trailing_zeros(const byte * const start,
376 const byte * const end)
378 // Return a pointer to the start of any trailing run of zeros, or
379 // end if there isn't one.
380 assert(start <= end);
383 const byte * cur = end;
384 while (cur > start && *--cur == 0) {}
388 return (byte *) (cur + 1);
392 static byte *find_non_sparse_end(const byte * const start,
393 const byte * const end,
394 const ptrdiff_t min_len)
396 // Return the first pointer to a min_len sparse block in [start,
397 // end) if there is one, otherwise a pointer to the start of any
398 // trailing run of zeros. If there are no trailing zeros, return
404 // Probe in min_len jumps, searching backward from the jump
405 // destination for a non-zero byte. If such a byte is found, move
406 // just past it and try again.
407 const byte *candidate = start;
408 // End of any run of zeros, starting at candidate, that we've already seen
409 const byte *end_of_known_zeros = candidate;
410 while (end - candidate >= min_len) // Handle all min_len candidate blocks
412 const byte * const probe_end = candidate + min_len;
413 const byte * const trailing_zeros =
414 find_trailing_zeros(end_of_known_zeros, probe_end);
415 if (trailing_zeros == probe_end)
416 end_of_known_zeros = candidate = probe_end;
417 else if (trailing_zeros == end_of_known_zeros)
419 assert(candidate >= start);
420 assert(candidate <= end);
421 assert(*candidate == 0);
422 return (byte *) candidate;
426 candidate = trailing_zeros;
427 end_of_known_zeros = probe_end;
431 if (candidate == end)
434 // No min_len sparse run found, search backward from end
435 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
438 if (trailing_zeros == end_of_known_zeros)
440 assert(candidate >= start);
441 assert(candidate < end);
442 assert(*candidate == 0);
443 assert(end - candidate < min_len);
444 return (byte *) candidate;
447 if (trailing_zeros == end)
449 assert(*(end - 1) != 0);
453 assert(end - trailing_zeros < min_len);
454 assert(trailing_zeros >= start);
455 assert(trailing_zeros < end);
456 assert(*trailing_zeros == 0);
457 return (byte *) trailing_zeros;
461 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
464 unsigned char *buf = NULL;
466 PyObject *py_min_sparse_len, *py_prev_sparse_len;
467 if (!PyArg_ParseTuple(args, "it#OO",
468 &fd, &buf, &sbuf_len,
469 &py_min_sparse_len, &py_prev_sparse_len))
471 ptrdiff_t min_sparse_len;
472 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
473 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
475 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
476 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
477 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
480 return PyErr_Format(PyExc_ValueError, "negative bufer length");
481 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
482 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
484 const byte * block = buf; // Start of pending block
485 const byte * const end = buf + buf_len;
486 unsigned long long zeros = prev_sparse_len;
489 assert(block <= end);
491 return PyLong_FromUnsignedLongLong(zeros);
495 // Look for the end of block, i.e. the next sparse run of
496 // at least min_sparse_len zeros, or the end of the
498 const byte * const probe = find_non_sparse_end(block + 1, end,
500 // Either at end of block, or end of non-sparse; write pending data
501 PyObject *err = append_sparse_region(fd, zeros);
504 int rc = write_all(fd, block, probe - block);
506 return PyErr_SetFromErrno(PyExc_IOError);
508 if (end - probe < min_sparse_len)
511 zeros = min_sparse_len;
512 block = probe + zeros;
516 // Should be in the first loop iteration, a sparse run of
517 // zeros, or nearly at the end of the block (within
519 const byte * const zeros_end = find_not_zero(block, end);
520 PyObject *err = record_sparse_zeros(&zeros, fd,
521 zeros, zeros_end - block);
524 assert(block <= zeros_end);
531 static PyObject *selftest(PyObject *self, PyObject *args)
533 if (!PyArg_ParseTuple(args, ""))
536 return Py_BuildValue("i", !bupsplit_selftest());
540 static PyObject *blobbits(PyObject *self, PyObject *args)
542 if (!PyArg_ParseTuple(args, ""))
544 return Py_BuildValue("i", BUP_BLOBBITS);
548 static PyObject *splitbuf(PyObject *self, PyObject *args)
550 // We stick to buffers in python 2 because they appear to be
551 // substantially smaller than memoryviews, and because
552 // zlib.compress() in python 2 can't accept a memoryview
553 // (cf. hashsplit.py).
554 int out = 0, bits = -1;
555 if (PY_MAJOR_VERSION > 2)
558 if (!PyArg_ParseTuple(args, "y*", &buf))
560 assert(buf.len <= INT_MAX);
561 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
562 PyBuffer_Release(&buf);
566 unsigned char *buf = NULL;
568 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
570 assert(len <= INT_MAX);
571 out = bupsplit_find_ofs(buf, len, &bits);
573 if (out) assert(bits >= BUP_BLOBBITS);
574 return Py_BuildValue("ii", out, bits);
578 static PyObject *bitmatch(PyObject *self, PyObject *args)
580 unsigned char *buf1 = NULL, *buf2 = NULL;
581 Py_ssize_t len1 = 0, len2 = 0;
585 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
589 for (byte = 0; byte < len1 && byte < len2; byte++)
591 int b1 = buf1[byte], b2 = buf2[byte];
594 for (bit = 0; bit < 8; bit++)
595 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
601 assert(byte <= (INT_MAX >> 3));
602 return Py_BuildValue("i", byte*8 + bit);
606 static PyObject *firstword(PyObject *self, PyObject *args)
608 unsigned char *buf = NULL;
612 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
618 v = ntohl(*(uint32_t *)buf);
619 return PyLong_FromUnsignedLong(v);
623 #define BLOOM2_HEADERLEN 16
625 static void to_bloom_address_bitmask4(const unsigned char *buf,
626 const int nbits, uint64_t *v, unsigned char *bitmask)
632 memcpy(&high, buf, 4);
633 mask = (1<<nbits) - 1;
634 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
635 bit = (raw >> (37-nbits)) & 0x7;
636 *v = (raw >> (40-nbits)) & mask;
640 static void to_bloom_address_bitmask5(const unsigned char *buf,
641 const int nbits, uint32_t *v, unsigned char *bitmask)
647 memcpy(&high, buf, 4);
648 mask = (1<<nbits) - 1;
650 bit = (raw >> (29-nbits)) & 0x7;
651 *v = (raw >> (32-nbits)) & mask;
655 #define BLOOM_SET_BIT(name, address, otype) \
656 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
658 unsigned char bitmask;\
660 address(buf, nbits, &v, &bitmask);\
661 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
663 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
664 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
667 #define BLOOM_GET_BIT(name, address, otype) \
668 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
670 unsigned char bitmask;\
672 address(buf, nbits, &v, &bitmask);\
673 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
675 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
676 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
679 static PyObject *bloom_add(PyObject *self, PyObject *args)
681 unsigned char *sha = NULL, *bloom = NULL;
683 Py_ssize_t len = 0, blen = 0;
684 int nbits = 0, k = 0;
686 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
689 if (blen < 16+(1<<nbits) || len % 20 != 0)
696 for (end = sha + len; sha < end; sha += 20/k)
697 bloom_set_bit5(bloom, sha, nbits);
703 for (end = sha + len; sha < end; sha += 20/k)
704 bloom_set_bit4(bloom, sha, nbits);
710 return Py_BuildValue("n", len/20);
713 static PyObject *bloom_contains(PyObject *self, PyObject *args)
715 unsigned char *sha = NULL, *bloom = NULL;
716 Py_ssize_t len = 0, blen = 0;
717 int nbits = 0, k = 0;
721 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
731 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
732 if (!bloom_get_bit5(bloom, sha, nbits))
733 return Py_BuildValue("Oi", Py_None, steps);
739 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
740 if (!bloom_get_bit4(bloom, sha, nbits))
741 return Py_BuildValue("Oi", Py_None, steps);
746 return Py_BuildValue("ii", 1, k);
750 static uint32_t _extract_bits(unsigned char *buf, int nbits)
754 mask = (1<<nbits) - 1;
755 v = ntohl(*(uint32_t *)buf);
756 v = (v >> (32-nbits)) & mask;
761 static PyObject *extract_bits(PyObject *self, PyObject *args)
763 unsigned char *buf = NULL;
767 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
773 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
778 unsigned char bytes[20];
781 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
783 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
796 static void _fix_idx_order(struct idx **idxs, int *last_i)
799 int low, mid, high, c = 0;
802 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
804 idxs[*last_i] = NULL;
817 mid = (low + high) / 2;
818 c = _cmp_sha(idx->cur, idxs[mid]->cur);
830 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
835 static uint32_t _get_idx_i(struct idx *idx)
837 if (idx->cur_name == NULL)
838 return idx->name_base;
839 return ntohl(*idx->cur_name) + idx->name_base;
842 #define MIDX4_HEADERLEN 12
844 static PyObject *merge_into(PyObject *self, PyObject *args)
846 PyObject *py_total, *ilist = NULL;
847 unsigned char *fmap = NULL;
848 struct sha *sha_ptr, *sha_start = NULL;
849 uint32_t *table_ptr, *name_ptr, *name_start;
850 struct idx **idxs = NULL;
854 uint32_t count, prefix;
858 if (!PyArg_ParseTuple(args, "w#iOO",
859 &fmap, &flen, &bits, &py_total, &ilist))
862 if (!bup_uint_from_py(&total, py_total, "total"))
865 num_i = PyList_Size(ilist);
866 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
868 for (i = 0; i < num_i; i++)
870 long len, sha_ofs, name_map_ofs;
871 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
872 PyObject *itup = PyList_GetItem(ilist, i);
873 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
874 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
876 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
877 idxs[i]->end = &idxs[i]->cur[len];
879 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
881 idxs[i]->cur_name = NULL;
883 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
884 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
885 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
894 if (count % 102424 == 0 && get_state(self)->istty2)
895 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
896 count*100.0/total, count, total);
898 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
899 while (prefix < new_prefix)
900 table_ptr[prefix++] = htonl(count);
901 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
902 *name_ptr++ = htonl(_get_idx_i(idx));
904 if (idx->cur_name != NULL)
906 _fix_idx_order(idxs, &last_i);
909 while (prefix < ((uint32_t) 1 << bits))
910 table_ptr[prefix++] = htonl(count);
911 assert(count == total);
912 assert(prefix == ((uint32_t) 1 << bits));
913 assert(sha_ptr == sha_start+count);
914 assert(name_ptr == name_start+count);
917 return PyLong_FromUnsignedLong(count);
920 #define FAN_ENTRIES 256
922 static PyObject *write_idx(PyObject *self, PyObject *args)
924 char *filename = NULL;
925 PyObject *py_total, *idx = NULL;
927 unsigned char *fmap = NULL;
929 unsigned int total = 0;
931 int i, j, ofs64_count;
932 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
936 if (!PyArg_ParseTuple(args, "sw#OO",
937 &filename, &fmap, &flen, &idx, &py_total))
940 if (!bup_uint_from_py(&total, py_total, "total"))
943 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
944 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
947 const char idx_header[] = "\377tOc\0\0\0\002";
948 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
950 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
951 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
952 crc_ptr = (uint32_t *)&sha_ptr[total];
953 ofs_ptr = (uint32_t *)&crc_ptr[total];
954 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
958 for (i = 0; i < FAN_ENTRIES; ++i)
961 part = PyList_GET_ITEM(idx, i);
963 plen = PyList_GET_SIZE(part);
965 *fan_ptr++ = htonl(count);
966 for (j = 0; j < plen; ++j)
968 unsigned char *sha = NULL;
969 Py_ssize_t sha_len = 0;
970 PyObject *crc_py, *ofs_py;
972 unsigned PY_LONG_LONG ofs_ull;
974 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
975 &sha, &sha_len, &crc_py, &ofs_py))
977 if(!bup_uint_from_py(&crc, crc_py, "crc"))
979 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
981 assert(crc <= UINT32_MAX);
982 assert(ofs_ull <= UINT64_MAX);
984 if (sha_len != sizeof(struct sha))
986 memcpy(sha_ptr++, sha, sizeof(struct sha));
987 *crc_ptr++ = htonl(crc);
988 if (ofs > 0x7fffffff)
990 *ofs64_ptr++ = htonll(ofs);
991 ofs = 0x80000000 | ofs64_count++;
993 *ofs_ptr++ = htonl((uint32_t)ofs);
997 int rc = msync(fmap, flen, MS_ASYNC);
999 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1001 return PyLong_FromUnsignedLong(count);
1005 // I would have made this a lower-level function that just fills in a buffer
1006 // with random values, and then written those values from python. But that's
1007 // about 20% slower in my tests, and since we typically generate random
1008 // numbers for benchmarking other parts of bup, any slowness in generating
1009 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1010 // pseudorandom bytes much except for this anyway.
1011 static PyObject *write_random(PyObject *self, PyObject *args)
1013 uint32_t buf[1024/4];
1014 int fd = -1, seed = 0, verbose = 0;
1016 long long len = 0, kbytes = 0, written = 0;
1018 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1023 for (kbytes = 0; kbytes < len/1024; kbytes++)
1026 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1028 ret = write(fd, buf, sizeof(buf));
1032 if (ret < (int)sizeof(buf))
1034 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1035 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1038 // handle non-multiples of 1024
1042 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1044 ret = write(fd, buf, len % 1024);
1050 if (kbytes/1024 > 0)
1051 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1052 return Py_BuildValue("L", written);
1056 static PyObject *random_sha(PyObject *self, PyObject *args)
1058 static int seeded = 0;
1059 uint32_t shabuf[20/4];
1064 assert(sizeof(shabuf) == 20);
1065 srandom(time(NULL));
1069 if (!PyArg_ParseTuple(args, ""))
1072 memset(shabuf, 0, sizeof(shabuf));
1073 for (i=0; i < 20/4; i++)
1074 shabuf[i] = random();
1075 return Py_BuildValue("s#", shabuf, 20);
1079 static int _open_noatime(const char *filename, int attrs)
1081 int attrs_noatime, fd;
1084 attrs |= O_NOFOLLOW;
1087 attrs |= O_LARGEFILE;
1089 attrs_noatime = attrs;
1091 attrs_noatime |= O_NOATIME;
1093 fd = open(filename, attrs_noatime);
1094 if (fd < 0 && errno == EPERM)
1096 // older Linux kernels would return EPERM if you used O_NOATIME
1097 // and weren't the file's owner. This pointless restriction was
1098 // relaxed eventually, but we have to handle it anyway.
1099 // (VERY old kernels didn't recognized O_NOATIME, but they would
1100 // just harmlessly ignore it, so this branch won't trigger)
1101 fd = open(filename, attrs);
1107 static PyObject *open_noatime(PyObject *self, PyObject *args)
1109 char *filename = NULL;
1111 if (!PyArg_ParseTuple(args, "s", &filename))
1113 fd = _open_noatime(filename, 0);
1115 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1116 return Py_BuildValue("i", fd);
1120 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1123 long long llofs, lllen = 0;
1124 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1127 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1128 return PyErr_Format(PyExc_OverflowError,
1129 "fadvise offset overflows off_t");
1130 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1131 return PyErr_Format(PyExc_OverflowError,
1132 "fadvise length overflows off_t");
1133 #ifdef POSIX_FADV_DONTNEED
1134 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1136 return Py_BuildValue("");
1140 // Currently the Linux kernel and FUSE disagree over the type for
1141 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1142 // but FUSE chose long (matching the declaration in linux/fs.h). So
1143 // if you use int, and then traverse a FUSE filesystem, you may
1144 // corrupt the stack. But if you use long, then you may get invalid
1145 // results on big-endian systems.
1147 // For now, we just use long, and then disable Linux attrs entirely
1148 // (with a warning) in helpers.py on systems that are affected.
1150 #ifdef BUP_HAVE_FILE_ATTRS
1151 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1158 if (!PyArg_ParseTuple(args, "s", &path))
1161 fd = _open_noatime(path, O_NONBLOCK);
1163 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1165 attr = 0; // Handle int/long mismatch (see above)
1166 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1170 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1173 assert(attr <= UINT_MAX); // Kernel type is actually int
1174 return PyLong_FromUnsignedLong(attr);
1176 #endif /* def BUP_HAVE_FILE_ATTRS */
1180 #ifdef BUP_HAVE_FILE_ATTRS
1181 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1184 unsigned long orig_attr;
1190 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1193 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1196 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1198 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1200 // Restrict attr to modifiable flags acdeijstuADST -- see
1201 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1202 // in pf.c flags_array[].
1203 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1204 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1205 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1206 | FS_TOPDIR_FL | FS_NOCOW_FL;
1208 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1209 orig_attr = 0; // Handle int/long mismatch (see above)
1210 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1214 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1216 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1217 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1219 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1223 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1227 return Py_BuildValue("O", Py_None);
1229 #endif /* def BUP_HAVE_FILE_ATTRS */
1232 #ifndef HAVE_UTIMENSAT
1234 #error "cannot find utimensat or utimes()"
1236 #ifndef HAVE_LUTIMES
1237 #error "cannot find utimensat or lutimes()"
1241 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1245 const long long lltmp = PyLong_AsLongLong(pylong); \
1246 if (lltmp == -1 && PyErr_Occurred()) \
1248 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1250 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1251 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1253 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1259 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1267 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1276 #ifdef HAVE_UTIMENSAT
1278 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1283 PyObject *access_py, *modification_py;
1284 struct timespec ts[2];
1286 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1289 &access_py, &(ts[0].tv_nsec),
1290 &modification_py, &(ts[1].tv_nsec),
1295 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1298 PyErr_SetString(PyExc_ValueError,
1299 "unable to convert access time seconds for utimensat");
1302 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1305 PyErr_SetString(PyExc_ValueError,
1306 "unable to convert modification time seconds for utimensat");
1309 rc = utimensat(fd, path, ts, flag);
1311 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1313 return Py_BuildValue("O", Py_None);
1316 #endif /* def HAVE_UTIMENSAT */
1319 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1321 static int bup_parse_xutimes_args(char **path,
1322 struct timeval tv[2],
1325 PyObject *access_py, *modification_py;
1326 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1328 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1330 &access_py, &access_us,
1331 &modification_py, &modification_us))
1335 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1338 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1341 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1343 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1346 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1349 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1352 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1354 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1360 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1364 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1367 struct timeval tv[2];
1368 if (!bup_parse_xutimes_args(&path, tv, args))
1370 int rc = utimes(path, tv);
1372 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1373 return Py_BuildValue("O", Py_None);
1375 #endif /* def HAVE_UTIMES */
1379 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1382 struct timeval tv[2];
1383 if (!bup_parse_xutimes_args(&path, tv, args))
1385 int rc = lutimes(path, tv);
1387 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1389 return Py_BuildValue("O", Py_None);
1391 #endif /* def HAVE_LUTIMES */
1394 #ifdef HAVE_STAT_ST_ATIM
1395 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1396 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1397 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1398 #elif defined HAVE_STAT_ST_ATIMENSEC
1399 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1400 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1401 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1403 # define BUP_STAT_ATIME_NS(st) 0
1404 # define BUP_STAT_MTIME_NS(st) 0
1405 # define BUP_STAT_CTIME_NS(st) 0
1409 #pragma clang diagnostic push
1410 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1412 static PyObject *stat_struct_to_py(const struct stat *st,
1413 const char *filename,
1416 // We can check the known (via POSIX) signed and unsigned types at
1417 // compile time, but not (easily) the unspecified types, so handle
1418 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1420 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1421 INTEGER_TO_PY(st->st_mode),
1422 (unsigned PY_LONG_LONG) st->st_ino,
1423 INTEGER_TO_PY(st->st_dev),
1424 INTEGER_TO_PY(st->st_nlink),
1425 INTEGER_TO_PY(st->st_uid),
1426 INTEGER_TO_PY(st->st_gid),
1427 INTEGER_TO_PY(st->st_rdev),
1428 (PY_LONG_LONG) st->st_size,
1429 INTEGER_TO_PY(st->st_atime),
1430 (long) BUP_STAT_ATIME_NS(st),
1431 INTEGER_TO_PY(st->st_mtime),
1432 (long) BUP_STAT_MTIME_NS(st),
1433 INTEGER_TO_PY(st->st_ctime),
1434 (long) BUP_STAT_CTIME_NS(st));
1437 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1439 static PyObject *bup_stat(PyObject *self, PyObject *args)
1444 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1448 rc = stat(filename, &st);
1450 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1451 return stat_struct_to_py(&st, filename, 0);
1455 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1460 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1464 rc = lstat(filename, &st);
1466 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1467 return stat_struct_to_py(&st, filename, 0);
1471 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1475 if (!PyArg_ParseTuple(args, "i", &fd))
1479 rc = fstat(fd, &st);
1481 return PyErr_SetFromErrno(PyExc_OSError);
1482 return stat_struct_to_py(&st, NULL, fd);
1486 #ifdef HAVE_TM_TM_GMTOFF
1487 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1491 if (!PyArg_ParseTuple(args, "L", &lltime))
1493 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1494 return PyErr_Format(PyExc_OverflowError, "time value too large");
1498 if(localtime_r(&ttime, &tm) == NULL)
1499 return PyErr_SetFromErrno(PyExc_OSError);
1501 // Match the Python struct_time values.
1502 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1503 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1504 tm.tm_hour, tm.tm_min, tm.tm_sec,
1505 tm.tm_wday, tm.tm_yday + 1,
1506 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1508 #endif /* def HAVE_TM_TM_GMTOFF */
1511 #ifdef BUP_MINCORE_BUF_TYPE
1512 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1514 Py_buffer src, dest;
1515 PyObject *py_src_n, *py_src_off, *py_dest_off;
1517 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1518 &src, &py_src_n, &py_src_off,
1519 &dest, &py_dest_off))
1522 PyObject *result = NULL;
1524 unsigned long long src_n, src_off, dest_off;
1525 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1526 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1527 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1528 goto clean_and_return;
1530 unsigned long long src_region_end;
1531 if (!uadd(&src_region_end, src_off, src_n)) {
1532 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1533 goto clean_and_return;
1535 assert(src.len >= 0);
1536 if (src_region_end > (unsigned long long) src.len) {
1537 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1538 goto clean_and_return;
1541 unsigned long long dest_size;
1542 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1543 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1544 goto clean_and_return;
1546 if (dest_off > dest_size) {
1547 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1548 goto clean_and_return;
1552 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1553 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1554 goto clean_and_return;
1556 int rc = mincore((void *)(src.buf + src_off), src_n,
1557 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1559 result = PyErr_SetFromErrno(PyExc_OSError);
1560 goto clean_and_return;
1562 result = Py_BuildValue("O", Py_None);
1565 PyBuffer_Release(&src);
1566 PyBuffer_Release(&dest);
1569 #endif /* def BUP_MINCORE_BUF_TYPE */
1572 static PyMethodDef helper_methods[] = {
1573 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1574 "Write buf excepting zeros at the end. Return trailing zero count." },
1575 { "selftest", selftest, METH_VARARGS,
1576 "Check that the rolling checksum rolls correctly (for unit tests)." },
1577 { "blobbits", blobbits, METH_VARARGS,
1578 "Return the number of bits in the rolling checksum." },
1579 { "splitbuf", splitbuf, METH_VARARGS,
1580 "Split a list of strings based on a rolling checksum." },
1581 { "bitmatch", bitmatch, METH_VARARGS,
1582 "Count the number of matching prefix bits between two strings." },
1583 { "firstword", firstword, METH_VARARGS,
1584 "Return an int corresponding to the first 32 bits of buf." },
1585 { "bloom_contains", bloom_contains, METH_VARARGS,
1586 "Check if a bloom filter of 2^nbits bytes contains an object" },
1587 { "bloom_add", bloom_add, METH_VARARGS,
1588 "Add an object to a bloom filter of 2^nbits bytes" },
1589 { "extract_bits", extract_bits, METH_VARARGS,
1590 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1591 { "merge_into", merge_into, METH_VARARGS,
1592 "Merges a bunch of idx and midx files into a single midx." },
1593 { "write_idx", write_idx, METH_VARARGS,
1594 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1595 { "write_random", write_random, METH_VARARGS,
1596 "Write random bytes to the given file descriptor" },
1597 { "random_sha", random_sha, METH_VARARGS,
1598 "Return a random 20-byte string" },
1599 { "open_noatime", open_noatime, METH_VARARGS,
1600 "open() the given filename for read with O_NOATIME if possible" },
1601 { "fadvise_done", fadvise_done, METH_VARARGS,
1602 "Inform the kernel that we're finished with earlier parts of a file" },
1603 #ifdef BUP_HAVE_FILE_ATTRS
1604 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1605 "Return the Linux attributes for the given file." },
1607 #ifdef BUP_HAVE_FILE_ATTRS
1608 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1609 "Set the Linux attributes for the given file." },
1611 #ifdef HAVE_UTIMENSAT
1612 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1613 "Change path timestamps with nanosecond precision (POSIX)." },
1616 { "bup_utimes", bup_utimes, METH_VARARGS,
1617 "Change path timestamps with microsecond precision." },
1620 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1621 "Change path timestamps with microsecond precision;"
1622 " don't follow symlinks." },
1624 { "stat", bup_stat, METH_VARARGS,
1625 "Extended version of stat." },
1626 { "lstat", bup_lstat, METH_VARARGS,
1627 "Extended version of lstat." },
1628 { "fstat", bup_fstat, METH_VARARGS,
1629 "Extended version of fstat." },
1630 #ifdef HAVE_TM_TM_GMTOFF
1631 { "localtime", bup_localtime, METH_VARARGS,
1632 "Return struct_time elements plus the timezone offset and name." },
1634 { "bytescmp", bup_bytescmp, METH_VARARGS,
1635 "Return a negative value if x < y, zero if equal, positive otherwise."},
1636 #ifdef BUP_MINCORE_BUF_TYPE
1637 { "mincore", bup_mincore, METH_VARARGS,
1638 "For mincore(src, src_n, src_off, dest, dest_off)"
1639 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1641 { NULL, NULL, 0, NULL }, // sentinel
1644 static void test_integral_assignment_fits(void)
1646 assert(sizeof(signed short) == sizeof(unsigned short));
1647 assert(sizeof(signed short) < sizeof(signed long long));
1648 assert(sizeof(signed short) < sizeof(unsigned long long));
1649 assert(sizeof(unsigned short) < sizeof(signed long long));
1650 assert(sizeof(unsigned short) < sizeof(unsigned long long));
1652 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
1653 unsigned short us, usmax = USHRT_MAX;
1654 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
1655 unsigned long long ullmax = ULLONG_MAX;
1657 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
1658 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
1659 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
1660 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
1661 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
1662 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
1664 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
1665 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
1666 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
1667 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
1668 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
1672 static int setup_module(PyObject *m)
1674 // FIXME: migrate these tests to configure, or at least don't
1675 // possibly crash the whole application. Check against the type
1676 // we're going to use when passing to python. Other stat types
1677 // are tested at runtime.
1678 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1679 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1680 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1681 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1682 // Just be sure (relevant when passing timestamps back to Python above).
1683 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1684 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1686 test_integral_assignment_fits();
1688 // Originally required by append_sparse_region()
1691 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1693 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1699 #pragma clang diagnostic push
1700 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1703 value = INTEGER_TO_PY(INT_MAX);
1704 PyObject_SetAttrString(m, "INT_MAX", value);
1706 value = INTEGER_TO_PY(UINT_MAX);
1707 PyObject_SetAttrString(m, "UINT_MAX", value);
1710 #ifdef HAVE_UTIMENSAT
1713 value = INTEGER_TO_PY(AT_FDCWD);
1714 PyObject_SetAttrString(m, "AT_FDCWD", value);
1716 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1717 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1719 value = INTEGER_TO_PY(UTIME_NOW);
1720 PyObject_SetAttrString(m, "UTIME_NOW", value);
1724 #ifdef BUP_HAVE_MINCORE_INCORE
1727 value = INTEGER_TO_PY(MINCORE_INCORE);
1728 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1732 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1734 e = getenv("BUP_FORCE_TTY");
1735 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1741 #if PY_MAJOR_VERSION < 3
1743 PyMODINIT_FUNC init_helpers(void)
1745 PyObject *m = Py_InitModule("_helpers", helper_methods);
1749 if (!setup_module(m))
1756 # else // PY_MAJOR_VERSION >= 3
1758 static struct PyModuleDef helpers_def = {
1759 PyModuleDef_HEAD_INIT,
1765 NULL, // helpers_traverse,
1766 NULL, // helpers_clear,
1770 PyMODINIT_FUNC PyInit__helpers(void)
1772 PyObject *module = PyModule_Create(&helpers_def);
1775 if (!setup_module(module))
1783 #endif // PY_MAJOR_VERSION >= 3