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 // cstr_argf: for byte vectors without null characters (e.g. paths)
75 // rbuf_argf: for read-only byte vectors
76 // wbuf_argf: for mutable byte vectors
78 #if PY_MAJOR_VERSION < 3
80 # define get_state(x) (&state)
81 # define cstr_argf "s"
82 # define rbuf_argf "s#"
83 # define wbuf_argf "s*"
85 # define get_state(x) ((state_t *) PyModule_GetState(x))
86 # define cstr_argf "y"
87 # define rbuf_argf "y#"
88 # define wbuf_argf "y*"
89 #endif // PY_MAJOR_VERSION >= 3
93 // This function should technically be macro'd out if it's going to be used
94 // more than ocasionally. As of this writing, it'll actually never be called
95 // in real world bup scenarios (because our packs are < MAX_INT bytes).
96 static uint64_t htonll(uint64_t value)
98 static const int endian_test = 42;
100 if (*(char *)&endian_test == endian_test) // LSB-MSB
101 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
102 return value; // already in network byte order MSB-LSB
108 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
111 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
114 // Disabling sign-compare here should be fine since we're explicitly
115 // checking for a sign mismatch, i.e. if the signs don't match, then
116 // it doesn't matter what the value comparison says.
117 // FIXME: ... so should we reverse the order?
118 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
120 _Pragma("GCC diagnostic push"); \
121 _Pragma("GCC diagnostic ignored \"-Wsign-compare\""); \
123 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
124 _Pragma("GCC diagnostic pop"); \
129 // At the moment any code that calls INTEGER_TO_PY() will have to
130 // disable -Wtautological-compare for clang. See below.
132 #define INTEGER_TO_PY(x) \
133 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
137 #if PY_MAJOR_VERSION < 3
138 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
141 const long tmp = PyInt_AsLong(py);
142 if (tmp == -1 && PyErr_Occurred())
144 if (PyErr_ExceptionMatches(PyExc_OverflowError))
145 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
151 PyErr_Format(PyExc_OverflowError,
152 "negative %s cannot be converted to unsigned long", name);
161 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
163 #if PY_MAJOR_VERSION < 3
165 return bup_ulong_from_pyint(x, py, name);
168 if (!PyLong_Check(py))
170 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
174 const unsigned long tmp = PyLong_AsUnsignedLong(py);
175 if (PyErr_Occurred())
177 if (PyErr_ExceptionMatches(PyExc_OverflowError))
178 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
187 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
190 if (!bup_ulong_from_py(&tmp, py, name))
195 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
202 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
205 #if PY_MAJOR_VERSION < 3
209 if (bup_ulong_from_pyint(&tmp, py, name))
218 if (!PyLong_Check(py))
220 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
224 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
225 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
227 if (PyErr_ExceptionMatches(PyExc_OverflowError))
228 PyErr_Format(PyExc_OverflowError,
229 "%s too big for unsigned long long", name);
237 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
239 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
240 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
243 Py_ssize_t s1_len, s2_len;
244 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
246 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
248 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
249 const int cmp = memcmp(s1, s2, n);
251 return PyLong_FromLong(cmp);
252 if (s1_len == s2_len)
253 return PyLong_FromLong(0);;
254 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
258 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
259 #if __WIN32__ || __CYGWIN__
261 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
262 static void unpythonize_argv(void) { }
264 #else // not __WIN32__
266 // For some reason this isn't declared in Python.h
267 extern void Py_GetArgcArgv(int *argc, char ***argv);
269 static void unpythonize_argv(void)
274 Py_GetArgcArgv(&argc, &argv);
276 for (i = 0; i < argc-1; i++)
278 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
280 // The argv block doesn't work the way we expected; it's unsafe
286 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
288 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
292 p = strrchr(argv[1], '/');
298 memmove(argv[0], p, len);
299 memset(arge - diff, 0, diff);
300 for (i = 0; i < argc; i++)
301 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
306 #endif // not __WIN32__ or __CYGWIN__
309 static int write_all(int fd, const void *buf, const size_t count)
312 while (written < count)
314 const ssize_t rc = write(fd, buf + written, count - written);
323 static int uadd(unsigned long long *dest,
324 const unsigned long long x,
325 const unsigned long long y)
327 const unsigned long long result = x + y;
328 if (result < x || result < y)
335 static PyObject *append_sparse_region(const int fd, unsigned long long n)
340 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
342 const off_t off = lseek(fd, new_off, SEEK_CUR);
343 if (off == (off_t) -1)
344 return PyErr_SetFromErrno(PyExc_IOError);
351 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
353 unsigned long long prev_pending,
354 const unsigned long long count)
356 // Add count additional sparse zeros to prev_pending and store the
357 // result in new_pending, or if the total won't fit in
358 // new_pending, write some of the zeros to fd sparsely, and store
359 // the remaining sum in new_pending.
360 if (!uadd(new_pending, prev_pending, count))
362 PyObject *err = append_sparse_region(fd, prev_pending);
365 *new_pending = count;
371 static byte* find_not_zero(const byte * const start, const byte * const end)
373 // Return a pointer to first non-zero byte between start and end,
374 // or end if there isn't one.
375 assert(start <= end);
376 const unsigned char *cur = start;
377 while (cur < end && *cur == 0)
383 static byte* find_trailing_zeros(const byte * const start,
384 const byte * const end)
386 // Return a pointer to the start of any trailing run of zeros, or
387 // end if there isn't one.
388 assert(start <= end);
391 const byte * cur = end;
392 while (cur > start && *--cur == 0) {}
396 return (byte *) (cur + 1);
400 static byte *find_non_sparse_end(const byte * const start,
401 const byte * const end,
402 const ptrdiff_t min_len)
404 // Return the first pointer to a min_len sparse block in [start,
405 // end) if there is one, otherwise a pointer to the start of any
406 // trailing run of zeros. If there are no trailing zeros, return
412 // Probe in min_len jumps, searching backward from the jump
413 // destination for a non-zero byte. If such a byte is found, move
414 // just past it and try again.
415 const byte *candidate = start;
416 // End of any run of zeros, starting at candidate, that we've already seen
417 const byte *end_of_known_zeros = candidate;
418 while (end - candidate >= min_len) // Handle all min_len candidate blocks
420 const byte * const probe_end = candidate + min_len;
421 const byte * const trailing_zeros =
422 find_trailing_zeros(end_of_known_zeros, probe_end);
423 if (trailing_zeros == probe_end)
424 end_of_known_zeros = candidate = probe_end;
425 else if (trailing_zeros == end_of_known_zeros)
427 assert(candidate >= start);
428 assert(candidate <= end);
429 assert(*candidate == 0);
430 return (byte *) candidate;
434 candidate = trailing_zeros;
435 end_of_known_zeros = probe_end;
439 if (candidate == end)
442 // No min_len sparse run found, search backward from end
443 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
446 if (trailing_zeros == end_of_known_zeros)
448 assert(candidate >= start);
449 assert(candidate < end);
450 assert(*candidate == 0);
451 assert(end - candidate < min_len);
452 return (byte *) candidate;
455 if (trailing_zeros == end)
457 assert(*(end - 1) != 0);
461 assert(end - trailing_zeros < min_len);
462 assert(trailing_zeros >= start);
463 assert(trailing_zeros < end);
464 assert(*trailing_zeros == 0);
465 return (byte *) trailing_zeros;
469 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
472 unsigned char *buf = NULL;
474 PyObject *py_min_sparse_len, *py_prev_sparse_len;
475 if (!PyArg_ParseTuple(args, "it#OO",
476 &fd, &buf, &sbuf_len,
477 &py_min_sparse_len, &py_prev_sparse_len))
479 ptrdiff_t min_sparse_len;
480 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
481 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
483 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
484 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
485 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
488 return PyErr_Format(PyExc_ValueError, "negative bufer length");
489 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
490 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
492 const byte * block = buf; // Start of pending block
493 const byte * const end = buf + buf_len;
494 unsigned long long zeros = prev_sparse_len;
497 assert(block <= end);
499 return PyLong_FromUnsignedLongLong(zeros);
503 // Look for the end of block, i.e. the next sparse run of
504 // at least min_sparse_len zeros, or the end of the
506 const byte * const probe = find_non_sparse_end(block + 1, end,
508 // Either at end of block, or end of non-sparse; write pending data
509 PyObject *err = append_sparse_region(fd, zeros);
512 int rc = write_all(fd, block, probe - block);
514 return PyErr_SetFromErrno(PyExc_IOError);
516 if (end - probe < min_sparse_len)
519 zeros = min_sparse_len;
520 block = probe + zeros;
524 // Should be in the first loop iteration, a sparse run of
525 // zeros, or nearly at the end of the block (within
527 const byte * const zeros_end = find_not_zero(block, end);
528 PyObject *err = record_sparse_zeros(&zeros, fd,
529 zeros, zeros_end - block);
532 assert(block <= zeros_end);
539 static PyObject *selftest(PyObject *self, PyObject *args)
541 if (!PyArg_ParseTuple(args, ""))
544 return Py_BuildValue("i", !bupsplit_selftest());
548 static PyObject *blobbits(PyObject *self, PyObject *args)
550 if (!PyArg_ParseTuple(args, ""))
552 return Py_BuildValue("i", BUP_BLOBBITS);
556 static PyObject *splitbuf(PyObject *self, PyObject *args)
558 // We stick to buffers in python 2 because they appear to be
559 // substantially smaller than memoryviews, and because
560 // zlib.compress() in python 2 can't accept a memoryview
561 // (cf. hashsplit.py).
562 int out = 0, bits = -1;
563 if (PY_MAJOR_VERSION > 2)
566 if (!PyArg_ParseTuple(args, "y*", &buf))
568 assert(buf.len <= INT_MAX);
569 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
570 PyBuffer_Release(&buf);
574 unsigned char *buf = NULL;
576 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
578 assert(len <= INT_MAX);
579 out = bupsplit_find_ofs(buf, len, &bits);
581 if (out) assert(bits >= BUP_BLOBBITS);
582 return Py_BuildValue("ii", out, bits);
586 static PyObject *bitmatch(PyObject *self, PyObject *args)
588 unsigned char *buf1 = NULL, *buf2 = NULL;
589 Py_ssize_t len1 = 0, len2 = 0;
593 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
597 for (byte = 0; byte < len1 && byte < len2; byte++)
599 int b1 = buf1[byte], b2 = buf2[byte];
602 for (bit = 0; bit < 8; bit++)
603 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
609 assert(byte <= (INT_MAX >> 3));
610 return Py_BuildValue("i", byte*8 + bit);
614 static PyObject *firstword(PyObject *self, PyObject *args)
616 unsigned char *buf = NULL;
620 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
626 v = ntohl(*(uint32_t *)buf);
627 return PyLong_FromUnsignedLong(v);
631 #define BLOOM2_HEADERLEN 16
633 static void to_bloom_address_bitmask4(const unsigned char *buf,
634 const int nbits, uint64_t *v, unsigned char *bitmask)
640 memcpy(&high, buf, 4);
641 mask = (1<<nbits) - 1;
642 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
643 bit = (raw >> (37-nbits)) & 0x7;
644 *v = (raw >> (40-nbits)) & mask;
648 static void to_bloom_address_bitmask5(const unsigned char *buf,
649 const int nbits, uint32_t *v, unsigned char *bitmask)
655 memcpy(&high, buf, 4);
656 mask = (1<<nbits) - 1;
658 bit = (raw >> (29-nbits)) & 0x7;
659 *v = (raw >> (32-nbits)) & mask;
663 #define BLOOM_SET_BIT(name, address, otype) \
664 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
666 unsigned char bitmask;\
668 address(buf, nbits, &v, &bitmask);\
669 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
671 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
672 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
675 #define BLOOM_GET_BIT(name, address, otype) \
676 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
678 unsigned char bitmask;\
680 address(buf, nbits, &v, &bitmask);\
681 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
683 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
684 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
687 static PyObject *bloom_add(PyObject *self, PyObject *args)
689 Py_buffer bloom, sha;
690 int nbits = 0, k = 0;
691 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
692 &bloom, &sha, &nbits, &k))
695 PyObject *result = NULL;
697 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
698 goto clean_and_return;
703 goto clean_and_return;
704 unsigned char *cur = sha.buf;
706 for (end = cur + sha.len; cur < end; cur += 20/k)
707 bloom_set_bit5(bloom.buf, cur, nbits);
712 goto clean_and_return;
713 unsigned char *cur = sha.buf;
714 unsigned char *end = cur + sha.len;
715 for (; cur < end; cur += 20/k)
716 bloom_set_bit4(bloom.buf, cur, nbits);
719 goto clean_and_return;
721 result = Py_BuildValue("n", sha.len / 20);
724 PyBuffer_Release(&bloom);
725 PyBuffer_Release(&sha);
729 static PyObject *bloom_contains(PyObject *self, PyObject *args)
732 unsigned char *sha = NULL;
734 int nbits = 0, k = 0;
735 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
736 &bloom, &sha, &len, &nbits, &k))
739 PyObject *result = NULL;
742 goto clean_and_return;
747 goto clean_and_return;
750 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
751 if (!bloom_get_bit5(bloom.buf, sha, nbits))
753 result = Py_BuildValue("Oi", Py_None, steps);
754 goto clean_and_return;
760 goto clean_and_return;
763 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
764 if (!bloom_get_bit4(bloom.buf, sha, nbits))
766 result = Py_BuildValue("Oi", Py_None, steps);
767 goto clean_and_return;
771 goto clean_and_return;
773 result = Py_BuildValue("ii", 1, k);
776 PyBuffer_Release(&bloom);
781 static uint32_t _extract_bits(unsigned char *buf, int nbits)
785 mask = (1<<nbits) - 1;
786 v = ntohl(*(uint32_t *)buf);
787 v = (v >> (32-nbits)) & mask;
792 static PyObject *extract_bits(PyObject *self, PyObject *args)
794 unsigned char *buf = NULL;
798 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
804 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
809 unsigned char bytes[20];
812 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
814 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
827 static void _fix_idx_order(struct idx **idxs, int *last_i)
830 int low, mid, high, c = 0;
833 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
835 idxs[*last_i] = NULL;
848 mid = (low + high) / 2;
849 c = _cmp_sha(idx->cur, idxs[mid]->cur);
861 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
866 static uint32_t _get_idx_i(struct idx *idx)
868 if (idx->cur_name == NULL)
869 return idx->name_base;
870 return ntohl(*idx->cur_name) + idx->name_base;
873 #define MIDX4_HEADERLEN 12
875 static PyObject *merge_into(PyObject *self, PyObject *args)
877 PyObject *py_total, *ilist = NULL;
878 unsigned char *fmap = NULL;
879 struct sha *sha_ptr, *sha_start = NULL;
880 uint32_t *table_ptr, *name_ptr, *name_start;
881 struct idx **idxs = NULL;
885 uint32_t count, prefix;
889 if (!PyArg_ParseTuple(args, "w#iOO",
890 &fmap, &flen, &bits, &py_total, &ilist))
893 if (!bup_uint_from_py(&total, py_total, "total"))
896 num_i = PyList_Size(ilist);
897 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
899 for (i = 0; i < num_i; i++)
901 long len, sha_ofs, name_map_ofs;
902 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
903 PyObject *itup = PyList_GetItem(ilist, i);
904 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
905 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
907 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
908 idxs[i]->end = &idxs[i]->cur[len];
910 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
912 idxs[i]->cur_name = NULL;
914 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
915 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
916 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
925 if (count % 102424 == 0 && get_state(self)->istty2)
926 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
927 count*100.0/total, count, total);
929 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
930 while (prefix < new_prefix)
931 table_ptr[prefix++] = htonl(count);
932 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
933 *name_ptr++ = htonl(_get_idx_i(idx));
935 if (idx->cur_name != NULL)
937 _fix_idx_order(idxs, &last_i);
940 while (prefix < ((uint32_t) 1 << bits))
941 table_ptr[prefix++] = htonl(count);
942 assert(count == total);
943 assert(prefix == ((uint32_t) 1 << bits));
944 assert(sha_ptr == sha_start+count);
945 assert(name_ptr == name_start+count);
948 return PyLong_FromUnsignedLong(count);
951 #define FAN_ENTRIES 256
953 static PyObject *write_idx(PyObject *self, PyObject *args)
955 char *filename = NULL;
956 PyObject *py_total, *idx = NULL;
958 unsigned int total = 0;
960 int i, j, ofs64_count;
961 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
966 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
967 &filename, &fmap, &idx, &py_total))
970 PyObject *result = NULL;
972 if (!bup_uint_from_py(&total, py_total, "total"))
973 goto clean_and_return;
975 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
977 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
979 goto clean_and_return;
982 const char idx_header[] = "\377tOc\0\0\0\002";
983 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
985 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
986 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
987 crc_ptr = (uint32_t *)&sha_ptr[total];
988 ofs_ptr = (uint32_t *)&crc_ptr[total];
989 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
993 for (i = 0; i < FAN_ENTRIES; ++i)
996 part = PyList_GET_ITEM(idx, i);
998 plen = PyList_GET_SIZE(part);
1000 *fan_ptr++ = htonl(count);
1001 for (j = 0; j < plen; ++j)
1003 unsigned char *sha = NULL;
1004 Py_ssize_t sha_len = 0;
1005 PyObject *crc_py, *ofs_py;
1007 unsigned PY_LONG_LONG ofs_ull;
1009 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1010 &sha, &sha_len, &crc_py, &ofs_py))
1011 goto clean_and_return;
1012 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1013 goto clean_and_return;
1014 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1015 goto clean_and_return;
1016 assert(crc <= UINT32_MAX);
1017 assert(ofs_ull <= UINT64_MAX);
1019 if (sha_len != sizeof(struct sha))
1020 goto clean_and_return;
1021 memcpy(sha_ptr++, sha, sizeof(struct sha));
1022 *crc_ptr++ = htonl(crc);
1023 if (ofs > 0x7fffffff)
1025 *ofs64_ptr++ = htonll(ofs);
1026 ofs = 0x80000000 | ofs64_count++;
1028 *ofs_ptr++ = htonl((uint32_t)ofs);
1032 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1035 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1036 goto clean_and_return;
1039 result = PyLong_FromUnsignedLong(count);
1042 PyBuffer_Release(&fmap);
1047 // I would have made this a lower-level function that just fills in a buffer
1048 // with random values, and then written those values from python. But that's
1049 // about 20% slower in my tests, and since we typically generate random
1050 // numbers for benchmarking other parts of bup, any slowness in generating
1051 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1052 // pseudorandom bytes much except for this anyway.
1053 static PyObject *write_random(PyObject *self, PyObject *args)
1055 uint32_t buf[1024/4];
1056 int fd = -1, seed = 0, verbose = 0;
1058 long long len = 0, kbytes = 0, written = 0;
1060 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1065 for (kbytes = 0; kbytes < len/1024; kbytes++)
1068 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1070 ret = write(fd, buf, sizeof(buf));
1074 if (ret < (int)sizeof(buf))
1076 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1077 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1080 // handle non-multiples of 1024
1084 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1086 ret = write(fd, buf, len % 1024);
1092 if (kbytes/1024 > 0)
1093 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1094 return Py_BuildValue("L", written);
1098 static PyObject *random_sha(PyObject *self, PyObject *args)
1100 static int seeded = 0;
1101 uint32_t shabuf[20/4];
1106 assert(sizeof(shabuf) == 20);
1107 srandom(time(NULL));
1111 if (!PyArg_ParseTuple(args, ""))
1114 memset(shabuf, 0, sizeof(shabuf));
1115 for (i=0; i < 20/4; i++)
1116 shabuf[i] = random();
1117 return Py_BuildValue("s#", shabuf, 20);
1121 static int _open_noatime(const char *filename, int attrs)
1123 int attrs_noatime, fd;
1126 attrs |= O_NOFOLLOW;
1129 attrs |= O_LARGEFILE;
1131 attrs_noatime = attrs;
1133 attrs_noatime |= O_NOATIME;
1135 fd = open(filename, attrs_noatime);
1136 if (fd < 0 && errno == EPERM)
1138 // older Linux kernels would return EPERM if you used O_NOATIME
1139 // and weren't the file's owner. This pointless restriction was
1140 // relaxed eventually, but we have to handle it anyway.
1141 // (VERY old kernels didn't recognized O_NOATIME, but they would
1142 // just harmlessly ignore it, so this branch won't trigger)
1143 fd = open(filename, attrs);
1149 static PyObject *open_noatime(PyObject *self, PyObject *args)
1151 char *filename = NULL;
1153 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1155 fd = _open_noatime(filename, 0);
1157 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1158 return Py_BuildValue("i", fd);
1162 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1165 long long llofs, lllen = 0;
1166 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1169 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1170 return PyErr_Format(PyExc_OverflowError,
1171 "fadvise offset overflows off_t");
1172 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1173 return PyErr_Format(PyExc_OverflowError,
1174 "fadvise length overflows off_t");
1175 #ifdef POSIX_FADV_DONTNEED
1176 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1178 return Py_BuildValue("");
1182 // Currently the Linux kernel and FUSE disagree over the type for
1183 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1184 // but FUSE chose long (matching the declaration in linux/fs.h). So
1185 // if you use int, and then traverse a FUSE filesystem, you may
1186 // corrupt the stack. But if you use long, then you may get invalid
1187 // results on big-endian systems.
1189 // For now, we just use long, and then disable Linux attrs entirely
1190 // (with a warning) in helpers.py on systems that are affected.
1192 #ifdef BUP_HAVE_FILE_ATTRS
1193 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1200 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1203 fd = _open_noatime(path, O_NONBLOCK);
1205 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1207 attr = 0; // Handle int/long mismatch (see above)
1208 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1212 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1215 assert(attr <= UINT_MAX); // Kernel type is actually int
1216 return PyLong_FromUnsignedLong(attr);
1218 #endif /* def BUP_HAVE_FILE_ATTRS */
1222 #ifdef BUP_HAVE_FILE_ATTRS
1223 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1226 unsigned long orig_attr;
1232 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1235 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1238 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1240 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1242 // Restrict attr to modifiable flags acdeijstuADST -- see
1243 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1244 // in pf.c flags_array[].
1245 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1246 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1247 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1248 | FS_TOPDIR_FL | FS_NOCOW_FL;
1250 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1251 orig_attr = 0; // Handle int/long mismatch (see above)
1252 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1256 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1258 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1259 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1261 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1265 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1269 return Py_BuildValue("O", Py_None);
1271 #endif /* def BUP_HAVE_FILE_ATTRS */
1274 #ifndef HAVE_UTIMENSAT
1276 #error "cannot find utimensat or utimes()"
1278 #ifndef HAVE_LUTIMES
1279 #error "cannot find utimensat or lutimes()"
1283 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1287 const long long lltmp = PyLong_AsLongLong(pylong); \
1288 if (lltmp == -1 && PyErr_Occurred()) \
1290 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1292 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1293 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1295 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1301 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1309 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1318 #ifdef HAVE_UTIMENSAT
1320 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1325 PyObject *access_py, *modification_py;
1326 struct timespec ts[2];
1328 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1331 &access_py, &(ts[0].tv_nsec),
1332 &modification_py, &(ts[1].tv_nsec),
1337 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1340 PyErr_SetString(PyExc_ValueError,
1341 "unable to convert access time seconds for utimensat");
1344 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1347 PyErr_SetString(PyExc_ValueError,
1348 "unable to convert modification time seconds for utimensat");
1351 rc = utimensat(fd, path, ts, flag);
1353 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1355 return Py_BuildValue("O", Py_None);
1358 #endif /* def HAVE_UTIMENSAT */
1361 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1363 static int bup_parse_xutimes_args(char **path,
1364 struct timeval tv[2],
1367 PyObject *access_py, *modification_py;
1368 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1370 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1372 &access_py, &access_us,
1373 &modification_py, &modification_us))
1377 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1380 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1383 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1385 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1388 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1391 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1394 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1396 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1402 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1406 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1409 struct timeval tv[2];
1410 if (!bup_parse_xutimes_args(&path, tv, args))
1412 int rc = utimes(path, tv);
1414 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1415 return Py_BuildValue("O", Py_None);
1417 #endif /* def HAVE_UTIMES */
1421 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1424 struct timeval tv[2];
1425 if (!bup_parse_xutimes_args(&path, tv, args))
1427 int rc = lutimes(path, tv);
1429 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1431 return Py_BuildValue("O", Py_None);
1433 #endif /* def HAVE_LUTIMES */
1436 #ifdef HAVE_STAT_ST_ATIM
1437 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1438 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1439 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1440 #elif defined HAVE_STAT_ST_ATIMENSEC
1441 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1442 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1443 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1445 # define BUP_STAT_ATIME_NS(st) 0
1446 # define BUP_STAT_MTIME_NS(st) 0
1447 # define BUP_STAT_CTIME_NS(st) 0
1451 #pragma clang diagnostic push
1452 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1454 static PyObject *stat_struct_to_py(const struct stat *st,
1455 const char *filename,
1458 // We can check the known (via POSIX) signed and unsigned types at
1459 // compile time, but not (easily) the unspecified types, so handle
1460 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1462 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1463 INTEGER_TO_PY(st->st_mode),
1464 (unsigned PY_LONG_LONG) st->st_ino,
1465 INTEGER_TO_PY(st->st_dev),
1466 INTEGER_TO_PY(st->st_nlink),
1467 INTEGER_TO_PY(st->st_uid),
1468 INTEGER_TO_PY(st->st_gid),
1469 INTEGER_TO_PY(st->st_rdev),
1470 (PY_LONG_LONG) st->st_size,
1471 INTEGER_TO_PY(st->st_atime),
1472 (long) BUP_STAT_ATIME_NS(st),
1473 INTEGER_TO_PY(st->st_mtime),
1474 (long) BUP_STAT_MTIME_NS(st),
1475 INTEGER_TO_PY(st->st_ctime),
1476 (long) BUP_STAT_CTIME_NS(st));
1479 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1481 static PyObject *bup_stat(PyObject *self, PyObject *args)
1486 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1490 rc = stat(filename, &st);
1492 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1493 return stat_struct_to_py(&st, filename, 0);
1497 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1502 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1506 rc = lstat(filename, &st);
1508 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1509 return stat_struct_to_py(&st, filename, 0);
1513 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1517 if (!PyArg_ParseTuple(args, "i", &fd))
1521 rc = fstat(fd, &st);
1523 return PyErr_SetFromErrno(PyExc_OSError);
1524 return stat_struct_to_py(&st, NULL, fd);
1528 #ifdef HAVE_TM_TM_GMTOFF
1529 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1533 if (!PyArg_ParseTuple(args, "L", &lltime))
1535 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1536 return PyErr_Format(PyExc_OverflowError, "time value too large");
1540 if(localtime_r(&ttime, &tm) == NULL)
1541 return PyErr_SetFromErrno(PyExc_OSError);
1543 // Match the Python struct_time values.
1544 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1545 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1546 tm.tm_hour, tm.tm_min, tm.tm_sec,
1547 tm.tm_wday, tm.tm_yday + 1,
1548 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1550 #endif /* def HAVE_TM_TM_GMTOFF */
1553 #ifdef BUP_MINCORE_BUF_TYPE
1554 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1556 Py_buffer src, dest;
1557 PyObject *py_src_n, *py_src_off, *py_dest_off;
1559 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1560 &src, &py_src_n, &py_src_off,
1561 &dest, &py_dest_off))
1564 PyObject *result = NULL;
1566 unsigned long long src_n, src_off, dest_off;
1567 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1568 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1569 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1570 goto clean_and_return;
1572 unsigned long long src_region_end;
1573 if (!uadd(&src_region_end, src_off, src_n)) {
1574 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1575 goto clean_and_return;
1577 assert(src.len >= 0);
1578 if (src_region_end > (unsigned long long) src.len) {
1579 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1580 goto clean_and_return;
1583 unsigned long long dest_size;
1584 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1585 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1586 goto clean_and_return;
1588 if (dest_off > dest_size) {
1589 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1590 goto clean_and_return;
1594 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1595 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1596 goto clean_and_return;
1598 int rc = mincore((void *)(src.buf + src_off), src_n,
1599 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1601 result = PyErr_SetFromErrno(PyExc_OSError);
1602 goto clean_and_return;
1604 result = Py_BuildValue("O", Py_None);
1607 PyBuffer_Release(&src);
1608 PyBuffer_Release(&dest);
1611 #endif /* def BUP_MINCORE_BUF_TYPE */
1614 static PyMethodDef helper_methods[] = {
1615 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1616 "Write buf excepting zeros at the end. Return trailing zero count." },
1617 { "selftest", selftest, METH_VARARGS,
1618 "Check that the rolling checksum rolls correctly (for unit tests)." },
1619 { "blobbits", blobbits, METH_VARARGS,
1620 "Return the number of bits in the rolling checksum." },
1621 { "splitbuf", splitbuf, METH_VARARGS,
1622 "Split a list of strings based on a rolling checksum." },
1623 { "bitmatch", bitmatch, METH_VARARGS,
1624 "Count the number of matching prefix bits between two strings." },
1625 { "firstword", firstword, METH_VARARGS,
1626 "Return an int corresponding to the first 32 bits of buf." },
1627 { "bloom_contains", bloom_contains, METH_VARARGS,
1628 "Check if a bloom filter of 2^nbits bytes contains an object" },
1629 { "bloom_add", bloom_add, METH_VARARGS,
1630 "Add an object to a bloom filter of 2^nbits bytes" },
1631 { "extract_bits", extract_bits, METH_VARARGS,
1632 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1633 { "merge_into", merge_into, METH_VARARGS,
1634 "Merges a bunch of idx and midx files into a single midx." },
1635 { "write_idx", write_idx, METH_VARARGS,
1636 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1637 { "write_random", write_random, METH_VARARGS,
1638 "Write random bytes to the given file descriptor" },
1639 { "random_sha", random_sha, METH_VARARGS,
1640 "Return a random 20-byte string" },
1641 { "open_noatime", open_noatime, METH_VARARGS,
1642 "open() the given filename for read with O_NOATIME if possible" },
1643 { "fadvise_done", fadvise_done, METH_VARARGS,
1644 "Inform the kernel that we're finished with earlier parts of a file" },
1645 #ifdef BUP_HAVE_FILE_ATTRS
1646 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1647 "Return the Linux attributes for the given file." },
1649 #ifdef BUP_HAVE_FILE_ATTRS
1650 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1651 "Set the Linux attributes for the given file." },
1653 #ifdef HAVE_UTIMENSAT
1654 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1655 "Change path timestamps with nanosecond precision (POSIX)." },
1658 { "bup_utimes", bup_utimes, METH_VARARGS,
1659 "Change path timestamps with microsecond precision." },
1662 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1663 "Change path timestamps with microsecond precision;"
1664 " don't follow symlinks." },
1666 { "stat", bup_stat, METH_VARARGS,
1667 "Extended version of stat." },
1668 { "lstat", bup_lstat, METH_VARARGS,
1669 "Extended version of lstat." },
1670 { "fstat", bup_fstat, METH_VARARGS,
1671 "Extended version of fstat." },
1672 #ifdef HAVE_TM_TM_GMTOFF
1673 { "localtime", bup_localtime, METH_VARARGS,
1674 "Return struct_time elements plus the timezone offset and name." },
1676 { "bytescmp", bup_bytescmp, METH_VARARGS,
1677 "Return a negative value if x < y, zero if equal, positive otherwise."},
1678 #ifdef BUP_MINCORE_BUF_TYPE
1679 { "mincore", bup_mincore, METH_VARARGS,
1680 "For mincore(src, src_n, src_off, dest, dest_off)"
1681 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1683 { NULL, NULL, 0, NULL }, // sentinel
1686 static void test_integral_assignment_fits(void)
1688 assert(sizeof(signed short) == sizeof(unsigned short));
1689 assert(sizeof(signed short) < sizeof(signed long long));
1690 assert(sizeof(signed short) < sizeof(unsigned long long));
1691 assert(sizeof(unsigned short) < sizeof(signed long long));
1692 assert(sizeof(unsigned short) < sizeof(unsigned long long));
1694 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
1695 unsigned short us, usmax = USHRT_MAX;
1696 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
1697 unsigned long long ullmax = ULLONG_MAX;
1699 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
1700 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
1701 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
1702 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
1703 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
1704 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
1706 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
1707 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
1708 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
1709 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
1710 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
1714 static int setup_module(PyObject *m)
1716 // FIXME: migrate these tests to configure, or at least don't
1717 // possibly crash the whole application. Check against the type
1718 // we're going to use when passing to python. Other stat types
1719 // are tested at runtime.
1720 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1721 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1722 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1723 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1724 // Just be sure (relevant when passing timestamps back to Python above).
1725 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1726 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1728 test_integral_assignment_fits();
1730 // Originally required by append_sparse_region()
1733 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1735 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1741 #pragma clang diagnostic push
1742 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1745 value = INTEGER_TO_PY(INT_MAX);
1746 PyObject_SetAttrString(m, "INT_MAX", value);
1748 value = INTEGER_TO_PY(UINT_MAX);
1749 PyObject_SetAttrString(m, "UINT_MAX", value);
1752 #ifdef HAVE_UTIMENSAT
1755 value = INTEGER_TO_PY(AT_FDCWD);
1756 PyObject_SetAttrString(m, "AT_FDCWD", value);
1758 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1759 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1761 value = INTEGER_TO_PY(UTIME_NOW);
1762 PyObject_SetAttrString(m, "UTIME_NOW", value);
1766 #ifdef BUP_HAVE_MINCORE_INCORE
1769 value = INTEGER_TO_PY(MINCORE_INCORE);
1770 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1774 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1776 e = getenv("BUP_FORCE_TTY");
1777 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1783 #if PY_MAJOR_VERSION < 3
1785 PyMODINIT_FUNC init_helpers(void)
1787 PyObject *m = Py_InitModule("_helpers", helper_methods);
1791 if (!setup_module(m))
1798 # else // PY_MAJOR_VERSION >= 3
1800 static struct PyModuleDef helpers_def = {
1801 PyModuleDef_HEAD_INIT,
1807 NULL, // helpers_traverse,
1808 NULL, // helpers_clear,
1812 PyMODINIT_FUNC PyInit__helpers(void)
1814 PyObject *module = PyModule_Create(&helpers_def);
1817 if (!setup_module(module))
1825 #endif // PY_MAJOR_VERSION >= 3