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 INTGER_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;
705 for (unsigned char *end = cur + sha.len; cur < end; cur += 20/k)
706 bloom_set_bit5(bloom.buf, cur, nbits);
711 goto clean_and_return;
712 unsigned char *cur = sha.buf;
713 unsigned char *end = cur + sha.len;
714 for (; cur < end; cur += 20/k)
715 bloom_set_bit4(bloom.buf, cur, nbits);
718 goto clean_and_return;
720 result = Py_BuildValue("n", sha.len / 20);
723 PyBuffer_Release(&bloom);
724 PyBuffer_Release(&sha);
728 static PyObject *bloom_contains(PyObject *self, PyObject *args)
731 unsigned char *sha = NULL;
733 int nbits = 0, k = 0;
734 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
735 &bloom, &sha, &len, &nbits, &k))
738 PyObject *result = NULL;
741 goto clean_and_return;
746 goto clean_and_return;
749 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
750 if (!bloom_get_bit5(bloom.buf, sha, nbits))
752 result = Py_BuildValue("Oi", Py_None, steps);
753 goto clean_and_return;
759 goto clean_and_return;
762 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
763 if (!bloom_get_bit4(bloom.buf, sha, nbits))
765 result = Py_BuildValue("Oi", Py_None, steps);
766 goto clean_and_return;
770 goto clean_and_return;
772 result = Py_BuildValue("ii", 1, k);
775 PyBuffer_Release(&bloom);
780 static uint32_t _extract_bits(unsigned char *buf, int nbits)
784 mask = (1<<nbits) - 1;
785 v = ntohl(*(uint32_t *)buf);
786 v = (v >> (32-nbits)) & mask;
791 static PyObject *extract_bits(PyObject *self, PyObject *args)
793 unsigned char *buf = NULL;
797 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
803 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
808 unsigned char bytes[20];
811 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
813 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
826 static void _fix_idx_order(struct idx **idxs, int *last_i)
829 int low, mid, high, c = 0;
832 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
834 idxs[*last_i] = NULL;
847 mid = (low + high) / 2;
848 c = _cmp_sha(idx->cur, idxs[mid]->cur);
860 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
865 static uint32_t _get_idx_i(struct idx *idx)
867 if (idx->cur_name == NULL)
868 return idx->name_base;
869 return ntohl(*idx->cur_name) + idx->name_base;
872 #define MIDX4_HEADERLEN 12
874 static PyObject *merge_into(PyObject *self, PyObject *args)
876 PyObject *py_total, *ilist = NULL;
877 unsigned char *fmap = NULL;
878 struct sha *sha_ptr, *sha_start = NULL;
879 uint32_t *table_ptr, *name_ptr, *name_start;
880 struct idx **idxs = NULL;
884 uint32_t count, prefix;
888 if (!PyArg_ParseTuple(args, "w#iOO",
889 &fmap, &flen, &bits, &py_total, &ilist))
892 if (!bup_uint_from_py(&total, py_total, "total"))
895 num_i = PyList_Size(ilist);
896 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
898 for (i = 0; i < num_i; i++)
900 long len, sha_ofs, name_map_ofs;
901 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
902 PyObject *itup = PyList_GetItem(ilist, i);
903 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
904 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
906 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
907 idxs[i]->end = &idxs[i]->cur[len];
909 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
911 idxs[i]->cur_name = NULL;
913 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
914 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
915 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
924 if (count % 102424 == 0 && get_state(self)->istty2)
925 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
926 count*100.0/total, count, total);
928 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
929 while (prefix < new_prefix)
930 table_ptr[prefix++] = htonl(count);
931 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
932 *name_ptr++ = htonl(_get_idx_i(idx));
934 if (idx->cur_name != NULL)
936 _fix_idx_order(idxs, &last_i);
939 while (prefix < ((uint32_t) 1 << bits))
940 table_ptr[prefix++] = htonl(count);
941 assert(count == total);
942 assert(prefix == ((uint32_t) 1 << bits));
943 assert(sha_ptr == sha_start+count);
944 assert(name_ptr == name_start+count);
947 return PyLong_FromUnsignedLong(count);
950 #define FAN_ENTRIES 256
952 static PyObject *write_idx(PyObject *self, PyObject *args)
954 char *filename = NULL;
955 PyObject *py_total, *idx = NULL;
957 unsigned char *fmap = NULL;
959 unsigned int total = 0;
961 int i, j, ofs64_count;
962 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
966 if (!PyArg_ParseTuple(args, "sw#OO",
967 &filename, &fmap, &flen, &idx, &py_total))
970 if (!bup_uint_from_py(&total, py_total, "total"))
973 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
974 return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
977 const char idx_header[] = "\377tOc\0\0\0\002";
978 memcpy (fmap, idx_header, sizeof(idx_header) - 1);
980 fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
981 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
982 crc_ptr = (uint32_t *)&sha_ptr[total];
983 ofs_ptr = (uint32_t *)&crc_ptr[total];
984 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
988 for (i = 0; i < FAN_ENTRIES; ++i)
991 part = PyList_GET_ITEM(idx, i);
993 plen = PyList_GET_SIZE(part);
995 *fan_ptr++ = htonl(count);
996 for (j = 0; j < plen; ++j)
998 unsigned char *sha = NULL;
999 Py_ssize_t sha_len = 0;
1000 PyObject *crc_py, *ofs_py;
1002 unsigned PY_LONG_LONG ofs_ull;
1004 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
1005 &sha, &sha_len, &crc_py, &ofs_py))
1007 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1009 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1011 assert(crc <= UINT32_MAX);
1012 assert(ofs_ull <= UINT64_MAX);
1014 if (sha_len != sizeof(struct sha))
1016 memcpy(sha_ptr++, sha, sizeof(struct sha));
1017 *crc_ptr++ = htonl(crc);
1018 if (ofs > 0x7fffffff)
1020 *ofs64_ptr++ = htonll(ofs);
1021 ofs = 0x80000000 | ofs64_count++;
1023 *ofs_ptr++ = htonl((uint32_t)ofs);
1027 int rc = msync(fmap, flen, MS_ASYNC);
1029 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1031 return PyLong_FromUnsignedLong(count);
1035 // I would have made this a lower-level function that just fills in a buffer
1036 // with random values, and then written those values from python. But that's
1037 // about 20% slower in my tests, and since we typically generate random
1038 // numbers for benchmarking other parts of bup, any slowness in generating
1039 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1040 // pseudorandom bytes much except for this anyway.
1041 static PyObject *write_random(PyObject *self, PyObject *args)
1043 uint32_t buf[1024/4];
1044 int fd = -1, seed = 0, verbose = 0;
1046 long long len = 0, kbytes = 0, written = 0;
1048 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1053 for (kbytes = 0; kbytes < len/1024; kbytes++)
1056 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1058 ret = write(fd, buf, sizeof(buf));
1062 if (ret < (int)sizeof(buf))
1064 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1065 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1068 // handle non-multiples of 1024
1072 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1074 ret = write(fd, buf, len % 1024);
1080 if (kbytes/1024 > 0)
1081 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1082 return Py_BuildValue("L", written);
1086 static PyObject *random_sha(PyObject *self, PyObject *args)
1088 static int seeded = 0;
1089 uint32_t shabuf[20/4];
1094 assert(sizeof(shabuf) == 20);
1095 srandom(time(NULL));
1099 if (!PyArg_ParseTuple(args, ""))
1102 memset(shabuf, 0, sizeof(shabuf));
1103 for (i=0; i < 20/4; i++)
1104 shabuf[i] = random();
1105 return Py_BuildValue("s#", shabuf, 20);
1109 static int _open_noatime(const char *filename, int attrs)
1111 int attrs_noatime, fd;
1114 attrs |= O_NOFOLLOW;
1117 attrs |= O_LARGEFILE;
1119 attrs_noatime = attrs;
1121 attrs_noatime |= O_NOATIME;
1123 fd = open(filename, attrs_noatime);
1124 if (fd < 0 && errno == EPERM)
1126 // older Linux kernels would return EPERM if you used O_NOATIME
1127 // and weren't the file's owner. This pointless restriction was
1128 // relaxed eventually, but we have to handle it anyway.
1129 // (VERY old kernels didn't recognized O_NOATIME, but they would
1130 // just harmlessly ignore it, so this branch won't trigger)
1131 fd = open(filename, attrs);
1137 static PyObject *open_noatime(PyObject *self, PyObject *args)
1139 char *filename = NULL;
1141 if (!PyArg_ParseTuple(args, "s", &filename))
1143 fd = _open_noatime(filename, 0);
1145 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1146 return Py_BuildValue("i", fd);
1150 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1153 long long llofs, lllen = 0;
1154 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1157 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1158 return PyErr_Format(PyExc_OverflowError,
1159 "fadvise offset overflows off_t");
1160 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1161 return PyErr_Format(PyExc_OverflowError,
1162 "fadvise length overflows off_t");
1163 #ifdef POSIX_FADV_DONTNEED
1164 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1166 return Py_BuildValue("");
1170 // Currently the Linux kernel and FUSE disagree over the type for
1171 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1172 // but FUSE chose long (matching the declaration in linux/fs.h). So
1173 // if you use int, and then traverse a FUSE filesystem, you may
1174 // corrupt the stack. But if you use long, then you may get invalid
1175 // results on big-endian systems.
1177 // For now, we just use long, and then disable Linux attrs entirely
1178 // (with a warning) in helpers.py on systems that are affected.
1180 #ifdef BUP_HAVE_FILE_ATTRS
1181 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1188 if (!PyArg_ParseTuple(args, "s", &path))
1191 fd = _open_noatime(path, O_NONBLOCK);
1193 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1195 attr = 0; // Handle int/long mismatch (see above)
1196 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1200 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1203 assert(attr <= UINT_MAX); // Kernel type is actually int
1204 return PyLong_FromUnsignedLong(attr);
1206 #endif /* def BUP_HAVE_FILE_ATTRS */
1210 #ifdef BUP_HAVE_FILE_ATTRS
1211 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1214 unsigned long orig_attr;
1220 if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1223 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1226 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1228 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1230 // Restrict attr to modifiable flags acdeijstuADST -- see
1231 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1232 // in pf.c flags_array[].
1233 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1234 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1235 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1236 | FS_TOPDIR_FL | FS_NOCOW_FL;
1238 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1239 orig_attr = 0; // Handle int/long mismatch (see above)
1240 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1244 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1246 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1247 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1249 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1253 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1257 return Py_BuildValue("O", Py_None);
1259 #endif /* def BUP_HAVE_FILE_ATTRS */
1262 #ifndef HAVE_UTIMENSAT
1264 #error "cannot find utimensat or utimes()"
1266 #ifndef HAVE_LUTIMES
1267 #error "cannot find utimensat or lutimes()"
1271 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1275 const long long lltmp = PyLong_AsLongLong(pylong); \
1276 if (lltmp == -1 && PyErr_Occurred()) \
1278 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1280 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1281 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1283 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1289 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1297 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1306 #ifdef HAVE_UTIMENSAT
1308 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1313 PyObject *access_py, *modification_py;
1314 struct timespec ts[2];
1316 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1319 &access_py, &(ts[0].tv_nsec),
1320 &modification_py, &(ts[1].tv_nsec),
1325 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1328 PyErr_SetString(PyExc_ValueError,
1329 "unable to convert access time seconds for utimensat");
1332 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1335 PyErr_SetString(PyExc_ValueError,
1336 "unable to convert modification time seconds for utimensat");
1339 rc = utimensat(fd, path, ts, flag);
1341 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1343 return Py_BuildValue("O", Py_None);
1346 #endif /* def HAVE_UTIMENSAT */
1349 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1351 static int bup_parse_xutimes_args(char **path,
1352 struct timeval tv[2],
1355 PyObject *access_py, *modification_py;
1356 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1358 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1360 &access_py, &access_us,
1361 &modification_py, &modification_us))
1365 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1368 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1371 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1373 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1376 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1379 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1382 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1384 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1390 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1394 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1397 struct timeval tv[2];
1398 if (!bup_parse_xutimes_args(&path, tv, args))
1400 int rc = utimes(path, tv);
1402 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1403 return Py_BuildValue("O", Py_None);
1405 #endif /* def HAVE_UTIMES */
1409 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1412 struct timeval tv[2];
1413 if (!bup_parse_xutimes_args(&path, tv, args))
1415 int rc = lutimes(path, tv);
1417 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1419 return Py_BuildValue("O", Py_None);
1421 #endif /* def HAVE_LUTIMES */
1424 #ifdef HAVE_STAT_ST_ATIM
1425 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1426 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1427 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1428 #elif defined HAVE_STAT_ST_ATIMENSEC
1429 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1430 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1431 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1433 # define BUP_STAT_ATIME_NS(st) 0
1434 # define BUP_STAT_MTIME_NS(st) 0
1435 # define BUP_STAT_CTIME_NS(st) 0
1439 #pragma clang diagnostic push
1440 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1442 static PyObject *stat_struct_to_py(const struct stat *st,
1443 const char *filename,
1446 // We can check the known (via POSIX) signed and unsigned types at
1447 // compile time, but not (easily) the unspecified types, so handle
1448 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1450 return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1451 INTEGER_TO_PY(st->st_mode),
1452 (unsigned PY_LONG_LONG) st->st_ino,
1453 INTEGER_TO_PY(st->st_dev),
1454 INTEGER_TO_PY(st->st_nlink),
1455 INTEGER_TO_PY(st->st_uid),
1456 INTEGER_TO_PY(st->st_gid),
1457 INTEGER_TO_PY(st->st_rdev),
1458 (PY_LONG_LONG) st->st_size,
1459 INTEGER_TO_PY(st->st_atime),
1460 (long) BUP_STAT_ATIME_NS(st),
1461 INTEGER_TO_PY(st->st_mtime),
1462 (long) BUP_STAT_MTIME_NS(st),
1463 INTEGER_TO_PY(st->st_ctime),
1464 (long) BUP_STAT_CTIME_NS(st));
1467 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1469 static PyObject *bup_stat(PyObject *self, PyObject *args)
1474 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1478 rc = stat(filename, &st);
1480 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1481 return stat_struct_to_py(&st, filename, 0);
1485 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1490 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1494 rc = lstat(filename, &st);
1496 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1497 return stat_struct_to_py(&st, filename, 0);
1501 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1505 if (!PyArg_ParseTuple(args, "i", &fd))
1509 rc = fstat(fd, &st);
1511 return PyErr_SetFromErrno(PyExc_OSError);
1512 return stat_struct_to_py(&st, NULL, fd);
1516 #ifdef HAVE_TM_TM_GMTOFF
1517 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1521 if (!PyArg_ParseTuple(args, "L", &lltime))
1523 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1524 return PyErr_Format(PyExc_OverflowError, "time value too large");
1528 if(localtime_r(&ttime, &tm) == NULL)
1529 return PyErr_SetFromErrno(PyExc_OSError);
1531 // Match the Python struct_time values.
1532 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1533 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1534 tm.tm_hour, tm.tm_min, tm.tm_sec,
1535 tm.tm_wday, tm.tm_yday + 1,
1536 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1538 #endif /* def HAVE_TM_TM_GMTOFF */
1541 #ifdef BUP_MINCORE_BUF_TYPE
1542 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1544 Py_buffer src, dest;
1545 PyObject *py_src_n, *py_src_off, *py_dest_off;
1547 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1548 &src, &py_src_n, &py_src_off,
1549 &dest, &py_dest_off))
1552 PyObject *result = NULL;
1554 unsigned long long src_n, src_off, dest_off;
1555 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1556 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1557 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1558 goto clean_and_return;
1560 unsigned long long src_region_end;
1561 if (!uadd(&src_region_end, src_off, src_n)) {
1562 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1563 goto clean_and_return;
1565 assert(src.len >= 0);
1566 if (src_region_end > (unsigned long long) src.len) {
1567 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1568 goto clean_and_return;
1571 unsigned long long dest_size;
1572 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1573 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1574 goto clean_and_return;
1576 if (dest_off > dest_size) {
1577 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1578 goto clean_and_return;
1582 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1583 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1584 goto clean_and_return;
1586 int rc = mincore((void *)(src.buf + src_off), src_n,
1587 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1589 result = PyErr_SetFromErrno(PyExc_OSError);
1590 goto clean_and_return;
1592 result = Py_BuildValue("O", Py_None);
1595 PyBuffer_Release(&src);
1596 PyBuffer_Release(&dest);
1599 #endif /* def BUP_MINCORE_BUF_TYPE */
1602 static PyMethodDef helper_methods[] = {
1603 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1604 "Write buf excepting zeros at the end. Return trailing zero count." },
1605 { "selftest", selftest, METH_VARARGS,
1606 "Check that the rolling checksum rolls correctly (for unit tests)." },
1607 { "blobbits", blobbits, METH_VARARGS,
1608 "Return the number of bits in the rolling checksum." },
1609 { "splitbuf", splitbuf, METH_VARARGS,
1610 "Split a list of strings based on a rolling checksum." },
1611 { "bitmatch", bitmatch, METH_VARARGS,
1612 "Count the number of matching prefix bits between two strings." },
1613 { "firstword", firstword, METH_VARARGS,
1614 "Return an int corresponding to the first 32 bits of buf." },
1615 { "bloom_contains", bloom_contains, METH_VARARGS,
1616 "Check if a bloom filter of 2^nbits bytes contains an object" },
1617 { "bloom_add", bloom_add, METH_VARARGS,
1618 "Add an object to a bloom filter of 2^nbits bytes" },
1619 { "extract_bits", extract_bits, METH_VARARGS,
1620 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1621 { "merge_into", merge_into, METH_VARARGS,
1622 "Merges a bunch of idx and midx files into a single midx." },
1623 { "write_idx", write_idx, METH_VARARGS,
1624 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1625 { "write_random", write_random, METH_VARARGS,
1626 "Write random bytes to the given file descriptor" },
1627 { "random_sha", random_sha, METH_VARARGS,
1628 "Return a random 20-byte string" },
1629 { "open_noatime", open_noatime, METH_VARARGS,
1630 "open() the given filename for read with O_NOATIME if possible" },
1631 { "fadvise_done", fadvise_done, METH_VARARGS,
1632 "Inform the kernel that we're finished with earlier parts of a file" },
1633 #ifdef BUP_HAVE_FILE_ATTRS
1634 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1635 "Return the Linux attributes for the given file." },
1637 #ifdef BUP_HAVE_FILE_ATTRS
1638 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1639 "Set the Linux attributes for the given file." },
1641 #ifdef HAVE_UTIMENSAT
1642 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1643 "Change path timestamps with nanosecond precision (POSIX)." },
1646 { "bup_utimes", bup_utimes, METH_VARARGS,
1647 "Change path timestamps with microsecond precision." },
1650 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1651 "Change path timestamps with microsecond precision;"
1652 " don't follow symlinks." },
1654 { "stat", bup_stat, METH_VARARGS,
1655 "Extended version of stat." },
1656 { "lstat", bup_lstat, METH_VARARGS,
1657 "Extended version of lstat." },
1658 { "fstat", bup_fstat, METH_VARARGS,
1659 "Extended version of fstat." },
1660 #ifdef HAVE_TM_TM_GMTOFF
1661 { "localtime", bup_localtime, METH_VARARGS,
1662 "Return struct_time elements plus the timezone offset and name." },
1664 { "bytescmp", bup_bytescmp, METH_VARARGS,
1665 "Return a negative value if x < y, zero if equal, positive otherwise."},
1666 #ifdef BUP_MINCORE_BUF_TYPE
1667 { "mincore", bup_mincore, METH_VARARGS,
1668 "For mincore(src, src_n, src_off, dest, dest_off)"
1669 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1671 { NULL, NULL, 0, NULL }, // sentinel
1674 static void test_integral_assignment_fits(void)
1676 assert(sizeof(signed short) == sizeof(unsigned short));
1677 assert(sizeof(signed short) < sizeof(signed long long));
1678 assert(sizeof(signed short) < sizeof(unsigned long long));
1679 assert(sizeof(unsigned short) < sizeof(signed long long));
1680 assert(sizeof(unsigned short) < sizeof(unsigned long long));
1682 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
1683 unsigned short us, usmax = USHRT_MAX;
1684 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
1685 unsigned long long ullmax = ULLONG_MAX;
1687 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
1688 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
1689 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
1690 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
1691 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
1692 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
1694 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
1695 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
1696 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
1697 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
1698 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
1702 static int setup_module(PyObject *m)
1704 // FIXME: migrate these tests to configure, or at least don't
1705 // possibly crash the whole application. Check against the type
1706 // we're going to use when passing to python. Other stat types
1707 // are tested at runtime.
1708 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1709 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1710 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1711 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1712 // Just be sure (relevant when passing timestamps back to Python above).
1713 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1714 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1716 test_integral_assignment_fits();
1718 // Originally required by append_sparse_region()
1721 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1723 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1729 #pragma clang diagnostic push
1730 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1733 value = INTEGER_TO_PY(INT_MAX);
1734 PyObject_SetAttrString(m, "INT_MAX", value);
1736 value = INTEGER_TO_PY(UINT_MAX);
1737 PyObject_SetAttrString(m, "UINT_MAX", value);
1740 #ifdef HAVE_UTIMENSAT
1743 value = INTEGER_TO_PY(AT_FDCWD);
1744 PyObject_SetAttrString(m, "AT_FDCWD", value);
1746 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1747 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1749 value = INTEGER_TO_PY(UTIME_NOW);
1750 PyObject_SetAttrString(m, "UTIME_NOW", value);
1754 #ifdef BUP_HAVE_MINCORE_INCORE
1757 value = INTEGER_TO_PY(MINCORE_INCORE);
1758 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1762 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1764 e = getenv("BUP_FORCE_TTY");
1765 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1771 #if PY_MAJOR_VERSION < 3
1773 PyMODINIT_FUNC init_helpers(void)
1775 PyObject *m = Py_InitModule("_helpers", helper_methods);
1779 if (!setup_module(m))
1786 # else // PY_MAJOR_VERSION >= 3
1788 static struct PyModuleDef helpers_def = {
1789 PyModuleDef_HEAD_INIT,
1795 NULL, // helpers_traverse,
1796 NULL, // helpers_clear,
1800 PyMODINIT_FUNC PyInit__helpers(void)
1802 PyObject *module = PyModule_Create(&helpers_def);
1805 if (!setup_module(module))
1813 #endif // PY_MAJOR_VERSION >= 3