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
92 static void *checked_malloc(size_t n, size_t size)
95 if (__builtin_mul_overflow(n, size, &total))
97 PyErr_Format(PyExc_OverflowError,
98 "request to allocate %lu items of size %lu is too large",
102 void *result = malloc(total);
104 return PyErr_NoMemory();
108 static void *checked_calloc(size_t n, size_t size)
110 void *result = calloc(n, size);
118 // This function should technically be macro'd out if it's going to be used
119 // more than ocasionally. As of this writing, it'll actually never be called
120 // in real world bup scenarios (because our packs are < MAX_INT bytes).
121 static uint64_t htonll(uint64_t value)
123 static const int endian_test = 42;
125 if (*(char *)&endian_test == endian_test) // LSB-MSB
126 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
127 return value; // already in network byte order MSB-LSB
132 // Disabling sign-compare here should be fine since we're explicitly
133 // checking for a sign mismatch, i.e. if the signs don't match, then
134 // it doesn't matter what the value comparison says.
135 // FIXME: ... so should we reverse the order?
136 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
138 _Pragma("GCC diagnostic push"); \
139 _Pragma("GCC diagnostic ignored \"-Wsign-compare\""); \
141 int result = *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
142 _Pragma("GCC diagnostic pop"); \
147 // At the moment any code that calls INTEGER_TO_PY() will have to
148 // disable -Wtautological-compare for clang. See below.
150 #define INTEGER_TO_PY(x) \
151 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
155 #if PY_MAJOR_VERSION < 3
156 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
159 const long tmp = PyInt_AsLong(py);
160 if (tmp == -1 && PyErr_Occurred())
162 if (PyErr_ExceptionMatches(PyExc_OverflowError))
163 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
169 PyErr_Format(PyExc_OverflowError,
170 "negative %s cannot be converted to unsigned long", name);
179 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
181 #if PY_MAJOR_VERSION < 3
183 return bup_ulong_from_pyint(x, py, name);
186 if (!PyLong_Check(py))
188 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
192 const unsigned long tmp = PyLong_AsUnsignedLong(py);
193 if (PyErr_Occurred())
195 if (PyErr_ExceptionMatches(PyExc_OverflowError))
196 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
205 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
208 if (!bup_ulong_from_py(&tmp, py, name))
213 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
220 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
223 #if PY_MAJOR_VERSION < 3
227 if (bup_ulong_from_pyint(&tmp, py, name))
236 if (!PyLong_Check(py))
238 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
242 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
243 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
245 if (PyErr_ExceptionMatches(PyExc_OverflowError))
246 PyErr_Format(PyExc_OverflowError,
247 "%s too big for unsigned long long", name);
255 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
257 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
258 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
261 Py_ssize_t s1_len, s2_len;
262 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
264 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
266 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
267 const int cmp = memcmp(s1, s2, n);
269 return PyLong_FromLong(cmp);
270 if (s1_len == s2_len)
271 return PyLong_FromLong(0);;
272 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
276 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
277 #if __WIN32__ || __CYGWIN__
279 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
280 static void unpythonize_argv(void) { }
282 #else // not __WIN32__
284 // For some reason this isn't declared in Python.h
285 extern void Py_GetArgcArgv(int *argc, char ***argv);
287 static void unpythonize_argv(void)
292 Py_GetArgcArgv(&argc, &argv);
294 for (i = 0; i < argc-1; i++)
296 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
298 // The argv block doesn't work the way we expected; it's unsafe
304 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
306 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
310 p = strrchr(argv[1], '/');
316 memmove(argv[0], p, len);
317 memset(arge - diff, 0, diff);
318 for (i = 0; i < argc; i++)
319 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
324 #endif // not __WIN32__ or __CYGWIN__
327 static int write_all(int fd, const void *buf, const size_t count)
330 while (written < count)
332 const ssize_t rc = write(fd, buf + written, count - written);
341 static int uadd(unsigned long long *dest,
342 const unsigned long long x,
343 const unsigned long long y)
345 const unsigned long long result = x + y;
346 if (result < x || result < y)
353 static PyObject *append_sparse_region(const int fd, unsigned long long n)
358 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
360 const off_t off = lseek(fd, new_off, SEEK_CUR);
361 if (off == (off_t) -1)
362 return PyErr_SetFromErrno(PyExc_IOError);
369 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
371 unsigned long long prev_pending,
372 const unsigned long long count)
374 // Add count additional sparse zeros to prev_pending and store the
375 // result in new_pending, or if the total won't fit in
376 // new_pending, write some of the zeros to fd sparsely, and store
377 // the remaining sum in new_pending.
378 if (!uadd(new_pending, prev_pending, count))
380 PyObject *err = append_sparse_region(fd, prev_pending);
383 *new_pending = count;
389 static byte* find_not_zero(const byte * const start, const byte * const end)
391 // Return a pointer to first non-zero byte between start and end,
392 // or end if there isn't one.
393 assert(start <= end);
394 const unsigned char *cur = start;
395 while (cur < end && *cur == 0)
401 static byte* find_trailing_zeros(const byte * const start,
402 const byte * const end)
404 // Return a pointer to the start of any trailing run of zeros, or
405 // end if there isn't one.
406 assert(start <= end);
409 const byte * cur = end;
410 while (cur > start && *--cur == 0) {}
414 return (byte *) (cur + 1);
418 static byte *find_non_sparse_end(const byte * const start,
419 const byte * const end,
420 const ptrdiff_t min_len)
422 // Return the first pointer to a min_len sparse block in [start,
423 // end) if there is one, otherwise a pointer to the start of any
424 // trailing run of zeros. If there are no trailing zeros, return
430 // Probe in min_len jumps, searching backward from the jump
431 // destination for a non-zero byte. If such a byte is found, move
432 // just past it and try again.
433 const byte *candidate = start;
434 // End of any run of zeros, starting at candidate, that we've already seen
435 const byte *end_of_known_zeros = candidate;
436 while (end - candidate >= min_len) // Handle all min_len candidate blocks
438 const byte * const probe_end = candidate + min_len;
439 const byte * const trailing_zeros =
440 find_trailing_zeros(end_of_known_zeros, probe_end);
441 if (trailing_zeros == probe_end)
442 end_of_known_zeros = candidate = probe_end;
443 else if (trailing_zeros == end_of_known_zeros)
445 assert(candidate >= start);
446 assert(candidate <= end);
447 assert(*candidate == 0);
448 return (byte *) candidate;
452 candidate = trailing_zeros;
453 end_of_known_zeros = probe_end;
457 if (candidate == end)
460 // No min_len sparse run found, search backward from end
461 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
464 if (trailing_zeros == end_of_known_zeros)
466 assert(candidate >= start);
467 assert(candidate < end);
468 assert(*candidate == 0);
469 assert(end - candidate < min_len);
470 return (byte *) candidate;
473 if (trailing_zeros == end)
475 assert(*(end - 1) != 0);
479 assert(end - trailing_zeros < min_len);
480 assert(trailing_zeros >= start);
481 assert(trailing_zeros < end);
482 assert(*trailing_zeros == 0);
483 return (byte *) trailing_zeros;
487 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
490 unsigned char *buf = NULL;
492 PyObject *py_min_sparse_len, *py_prev_sparse_len;
493 if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
494 &fd, &buf, &sbuf_len,
495 &py_min_sparse_len, &py_prev_sparse_len))
497 ptrdiff_t min_sparse_len;
498 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
499 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
501 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
502 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
503 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
506 return PyErr_Format(PyExc_ValueError, "negative bufer length");
507 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
508 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
510 const byte * block = buf; // Start of pending block
511 const byte * const end = buf + buf_len;
512 unsigned long long zeros = prev_sparse_len;
515 assert(block <= end);
517 return PyLong_FromUnsignedLongLong(zeros);
521 // Look for the end of block, i.e. the next sparse run of
522 // at least min_sparse_len zeros, or the end of the
524 const byte * const probe = find_non_sparse_end(block + 1, end,
526 // Either at end of block, or end of non-sparse; write pending data
527 PyObject *err = append_sparse_region(fd, zeros);
530 int rc = write_all(fd, block, probe - block);
532 return PyErr_SetFromErrno(PyExc_IOError);
534 if (end - probe < min_sparse_len)
537 zeros = min_sparse_len;
538 block = probe + zeros;
542 // Should be in the first loop iteration, a sparse run of
543 // zeros, or nearly at the end of the block (within
545 const byte * const zeros_end = find_not_zero(block, end);
546 PyObject *err = record_sparse_zeros(&zeros, fd,
547 zeros, zeros_end - block);
550 assert(block <= zeros_end);
557 static PyObject *selftest(PyObject *self, PyObject *args)
559 if (!PyArg_ParseTuple(args, ""))
562 return Py_BuildValue("i", !bupsplit_selftest());
566 static PyObject *blobbits(PyObject *self, PyObject *args)
568 if (!PyArg_ParseTuple(args, ""))
570 return Py_BuildValue("i", BUP_BLOBBITS);
574 static PyObject *splitbuf(PyObject *self, PyObject *args)
576 // We stick to buffers in python 2 because they appear to be
577 // substantially smaller than memoryviews, and because
578 // zlib.compress() in python 2 can't accept a memoryview
579 // (cf. hashsplit.py).
580 int out = 0, bits = -1;
581 if (PY_MAJOR_VERSION > 2)
584 if (!PyArg_ParseTuple(args, "y*", &buf))
586 assert(buf.len <= INT_MAX);
587 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
588 PyBuffer_Release(&buf);
592 unsigned char *buf = NULL;
594 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
596 assert(len <= INT_MAX);
597 out = bupsplit_find_ofs(buf, len, &bits);
599 if (out) assert(bits >= BUP_BLOBBITS);
600 return Py_BuildValue("ii", out, bits);
604 static PyObject *bitmatch(PyObject *self, PyObject *args)
606 unsigned char *buf1 = NULL, *buf2 = NULL;
607 Py_ssize_t len1 = 0, len2 = 0;
611 if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
615 for (byte = 0; byte < len1 && byte < len2; byte++)
617 int b1 = buf1[byte], b2 = buf2[byte];
620 for (bit = 0; bit < 8; bit++)
621 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
627 assert(byte <= (INT_MAX >> 3));
628 return Py_BuildValue("i", byte*8 + bit);
632 static PyObject *firstword(PyObject *self, PyObject *args)
634 unsigned char *buf = NULL;
638 if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
644 v = ntohl(*(uint32_t *)buf);
645 return PyLong_FromUnsignedLong(v);
649 #define BLOOM2_HEADERLEN 16
651 static void to_bloom_address_bitmask4(const unsigned char *buf,
652 const int nbits, uint64_t *v, unsigned char *bitmask)
658 memcpy(&high, buf, 4);
659 mask = (1<<nbits) - 1;
660 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
661 bit = (raw >> (37-nbits)) & 0x7;
662 *v = (raw >> (40-nbits)) & mask;
666 static void to_bloom_address_bitmask5(const unsigned char *buf,
667 const int nbits, uint32_t *v, unsigned char *bitmask)
673 memcpy(&high, buf, 4);
674 mask = (1<<nbits) - 1;
676 bit = (raw >> (29-nbits)) & 0x7;
677 *v = (raw >> (32-nbits)) & mask;
681 #define BLOOM_SET_BIT(name, address, otype) \
682 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
684 unsigned char bitmask;\
686 address(buf, nbits, &v, &bitmask);\
687 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
689 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
690 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
693 #define BLOOM_GET_BIT(name, address, otype) \
694 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
696 unsigned char bitmask;\
698 address(buf, nbits, &v, &bitmask);\
699 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
701 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
702 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
705 static PyObject *bloom_add(PyObject *self, PyObject *args)
707 Py_buffer bloom, sha;
708 int nbits = 0, k = 0;
709 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
710 &bloom, &sha, &nbits, &k))
713 PyObject *result = NULL;
715 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
716 goto clean_and_return;
721 goto clean_and_return;
722 unsigned char *cur = sha.buf;
724 for (end = cur + sha.len; cur < end; cur += 20/k)
725 bloom_set_bit5(bloom.buf, cur, nbits);
730 goto clean_and_return;
731 unsigned char *cur = sha.buf;
732 unsigned char *end = cur + sha.len;
733 for (; cur < end; cur += 20/k)
734 bloom_set_bit4(bloom.buf, cur, nbits);
737 goto clean_and_return;
739 result = Py_BuildValue("n", sha.len / 20);
742 PyBuffer_Release(&bloom);
743 PyBuffer_Release(&sha);
747 static PyObject *bloom_contains(PyObject *self, PyObject *args)
750 unsigned char *sha = NULL;
752 int nbits = 0, k = 0;
753 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
754 &bloom, &sha, &len, &nbits, &k))
757 PyObject *result = NULL;
760 goto clean_and_return;
765 goto clean_and_return;
768 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
769 if (!bloom_get_bit5(bloom.buf, sha, nbits))
771 result = Py_BuildValue("Oi", Py_None, steps);
772 goto clean_and_return;
778 goto clean_and_return;
781 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
782 if (!bloom_get_bit4(bloom.buf, sha, nbits))
784 result = Py_BuildValue("Oi", Py_None, steps);
785 goto clean_and_return;
789 goto clean_and_return;
791 result = Py_BuildValue("ii", 1, k);
794 PyBuffer_Release(&bloom);
799 static uint32_t _extract_bits(unsigned char *buf, int nbits)
803 mask = (1<<nbits) - 1;
804 v = ntohl(*(uint32_t *)buf);
805 v = (v >> (32-nbits)) & mask;
810 static PyObject *extract_bits(PyObject *self, PyObject *args)
812 unsigned char *buf = NULL;
816 if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
822 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
827 unsigned char bytes[20];
830 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
832 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
845 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
848 int low, mid, high, c = 0;
851 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
853 idxs[*last_i] = NULL;
866 mid = (low + high) / 2;
867 c = _cmp_sha(idx->cur, idxs[mid]->cur);
879 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
884 static uint32_t _get_idx_i(struct idx *idx)
886 if (idx->cur_name == NULL)
887 return idx->name_base;
888 return ntohl(*idx->cur_name) + idx->name_base;
891 #define MIDX4_HEADERLEN 12
893 static PyObject *merge_into(PyObject *self, PyObject *args)
895 struct sha *sha_ptr, *sha_start = NULL;
896 uint32_t *table_ptr, *name_ptr, *name_start;
899 uint32_t count, prefix;
904 PyObject *py_total, *ilist = NULL;
905 if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
906 &fmap, &bits, &py_total, &ilist))
909 PyObject *result = NULL;
910 struct idx **idxs = NULL;
911 Py_ssize_t num_i = 0;
912 int *idx_buf_init = NULL;
913 Py_buffer *idx_buf = NULL;
915 if (!bup_uint_from_py(&total, py_total, "total"))
916 goto clean_and_return;
918 num_i = PyList_Size(ilist);
920 if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
921 goto clean_and_return;
922 if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
923 goto clean_and_return;
924 if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
925 goto clean_and_return;
927 for (i = 0; i < num_i; i++)
929 long len, sha_ofs, name_map_ofs;
930 if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
931 goto clean_and_return;
932 PyObject *itup = PyList_GetItem(ilist, i);
933 if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
934 &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
935 &idxs[i]->name_base))
938 idxs[i]->map = idx_buf[i].buf;
939 idxs[i]->bytes = idx_buf[i].len;
940 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
941 idxs[i]->end = &idxs[i]->cur[len];
943 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
945 idxs[i]->cur_name = NULL;
947 table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
948 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
949 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
951 Py_ssize_t last_i = num_i - 1;
958 if (count % 102424 == 0 && get_state(self)->istty2)
959 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
960 count*100.0/total, count, total);
962 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
963 while (prefix < new_prefix)
964 table_ptr[prefix++] = htonl(count);
965 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
966 *name_ptr++ = htonl(_get_idx_i(idx));
968 if (idx->cur_name != NULL)
970 _fix_idx_order(idxs, &last_i);
973 while (prefix < ((uint32_t) 1 << bits))
974 table_ptr[prefix++] = htonl(count);
975 assert(count == total);
976 assert(prefix == ((uint32_t) 1 << bits));
977 assert(sha_ptr == sha_start+count);
978 assert(name_ptr == name_start+count);
980 result = PyLong_FromUnsignedLong(count);
985 for (i = 0; i < num_i; i++)
987 PyBuffer_Release(&(idx_buf[i]));
993 for (i = 0; i < num_i; i++)
997 PyBuffer_Release(&fmap);
1001 #define FAN_ENTRIES 256
1003 static PyObject *write_idx(PyObject *self, PyObject *args)
1005 char *filename = NULL;
1006 PyObject *py_total, *idx = NULL;
1008 unsigned int total = 0;
1010 int i, j, ofs64_count;
1011 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1012 uint64_t *ofs64_ptr;
1013 struct sha *sha_ptr;
1016 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1017 &filename, &fmap, &idx, &py_total))
1020 PyObject *result = NULL;
1022 if (!bup_uint_from_py(&total, py_total, "total"))
1023 goto clean_and_return;
1025 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1027 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1029 goto clean_and_return;
1032 const char idx_header[] = "\377tOc\0\0\0\002";
1033 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1035 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1036 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1037 crc_ptr = (uint32_t *)&sha_ptr[total];
1038 ofs_ptr = (uint32_t *)&crc_ptr[total];
1039 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1043 for (i = 0; i < FAN_ENTRIES; ++i)
1046 part = PyList_GET_ITEM(idx, i);
1048 plen = PyList_GET_SIZE(part);
1050 *fan_ptr++ = htonl(count);
1051 for (j = 0; j < plen; ++j)
1053 unsigned char *sha = NULL;
1054 Py_ssize_t sha_len = 0;
1055 PyObject *crc_py, *ofs_py;
1057 unsigned PY_LONG_LONG ofs_ull;
1059 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1060 &sha, &sha_len, &crc_py, &ofs_py))
1061 goto clean_and_return;
1062 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1063 goto clean_and_return;
1064 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1065 goto clean_and_return;
1066 assert(crc <= UINT32_MAX);
1067 assert(ofs_ull <= UINT64_MAX);
1069 if (sha_len != sizeof(struct sha))
1070 goto clean_and_return;
1071 memcpy(sha_ptr++, sha, sizeof(struct sha));
1072 *crc_ptr++ = htonl(crc);
1073 if (ofs > 0x7fffffff)
1075 *ofs64_ptr++ = htonll(ofs);
1076 ofs = 0x80000000 | ofs64_count++;
1078 *ofs_ptr++ = htonl((uint32_t)ofs);
1082 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1085 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1086 goto clean_and_return;
1089 result = PyLong_FromUnsignedLong(count);
1092 PyBuffer_Release(&fmap);
1097 // I would have made this a lower-level function that just fills in a buffer
1098 // with random values, and then written those values from python. But that's
1099 // about 20% slower in my tests, and since we typically generate random
1100 // numbers for benchmarking other parts of bup, any slowness in generating
1101 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1102 // pseudorandom bytes much except for this anyway.
1103 static PyObject *write_random(PyObject *self, PyObject *args)
1105 uint32_t buf[1024/4];
1106 int fd = -1, seed = 0, verbose = 0;
1108 long long len = 0, kbytes = 0, written = 0;
1110 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1115 for (kbytes = 0; kbytes < len/1024; kbytes++)
1118 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1120 ret = write(fd, buf, sizeof(buf));
1124 if (ret < (int)sizeof(buf))
1126 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1127 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1130 // handle non-multiples of 1024
1134 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1136 ret = write(fd, buf, len % 1024);
1142 if (kbytes/1024 > 0)
1143 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1144 return Py_BuildValue("L", written);
1148 static PyObject *random_sha(PyObject *self, PyObject *args)
1150 static int seeded = 0;
1151 uint32_t shabuf[20/4];
1156 assert(sizeof(shabuf) == 20);
1157 srandom(time(NULL));
1161 if (!PyArg_ParseTuple(args, ""))
1164 memset(shabuf, 0, sizeof(shabuf));
1165 for (i=0; i < 20/4; i++)
1166 shabuf[i] = random();
1167 return Py_BuildValue("s#", shabuf, 20);
1171 static int _open_noatime(const char *filename, int attrs)
1173 int attrs_noatime, fd;
1176 attrs |= O_NOFOLLOW;
1179 attrs |= O_LARGEFILE;
1181 attrs_noatime = attrs;
1183 attrs_noatime |= O_NOATIME;
1185 fd = open(filename, attrs_noatime);
1186 if (fd < 0 && errno == EPERM)
1188 // older Linux kernels would return EPERM if you used O_NOATIME
1189 // and weren't the file's owner. This pointless restriction was
1190 // relaxed eventually, but we have to handle it anyway.
1191 // (VERY old kernels didn't recognized O_NOATIME, but they would
1192 // just harmlessly ignore it, so this branch won't trigger)
1193 fd = open(filename, attrs);
1199 static PyObject *open_noatime(PyObject *self, PyObject *args)
1201 char *filename = NULL;
1203 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1205 fd = _open_noatime(filename, 0);
1207 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1208 return Py_BuildValue("i", fd);
1212 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1215 long long llofs, lllen = 0;
1216 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1219 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1220 return PyErr_Format(PyExc_OverflowError,
1221 "fadvise offset overflows off_t");
1222 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1223 return PyErr_Format(PyExc_OverflowError,
1224 "fadvise length overflows off_t");
1225 #ifdef POSIX_FADV_DONTNEED
1226 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1228 return Py_BuildValue("");
1232 // Currently the Linux kernel and FUSE disagree over the type for
1233 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1234 // but FUSE chose long (matching the declaration in linux/fs.h). So
1235 // if you use int, and then traverse a FUSE filesystem, you may
1236 // corrupt the stack. But if you use long, then you may get invalid
1237 // results on big-endian systems.
1239 // For now, we just use long, and then disable Linux attrs entirely
1240 // (with a warning) in helpers.py on systems that are affected.
1242 #ifdef BUP_HAVE_FILE_ATTRS
1243 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1250 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1253 fd = _open_noatime(path, O_NONBLOCK);
1255 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1257 attr = 0; // Handle int/long mismatch (see above)
1258 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1262 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1265 assert(attr <= UINT_MAX); // Kernel type is actually int
1266 return PyLong_FromUnsignedLong(attr);
1268 #endif /* def BUP_HAVE_FILE_ATTRS */
1272 #ifdef BUP_HAVE_FILE_ATTRS
1273 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1276 unsigned long orig_attr;
1282 if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1285 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1288 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1290 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1292 // Restrict attr to modifiable flags acdeijstuADST -- see
1293 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1294 // in pf.c flags_array[].
1295 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1296 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1297 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1298 | FS_TOPDIR_FL | FS_NOCOW_FL;
1300 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1301 orig_attr = 0; // Handle int/long mismatch (see above)
1302 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1306 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1308 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1309 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1311 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1315 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1319 return Py_BuildValue("O", Py_None);
1321 #endif /* def BUP_HAVE_FILE_ATTRS */
1324 #ifndef HAVE_UTIMENSAT
1326 #error "cannot find utimensat or utimes()"
1328 #ifndef HAVE_LUTIMES
1329 #error "cannot find utimensat or lutimes()"
1333 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1337 const long long lltmp = PyLong_AsLongLong(pylong); \
1338 if (lltmp == -1 && PyErr_Occurred()) \
1340 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1342 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1343 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1345 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1351 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1359 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1368 #ifdef HAVE_UTIMENSAT
1370 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1375 PyObject *access_py, *modification_py;
1376 struct timespec ts[2];
1378 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1381 &access_py, &(ts[0].tv_nsec),
1382 &modification_py, &(ts[1].tv_nsec),
1387 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1390 PyErr_SetString(PyExc_ValueError,
1391 "unable to convert access time seconds for utimensat");
1394 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1397 PyErr_SetString(PyExc_ValueError,
1398 "unable to convert modification time seconds for utimensat");
1401 rc = utimensat(fd, path, ts, flag);
1403 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1405 return Py_BuildValue("O", Py_None);
1408 #endif /* def HAVE_UTIMENSAT */
1411 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1413 static int bup_parse_xutimes_args(char **path,
1414 struct timeval tv[2],
1417 PyObject *access_py, *modification_py;
1418 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1420 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1422 &access_py, &access_us,
1423 &modification_py, &modification_us))
1427 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1430 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1433 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1435 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1438 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1441 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1444 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1446 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1452 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1456 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1459 struct timeval tv[2];
1460 if (!bup_parse_xutimes_args(&path, tv, args))
1462 int rc = utimes(path, tv);
1464 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1465 return Py_BuildValue("O", Py_None);
1467 #endif /* def HAVE_UTIMES */
1471 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1474 struct timeval tv[2];
1475 if (!bup_parse_xutimes_args(&path, tv, args))
1477 int rc = lutimes(path, tv);
1479 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1481 return Py_BuildValue("O", Py_None);
1483 #endif /* def HAVE_LUTIMES */
1486 #ifdef HAVE_STAT_ST_ATIM
1487 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1488 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1489 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1490 #elif defined HAVE_STAT_ST_ATIMENSEC
1491 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1492 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1493 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1495 # define BUP_STAT_ATIME_NS(st) 0
1496 # define BUP_STAT_MTIME_NS(st) 0
1497 # define BUP_STAT_CTIME_NS(st) 0
1501 #pragma clang diagnostic push
1502 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1504 static PyObject *stat_struct_to_py(const struct stat *st,
1505 const char *filename,
1508 // We can check the known (via POSIX) signed and unsigned types at
1509 // compile time, but not (easily) the unspecified types, so handle
1510 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1512 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1513 INTEGER_TO_PY(st->st_mode),
1514 (unsigned PY_LONG_LONG) st->st_ino,
1515 INTEGER_TO_PY(st->st_dev),
1516 INTEGER_TO_PY(st->st_nlink),
1517 INTEGER_TO_PY(st->st_uid),
1518 INTEGER_TO_PY(st->st_gid),
1519 INTEGER_TO_PY(st->st_rdev),
1520 (PY_LONG_LONG) st->st_size,
1521 INTEGER_TO_PY(st->st_atime),
1522 (long) BUP_STAT_ATIME_NS(st),
1523 INTEGER_TO_PY(st->st_mtime),
1524 (long) BUP_STAT_MTIME_NS(st),
1525 INTEGER_TO_PY(st->st_ctime),
1526 (long) BUP_STAT_CTIME_NS(st));
1529 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1531 static PyObject *bup_stat(PyObject *self, PyObject *args)
1536 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1540 rc = stat(filename, &st);
1542 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1543 return stat_struct_to_py(&st, filename, 0);
1547 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1552 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1556 rc = lstat(filename, &st);
1558 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1559 return stat_struct_to_py(&st, filename, 0);
1563 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1567 if (!PyArg_ParseTuple(args, "i", &fd))
1571 rc = fstat(fd, &st);
1573 return PyErr_SetFromErrno(PyExc_OSError);
1574 return stat_struct_to_py(&st, NULL, fd);
1578 #ifdef HAVE_TM_TM_GMTOFF
1579 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1583 if (!PyArg_ParseTuple(args, "L", &lltime))
1585 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1586 return PyErr_Format(PyExc_OverflowError, "time value too large");
1590 if(localtime_r(&ttime, &tm) == NULL)
1591 return PyErr_SetFromErrno(PyExc_OSError);
1593 // Match the Python struct_time values.
1594 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1595 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1596 tm.tm_hour, tm.tm_min, tm.tm_sec,
1597 tm.tm_wday, tm.tm_yday + 1,
1598 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1600 #endif /* def HAVE_TM_TM_GMTOFF */
1603 #ifdef BUP_MINCORE_BUF_TYPE
1604 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1606 Py_buffer src, dest;
1607 PyObject *py_src_n, *py_src_off, *py_dest_off;
1609 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1610 &src, &py_src_n, &py_src_off,
1611 &dest, &py_dest_off))
1614 PyObject *result = NULL;
1616 unsigned long long src_n, src_off, dest_off;
1617 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1618 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1619 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1620 goto clean_and_return;
1622 unsigned long long src_region_end;
1623 if (!uadd(&src_region_end, src_off, src_n)) {
1624 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1625 goto clean_and_return;
1627 assert(src.len >= 0);
1628 if (src_region_end > (unsigned long long) src.len) {
1629 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1630 goto clean_and_return;
1633 unsigned long long dest_size;
1634 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1635 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1636 goto clean_and_return;
1638 if (dest_off > dest_size) {
1639 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1640 goto clean_and_return;
1644 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1645 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1646 goto clean_and_return;
1648 int rc = mincore((void *)(src.buf + src_off), src_n,
1649 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1651 result = PyErr_SetFromErrno(PyExc_OSError);
1652 goto clean_and_return;
1654 result = Py_BuildValue("O", Py_None);
1657 PyBuffer_Release(&src);
1658 PyBuffer_Release(&dest);
1661 #endif /* def BUP_MINCORE_BUF_TYPE */
1664 static PyMethodDef helper_methods[] = {
1665 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1666 "Write buf excepting zeros at the end. Return trailing zero count." },
1667 { "selftest", selftest, METH_VARARGS,
1668 "Check that the rolling checksum rolls correctly (for unit tests)." },
1669 { "blobbits", blobbits, METH_VARARGS,
1670 "Return the number of bits in the rolling checksum." },
1671 { "splitbuf", splitbuf, METH_VARARGS,
1672 "Split a list of strings based on a rolling checksum." },
1673 { "bitmatch", bitmatch, METH_VARARGS,
1674 "Count the number of matching prefix bits between two strings." },
1675 { "firstword", firstword, METH_VARARGS,
1676 "Return an int corresponding to the first 32 bits of buf." },
1677 { "bloom_contains", bloom_contains, METH_VARARGS,
1678 "Check if a bloom filter of 2^nbits bytes contains an object" },
1679 { "bloom_add", bloom_add, METH_VARARGS,
1680 "Add an object to a bloom filter of 2^nbits bytes" },
1681 { "extract_bits", extract_bits, METH_VARARGS,
1682 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1683 { "merge_into", merge_into, METH_VARARGS,
1684 "Merges a bunch of idx and midx files into a single midx." },
1685 { "write_idx", write_idx, METH_VARARGS,
1686 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1687 { "write_random", write_random, METH_VARARGS,
1688 "Write random bytes to the given file descriptor" },
1689 { "random_sha", random_sha, METH_VARARGS,
1690 "Return a random 20-byte string" },
1691 { "open_noatime", open_noatime, METH_VARARGS,
1692 "open() the given filename for read with O_NOATIME if possible" },
1693 { "fadvise_done", fadvise_done, METH_VARARGS,
1694 "Inform the kernel that we're finished with earlier parts of a file" },
1695 #ifdef BUP_HAVE_FILE_ATTRS
1696 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1697 "Return the Linux attributes for the given file." },
1699 #ifdef BUP_HAVE_FILE_ATTRS
1700 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1701 "Set the Linux attributes for the given file." },
1703 #ifdef HAVE_UTIMENSAT
1704 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1705 "Change path timestamps with nanosecond precision (POSIX)." },
1708 { "bup_utimes", bup_utimes, METH_VARARGS,
1709 "Change path timestamps with microsecond precision." },
1712 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1713 "Change path timestamps with microsecond precision;"
1714 " don't follow symlinks." },
1716 { "stat", bup_stat, METH_VARARGS,
1717 "Extended version of stat." },
1718 { "lstat", bup_lstat, METH_VARARGS,
1719 "Extended version of lstat." },
1720 { "fstat", bup_fstat, METH_VARARGS,
1721 "Extended version of fstat." },
1722 #ifdef HAVE_TM_TM_GMTOFF
1723 { "localtime", bup_localtime, METH_VARARGS,
1724 "Return struct_time elements plus the timezone offset and name." },
1726 { "bytescmp", bup_bytescmp, METH_VARARGS,
1727 "Return a negative value if x < y, zero if equal, positive otherwise."},
1728 #ifdef BUP_MINCORE_BUF_TYPE
1729 { "mincore", bup_mincore, METH_VARARGS,
1730 "For mincore(src, src_n, src_off, dest, dest_off)"
1731 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1733 { NULL, NULL, 0, NULL }, // sentinel
1736 static void test_integral_assignment_fits(void)
1738 assert(sizeof(signed short) == sizeof(unsigned short));
1739 assert(sizeof(signed short) < sizeof(signed long long));
1740 assert(sizeof(signed short) < sizeof(unsigned long long));
1741 assert(sizeof(unsigned short) < sizeof(signed long long));
1742 assert(sizeof(unsigned short) < sizeof(unsigned long long));
1743 assert(sizeof(Py_ssize_t) <= sizeof(size_t));
1745 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
1746 unsigned short us, usmax = USHRT_MAX;
1747 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
1748 unsigned long long ullmax = ULLONG_MAX;
1750 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
1751 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
1752 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
1753 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
1754 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
1755 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
1757 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
1758 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
1759 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
1760 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
1761 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
1765 static int setup_module(PyObject *m)
1767 // FIXME: migrate these tests to configure, or at least don't
1768 // possibly crash the whole application. Check against the type
1769 // we're going to use when passing to python. Other stat types
1770 // are tested at runtime.
1771 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1772 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1773 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1774 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1775 // Just be sure (relevant when passing timestamps back to Python above).
1776 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1777 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1779 test_integral_assignment_fits();
1781 // Originally required by append_sparse_region()
1784 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1786 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1792 #pragma clang diagnostic push
1793 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1796 value = INTEGER_TO_PY(INT_MAX);
1797 PyObject_SetAttrString(m, "INT_MAX", value);
1799 value = INTEGER_TO_PY(UINT_MAX);
1800 PyObject_SetAttrString(m, "UINT_MAX", value);
1803 #ifdef HAVE_UTIMENSAT
1806 value = INTEGER_TO_PY(AT_FDCWD);
1807 PyObject_SetAttrString(m, "AT_FDCWD", value);
1809 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1810 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1812 value = INTEGER_TO_PY(UTIME_NOW);
1813 PyObject_SetAttrString(m, "UTIME_NOW", value);
1817 #ifdef BUP_HAVE_MINCORE_INCORE
1820 value = INTEGER_TO_PY(MINCORE_INCORE);
1821 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1825 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1827 e = getenv("BUP_FORCE_TTY");
1828 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1834 #if PY_MAJOR_VERSION < 3
1836 PyMODINIT_FUNC init_helpers(void)
1838 PyObject *m = Py_InitModule("_helpers", helper_methods);
1842 if (!setup_module(m))
1849 # else // PY_MAJOR_VERSION >= 3
1851 static struct PyModuleDef helpers_def = {
1852 PyModuleDef_HEAD_INIT,
1858 NULL, // helpers_traverse,
1859 NULL, // helpers_clear,
1863 PyMODINIT_FUNC PyInit__helpers(void)
1865 PyObject *module = PyModule_Create(&helpers_def);
1868 if (!setup_module(module))
1876 #endif // PY_MAJOR_VERSION >= 3