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
133 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
136 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
139 // Disabling sign-compare here should be fine since we're explicitly
140 // checking for a sign mismatch, i.e. if the signs don't match, then
141 // it doesn't matter what the value comparison says.
142 // FIXME: ... so should we reverse the order?
143 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
145 _Pragma("GCC diagnostic push"); \
146 _Pragma("GCC diagnostic ignored \"-Wsign-compare\""); \
148 *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
149 _Pragma("GCC diagnostic pop"); \
154 // At the moment any code that calls INTEGER_TO_PY() will have to
155 // disable -Wtautological-compare for clang. See below.
157 #define INTEGER_TO_PY(x) \
158 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
162 #if PY_MAJOR_VERSION < 3
163 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
166 const long tmp = PyInt_AsLong(py);
167 if (tmp == -1 && PyErr_Occurred())
169 if (PyErr_ExceptionMatches(PyExc_OverflowError))
170 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
176 PyErr_Format(PyExc_OverflowError,
177 "negative %s cannot be converted to unsigned long", name);
186 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
188 #if PY_MAJOR_VERSION < 3
190 return bup_ulong_from_pyint(x, py, name);
193 if (!PyLong_Check(py))
195 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
199 const unsigned long tmp = PyLong_AsUnsignedLong(py);
200 if (PyErr_Occurred())
202 if (PyErr_ExceptionMatches(PyExc_OverflowError))
203 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
212 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
215 if (!bup_ulong_from_py(&tmp, py, name))
220 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
227 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
230 #if PY_MAJOR_VERSION < 3
234 if (bup_ulong_from_pyint(&tmp, py, name))
243 if (!PyLong_Check(py))
245 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
249 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
250 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
252 if (PyErr_ExceptionMatches(PyExc_OverflowError))
253 PyErr_Format(PyExc_OverflowError,
254 "%s too big for unsigned long long", name);
262 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
264 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
265 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
268 Py_ssize_t s1_len, s2_len;
269 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
271 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
273 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
274 const int cmp = memcmp(s1, s2, n);
276 return PyLong_FromLong(cmp);
277 if (s1_len == s2_len)
278 return PyLong_FromLong(0);;
279 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
283 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
284 #if __WIN32__ || __CYGWIN__
286 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
287 static void unpythonize_argv(void) { }
289 #else // not __WIN32__
291 // For some reason this isn't declared in Python.h
292 extern void Py_GetArgcArgv(int *argc, char ***argv);
294 static void unpythonize_argv(void)
299 Py_GetArgcArgv(&argc, &argv);
301 for (i = 0; i < argc-1; i++)
303 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
305 // The argv block doesn't work the way we expected; it's unsafe
311 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
313 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
317 p = strrchr(argv[1], '/');
323 memmove(argv[0], p, len);
324 memset(arge - diff, 0, diff);
325 for (i = 0; i < argc; i++)
326 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
331 #endif // not __WIN32__ or __CYGWIN__
334 static int write_all(int fd, const void *buf, const size_t count)
337 while (written < count)
339 const ssize_t rc = write(fd, buf + written, count - written);
348 static int uadd(unsigned long long *dest,
349 const unsigned long long x,
350 const unsigned long long y)
352 const unsigned long long result = x + y;
353 if (result < x || result < y)
360 static PyObject *append_sparse_region(const int fd, unsigned long long n)
365 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
367 const off_t off = lseek(fd, new_off, SEEK_CUR);
368 if (off == (off_t) -1)
369 return PyErr_SetFromErrno(PyExc_IOError);
376 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
378 unsigned long long prev_pending,
379 const unsigned long long count)
381 // Add count additional sparse zeros to prev_pending and store the
382 // result in new_pending, or if the total won't fit in
383 // new_pending, write some of the zeros to fd sparsely, and store
384 // the remaining sum in new_pending.
385 if (!uadd(new_pending, prev_pending, count))
387 PyObject *err = append_sparse_region(fd, prev_pending);
390 *new_pending = count;
396 static byte* find_not_zero(const byte * const start, const byte * const end)
398 // Return a pointer to first non-zero byte between start and end,
399 // or end if there isn't one.
400 assert(start <= end);
401 const unsigned char *cur = start;
402 while (cur < end && *cur == 0)
408 static byte* find_trailing_zeros(const byte * const start,
409 const byte * const end)
411 // Return a pointer to the start of any trailing run of zeros, or
412 // end if there isn't one.
413 assert(start <= end);
416 const byte * cur = end;
417 while (cur > start && *--cur == 0) {}
421 return (byte *) (cur + 1);
425 static byte *find_non_sparse_end(const byte * const start,
426 const byte * const end,
427 const ptrdiff_t min_len)
429 // Return the first pointer to a min_len sparse block in [start,
430 // end) if there is one, otherwise a pointer to the start of any
431 // trailing run of zeros. If there are no trailing zeros, return
437 // Probe in min_len jumps, searching backward from the jump
438 // destination for a non-zero byte. If such a byte is found, move
439 // just past it and try again.
440 const byte *candidate = start;
441 // End of any run of zeros, starting at candidate, that we've already seen
442 const byte *end_of_known_zeros = candidate;
443 while (end - candidate >= min_len) // Handle all min_len candidate blocks
445 const byte * const probe_end = candidate + min_len;
446 const byte * const trailing_zeros =
447 find_trailing_zeros(end_of_known_zeros, probe_end);
448 if (trailing_zeros == probe_end)
449 end_of_known_zeros = candidate = probe_end;
450 else if (trailing_zeros == end_of_known_zeros)
452 assert(candidate >= start);
453 assert(candidate <= end);
454 assert(*candidate == 0);
455 return (byte *) candidate;
459 candidate = trailing_zeros;
460 end_of_known_zeros = probe_end;
464 if (candidate == end)
467 // No min_len sparse run found, search backward from end
468 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
471 if (trailing_zeros == end_of_known_zeros)
473 assert(candidate >= start);
474 assert(candidate < end);
475 assert(*candidate == 0);
476 assert(end - candidate < min_len);
477 return (byte *) candidate;
480 if (trailing_zeros == end)
482 assert(*(end - 1) != 0);
486 assert(end - trailing_zeros < min_len);
487 assert(trailing_zeros >= start);
488 assert(trailing_zeros < end);
489 assert(*trailing_zeros == 0);
490 return (byte *) trailing_zeros;
494 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
497 unsigned char *buf = NULL;
499 PyObject *py_min_sparse_len, *py_prev_sparse_len;
500 if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
501 &fd, &buf, &sbuf_len,
502 &py_min_sparse_len, &py_prev_sparse_len))
504 ptrdiff_t min_sparse_len;
505 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
506 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
508 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
509 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
510 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
513 return PyErr_Format(PyExc_ValueError, "negative bufer length");
514 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
515 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
517 const byte * block = buf; // Start of pending block
518 const byte * const end = buf + buf_len;
519 unsigned long long zeros = prev_sparse_len;
522 assert(block <= end);
524 return PyLong_FromUnsignedLongLong(zeros);
528 // Look for the end of block, i.e. the next sparse run of
529 // at least min_sparse_len zeros, or the end of the
531 const byte * const probe = find_non_sparse_end(block + 1, end,
533 // Either at end of block, or end of non-sparse; write pending data
534 PyObject *err = append_sparse_region(fd, zeros);
537 int rc = write_all(fd, block, probe - block);
539 return PyErr_SetFromErrno(PyExc_IOError);
541 if (end - probe < min_sparse_len)
544 zeros = min_sparse_len;
545 block = probe + zeros;
549 // Should be in the first loop iteration, a sparse run of
550 // zeros, or nearly at the end of the block (within
552 const byte * const zeros_end = find_not_zero(block, end);
553 PyObject *err = record_sparse_zeros(&zeros, fd,
554 zeros, zeros_end - block);
557 assert(block <= zeros_end);
564 static PyObject *selftest(PyObject *self, PyObject *args)
566 if (!PyArg_ParseTuple(args, ""))
569 return Py_BuildValue("i", !bupsplit_selftest());
573 static PyObject *blobbits(PyObject *self, PyObject *args)
575 if (!PyArg_ParseTuple(args, ""))
577 return Py_BuildValue("i", BUP_BLOBBITS);
581 static PyObject *splitbuf(PyObject *self, PyObject *args)
583 // We stick to buffers in python 2 because they appear to be
584 // substantially smaller than memoryviews, and because
585 // zlib.compress() in python 2 can't accept a memoryview
586 // (cf. hashsplit.py).
587 int out = 0, bits = -1;
588 if (PY_MAJOR_VERSION > 2)
591 if (!PyArg_ParseTuple(args, "y*", &buf))
593 assert(buf.len <= INT_MAX);
594 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
595 PyBuffer_Release(&buf);
599 unsigned char *buf = NULL;
601 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
603 assert(len <= INT_MAX);
604 out = bupsplit_find_ofs(buf, len, &bits);
606 if (out) assert(bits >= BUP_BLOBBITS);
607 return Py_BuildValue("ii", out, bits);
611 static PyObject *bitmatch(PyObject *self, PyObject *args)
613 unsigned char *buf1 = NULL, *buf2 = NULL;
614 Py_ssize_t len1 = 0, len2 = 0;
618 if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
622 for (byte = 0; byte < len1 && byte < len2; byte++)
624 int b1 = buf1[byte], b2 = buf2[byte];
627 for (bit = 0; bit < 8; bit++)
628 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
634 assert(byte <= (INT_MAX >> 3));
635 return Py_BuildValue("i", byte*8 + bit);
639 static PyObject *firstword(PyObject *self, PyObject *args)
641 unsigned char *buf = NULL;
645 if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
651 v = ntohl(*(uint32_t *)buf);
652 return PyLong_FromUnsignedLong(v);
656 #define BLOOM2_HEADERLEN 16
658 static void to_bloom_address_bitmask4(const unsigned char *buf,
659 const int nbits, uint64_t *v, unsigned char *bitmask)
665 memcpy(&high, buf, 4);
666 mask = (1<<nbits) - 1;
667 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
668 bit = (raw >> (37-nbits)) & 0x7;
669 *v = (raw >> (40-nbits)) & mask;
673 static void to_bloom_address_bitmask5(const unsigned char *buf,
674 const int nbits, uint32_t *v, unsigned char *bitmask)
680 memcpy(&high, buf, 4);
681 mask = (1<<nbits) - 1;
683 bit = (raw >> (29-nbits)) & 0x7;
684 *v = (raw >> (32-nbits)) & mask;
688 #define BLOOM_SET_BIT(name, address, otype) \
689 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
691 unsigned char bitmask;\
693 address(buf, nbits, &v, &bitmask);\
694 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
696 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
697 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
700 #define BLOOM_GET_BIT(name, address, otype) \
701 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
703 unsigned char bitmask;\
705 address(buf, nbits, &v, &bitmask);\
706 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
708 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
709 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
712 static PyObject *bloom_add(PyObject *self, PyObject *args)
714 Py_buffer bloom, sha;
715 int nbits = 0, k = 0;
716 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
717 &bloom, &sha, &nbits, &k))
720 PyObject *result = NULL;
722 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
723 goto clean_and_return;
728 goto clean_and_return;
729 unsigned char *cur = sha.buf;
731 for (end = cur + sha.len; cur < end; cur += 20/k)
732 bloom_set_bit5(bloom.buf, cur, nbits);
737 goto clean_and_return;
738 unsigned char *cur = sha.buf;
739 unsigned char *end = cur + sha.len;
740 for (; cur < end; cur += 20/k)
741 bloom_set_bit4(bloom.buf, cur, nbits);
744 goto clean_and_return;
746 result = Py_BuildValue("n", sha.len / 20);
749 PyBuffer_Release(&bloom);
750 PyBuffer_Release(&sha);
754 static PyObject *bloom_contains(PyObject *self, PyObject *args)
757 unsigned char *sha = NULL;
759 int nbits = 0, k = 0;
760 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
761 &bloom, &sha, &len, &nbits, &k))
764 PyObject *result = NULL;
767 goto clean_and_return;
772 goto clean_and_return;
775 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
776 if (!bloom_get_bit5(bloom.buf, sha, nbits))
778 result = Py_BuildValue("Oi", Py_None, steps);
779 goto clean_and_return;
785 goto clean_and_return;
788 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
789 if (!bloom_get_bit4(bloom.buf, sha, nbits))
791 result = Py_BuildValue("Oi", Py_None, steps);
792 goto clean_and_return;
796 goto clean_and_return;
798 result = Py_BuildValue("ii", 1, k);
801 PyBuffer_Release(&bloom);
806 static uint32_t _extract_bits(unsigned char *buf, int nbits)
810 mask = (1<<nbits) - 1;
811 v = ntohl(*(uint32_t *)buf);
812 v = (v >> (32-nbits)) & mask;
817 static PyObject *extract_bits(PyObject *self, PyObject *args)
819 unsigned char *buf = NULL;
823 if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
829 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
834 unsigned char bytes[20];
837 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
839 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
852 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
855 int low, mid, high, c = 0;
858 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
860 idxs[*last_i] = NULL;
873 mid = (low + high) / 2;
874 c = _cmp_sha(idx->cur, idxs[mid]->cur);
886 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
891 static uint32_t _get_idx_i(struct idx *idx)
893 if (idx->cur_name == NULL)
894 return idx->name_base;
895 return ntohl(*idx->cur_name) + idx->name_base;
898 #define MIDX4_HEADERLEN 12
900 static PyObject *merge_into(PyObject *self, PyObject *args)
902 struct sha *sha_ptr, *sha_start = NULL;
903 uint32_t *table_ptr, *name_ptr, *name_start;
906 uint32_t count, prefix;
911 PyObject *py_total, *ilist = NULL;
912 if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
913 &fmap, &bits, &py_total, &ilist))
916 PyObject *result = NULL;
917 struct idx **idxs = NULL;
918 Py_ssize_t num_i = 0;
919 int *idx_buf_init = NULL;
920 Py_buffer *idx_buf = NULL;
922 if (!bup_uint_from_py(&total, py_total, "total"))
923 goto clean_and_return;
925 num_i = PyList_Size(ilist);
927 if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
928 goto clean_and_return;
929 if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
930 goto clean_and_return;
931 if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
932 goto clean_and_return;
934 for (i = 0; i < num_i; i++)
936 long len, sha_ofs, name_map_ofs;
937 if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
938 goto clean_and_return;
939 PyObject *itup = PyList_GetItem(ilist, i);
940 if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
941 &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
942 &idxs[i]->name_base))
945 idxs[i]->map = idx_buf[i].buf;
946 idxs[i]->bytes = idx_buf[i].len;
947 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
948 idxs[i]->end = &idxs[i]->cur[len];
950 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
952 idxs[i]->cur_name = NULL;
954 table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
955 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
956 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
958 Py_ssize_t last_i = num_i - 1;
965 if (count % 102424 == 0 && get_state(self)->istty2)
966 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
967 count*100.0/total, count, total);
969 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
970 while (prefix < new_prefix)
971 table_ptr[prefix++] = htonl(count);
972 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
973 *name_ptr++ = htonl(_get_idx_i(idx));
975 if (idx->cur_name != NULL)
977 _fix_idx_order(idxs, &last_i);
980 while (prefix < ((uint32_t) 1 << bits))
981 table_ptr[prefix++] = htonl(count);
982 assert(count == total);
983 assert(prefix == ((uint32_t) 1 << bits));
984 assert(sha_ptr == sha_start+count);
985 assert(name_ptr == name_start+count);
987 result = PyLong_FromUnsignedLong(count);
992 for (i = 0; i < num_i; i++)
994 PyBuffer_Release(&(idx_buf[i]));
1000 for (i = 0; i < num_i; i++)
1004 PyBuffer_Release(&fmap);
1008 #define FAN_ENTRIES 256
1010 static PyObject *write_idx(PyObject *self, PyObject *args)
1012 char *filename = NULL;
1013 PyObject *py_total, *idx = NULL;
1015 unsigned int total = 0;
1017 int i, j, ofs64_count;
1018 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1019 uint64_t *ofs64_ptr;
1020 struct sha *sha_ptr;
1023 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1024 &filename, &fmap, &idx, &py_total))
1027 PyObject *result = NULL;
1029 if (!bup_uint_from_py(&total, py_total, "total"))
1030 goto clean_and_return;
1032 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1034 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1036 goto clean_and_return;
1039 const char idx_header[] = "\377tOc\0\0\0\002";
1040 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1042 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1043 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1044 crc_ptr = (uint32_t *)&sha_ptr[total];
1045 ofs_ptr = (uint32_t *)&crc_ptr[total];
1046 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1050 for (i = 0; i < FAN_ENTRIES; ++i)
1053 part = PyList_GET_ITEM(idx, i);
1055 plen = PyList_GET_SIZE(part);
1057 *fan_ptr++ = htonl(count);
1058 for (j = 0; j < plen; ++j)
1060 unsigned char *sha = NULL;
1061 Py_ssize_t sha_len = 0;
1062 PyObject *crc_py, *ofs_py;
1064 unsigned PY_LONG_LONG ofs_ull;
1066 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1067 &sha, &sha_len, &crc_py, &ofs_py))
1068 goto clean_and_return;
1069 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1070 goto clean_and_return;
1071 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1072 goto clean_and_return;
1073 assert(crc <= UINT32_MAX);
1074 assert(ofs_ull <= UINT64_MAX);
1076 if (sha_len != sizeof(struct sha))
1077 goto clean_and_return;
1078 memcpy(sha_ptr++, sha, sizeof(struct sha));
1079 *crc_ptr++ = htonl(crc);
1080 if (ofs > 0x7fffffff)
1082 *ofs64_ptr++ = htonll(ofs);
1083 ofs = 0x80000000 | ofs64_count++;
1085 *ofs_ptr++ = htonl((uint32_t)ofs);
1089 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1092 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1093 goto clean_and_return;
1096 result = PyLong_FromUnsignedLong(count);
1099 PyBuffer_Release(&fmap);
1104 // I would have made this a lower-level function that just fills in a buffer
1105 // with random values, and then written those values from python. But that's
1106 // about 20% slower in my tests, and since we typically generate random
1107 // numbers for benchmarking other parts of bup, any slowness in generating
1108 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1109 // pseudorandom bytes much except for this anyway.
1110 static PyObject *write_random(PyObject *self, PyObject *args)
1112 uint32_t buf[1024/4];
1113 int fd = -1, seed = 0, verbose = 0;
1115 long long len = 0, kbytes = 0, written = 0;
1117 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1122 for (kbytes = 0; kbytes < len/1024; kbytes++)
1125 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1127 ret = write(fd, buf, sizeof(buf));
1131 if (ret < (int)sizeof(buf))
1133 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1134 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1137 // handle non-multiples of 1024
1141 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1143 ret = write(fd, buf, len % 1024);
1149 if (kbytes/1024 > 0)
1150 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1151 return Py_BuildValue("L", written);
1155 static PyObject *random_sha(PyObject *self, PyObject *args)
1157 static int seeded = 0;
1158 uint32_t shabuf[20/4];
1163 assert(sizeof(shabuf) == 20);
1164 srandom(time(NULL));
1168 if (!PyArg_ParseTuple(args, ""))
1171 memset(shabuf, 0, sizeof(shabuf));
1172 for (i=0; i < 20/4; i++)
1173 shabuf[i] = random();
1174 return Py_BuildValue("s#", shabuf, 20);
1178 static int _open_noatime(const char *filename, int attrs)
1180 int attrs_noatime, fd;
1183 attrs |= O_NOFOLLOW;
1186 attrs |= O_LARGEFILE;
1188 attrs_noatime = attrs;
1190 attrs_noatime |= O_NOATIME;
1192 fd = open(filename, attrs_noatime);
1193 if (fd < 0 && errno == EPERM)
1195 // older Linux kernels would return EPERM if you used O_NOATIME
1196 // and weren't the file's owner. This pointless restriction was
1197 // relaxed eventually, but we have to handle it anyway.
1198 // (VERY old kernels didn't recognized O_NOATIME, but they would
1199 // just harmlessly ignore it, so this branch won't trigger)
1200 fd = open(filename, attrs);
1206 static PyObject *open_noatime(PyObject *self, PyObject *args)
1208 char *filename = NULL;
1210 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1212 fd = _open_noatime(filename, 0);
1214 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1215 return Py_BuildValue("i", fd);
1219 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1222 long long llofs, lllen = 0;
1223 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1226 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1227 return PyErr_Format(PyExc_OverflowError,
1228 "fadvise offset overflows off_t");
1229 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1230 return PyErr_Format(PyExc_OverflowError,
1231 "fadvise length overflows off_t");
1232 #ifdef POSIX_FADV_DONTNEED
1233 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1235 return Py_BuildValue("");
1239 // Currently the Linux kernel and FUSE disagree over the type for
1240 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1241 // but FUSE chose long (matching the declaration in linux/fs.h). So
1242 // if you use int, and then traverse a FUSE filesystem, you may
1243 // corrupt the stack. But if you use long, then you may get invalid
1244 // results on big-endian systems.
1246 // For now, we just use long, and then disable Linux attrs entirely
1247 // (with a warning) in helpers.py on systems that are affected.
1249 #ifdef BUP_HAVE_FILE_ATTRS
1250 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1257 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1260 fd = _open_noatime(path, O_NONBLOCK);
1262 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1264 attr = 0; // Handle int/long mismatch (see above)
1265 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1269 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1272 assert(attr <= UINT_MAX); // Kernel type is actually int
1273 return PyLong_FromUnsignedLong(attr);
1275 #endif /* def BUP_HAVE_FILE_ATTRS */
1279 #ifdef BUP_HAVE_FILE_ATTRS
1280 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1283 unsigned long orig_attr;
1289 if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1292 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1295 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1297 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1299 // Restrict attr to modifiable flags acdeijstuADST -- see
1300 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1301 // in pf.c flags_array[].
1302 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1303 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1304 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1305 | FS_TOPDIR_FL | FS_NOCOW_FL;
1307 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1308 orig_attr = 0; // Handle int/long mismatch (see above)
1309 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1313 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1315 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1316 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1318 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1322 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1326 return Py_BuildValue("O", Py_None);
1328 #endif /* def BUP_HAVE_FILE_ATTRS */
1331 #ifndef HAVE_UTIMENSAT
1333 #error "cannot find utimensat or utimes()"
1335 #ifndef HAVE_LUTIMES
1336 #error "cannot find utimensat or lutimes()"
1340 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1344 const long long lltmp = PyLong_AsLongLong(pylong); \
1345 if (lltmp == -1 && PyErr_Occurred()) \
1347 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1349 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1350 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1352 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1358 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1366 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1375 #ifdef HAVE_UTIMENSAT
1377 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1382 PyObject *access_py, *modification_py;
1383 struct timespec ts[2];
1385 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1388 &access_py, &(ts[0].tv_nsec),
1389 &modification_py, &(ts[1].tv_nsec),
1394 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1397 PyErr_SetString(PyExc_ValueError,
1398 "unable to convert access time seconds for utimensat");
1401 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1404 PyErr_SetString(PyExc_ValueError,
1405 "unable to convert modification time seconds for utimensat");
1408 rc = utimensat(fd, path, ts, flag);
1410 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1412 return Py_BuildValue("O", Py_None);
1415 #endif /* def HAVE_UTIMENSAT */
1418 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1420 static int bup_parse_xutimes_args(char **path,
1421 struct timeval tv[2],
1424 PyObject *access_py, *modification_py;
1425 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1427 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1429 &access_py, &access_us,
1430 &modification_py, &modification_us))
1434 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1437 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1440 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1442 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1445 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1448 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1451 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1453 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1459 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1463 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1466 struct timeval tv[2];
1467 if (!bup_parse_xutimes_args(&path, tv, args))
1469 int rc = utimes(path, tv);
1471 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1472 return Py_BuildValue("O", Py_None);
1474 #endif /* def HAVE_UTIMES */
1478 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1481 struct timeval tv[2];
1482 if (!bup_parse_xutimes_args(&path, tv, args))
1484 int rc = lutimes(path, tv);
1486 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1488 return Py_BuildValue("O", Py_None);
1490 #endif /* def HAVE_LUTIMES */
1493 #ifdef HAVE_STAT_ST_ATIM
1494 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1495 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1496 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1497 #elif defined HAVE_STAT_ST_ATIMENSEC
1498 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1499 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1500 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1502 # define BUP_STAT_ATIME_NS(st) 0
1503 # define BUP_STAT_MTIME_NS(st) 0
1504 # define BUP_STAT_CTIME_NS(st) 0
1508 #pragma clang diagnostic push
1509 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1511 static PyObject *stat_struct_to_py(const struct stat *st,
1512 const char *filename,
1515 // We can check the known (via POSIX) signed and unsigned types at
1516 // compile time, but not (easily) the unspecified types, so handle
1517 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1519 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1520 INTEGER_TO_PY(st->st_mode),
1521 (unsigned PY_LONG_LONG) st->st_ino,
1522 INTEGER_TO_PY(st->st_dev),
1523 INTEGER_TO_PY(st->st_nlink),
1524 INTEGER_TO_PY(st->st_uid),
1525 INTEGER_TO_PY(st->st_gid),
1526 INTEGER_TO_PY(st->st_rdev),
1527 (PY_LONG_LONG) st->st_size,
1528 INTEGER_TO_PY(st->st_atime),
1529 (long) BUP_STAT_ATIME_NS(st),
1530 INTEGER_TO_PY(st->st_mtime),
1531 (long) BUP_STAT_MTIME_NS(st),
1532 INTEGER_TO_PY(st->st_ctime),
1533 (long) BUP_STAT_CTIME_NS(st));
1536 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1538 static PyObject *bup_stat(PyObject *self, PyObject *args)
1543 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1547 rc = stat(filename, &st);
1549 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1550 return stat_struct_to_py(&st, filename, 0);
1554 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1559 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1563 rc = lstat(filename, &st);
1565 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1566 return stat_struct_to_py(&st, filename, 0);
1570 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1574 if (!PyArg_ParseTuple(args, "i", &fd))
1578 rc = fstat(fd, &st);
1580 return PyErr_SetFromErrno(PyExc_OSError);
1581 return stat_struct_to_py(&st, NULL, fd);
1585 #ifdef HAVE_TM_TM_GMTOFF
1586 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1590 if (!PyArg_ParseTuple(args, "L", &lltime))
1592 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1593 return PyErr_Format(PyExc_OverflowError, "time value too large");
1597 if(localtime_r(&ttime, &tm) == NULL)
1598 return PyErr_SetFromErrno(PyExc_OSError);
1600 // Match the Python struct_time values.
1601 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1602 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1603 tm.tm_hour, tm.tm_min, tm.tm_sec,
1604 tm.tm_wday, tm.tm_yday + 1,
1605 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1607 #endif /* def HAVE_TM_TM_GMTOFF */
1610 #ifdef BUP_MINCORE_BUF_TYPE
1611 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1613 Py_buffer src, dest;
1614 PyObject *py_src_n, *py_src_off, *py_dest_off;
1616 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1617 &src, &py_src_n, &py_src_off,
1618 &dest, &py_dest_off))
1621 PyObject *result = NULL;
1623 unsigned long long src_n, src_off, dest_off;
1624 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1625 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1626 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1627 goto clean_and_return;
1629 unsigned long long src_region_end;
1630 if (!uadd(&src_region_end, src_off, src_n)) {
1631 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1632 goto clean_and_return;
1634 assert(src.len >= 0);
1635 if (src_region_end > (unsigned long long) src.len) {
1636 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1637 goto clean_and_return;
1640 unsigned long long dest_size;
1641 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1642 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1643 goto clean_and_return;
1645 if (dest_off > dest_size) {
1646 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1647 goto clean_and_return;
1651 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1652 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1653 goto clean_and_return;
1655 int rc = mincore((void *)(src.buf + src_off), src_n,
1656 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1658 result = PyErr_SetFromErrno(PyExc_OSError);
1659 goto clean_and_return;
1661 result = Py_BuildValue("O", Py_None);
1664 PyBuffer_Release(&src);
1665 PyBuffer_Release(&dest);
1668 #endif /* def BUP_MINCORE_BUF_TYPE */
1671 static PyMethodDef helper_methods[] = {
1672 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1673 "Write buf excepting zeros at the end. Return trailing zero count." },
1674 { "selftest", selftest, METH_VARARGS,
1675 "Check that the rolling checksum rolls correctly (for unit tests)." },
1676 { "blobbits", blobbits, METH_VARARGS,
1677 "Return the number of bits in the rolling checksum." },
1678 { "splitbuf", splitbuf, METH_VARARGS,
1679 "Split a list of strings based on a rolling checksum." },
1680 { "bitmatch", bitmatch, METH_VARARGS,
1681 "Count the number of matching prefix bits between two strings." },
1682 { "firstword", firstword, METH_VARARGS,
1683 "Return an int corresponding to the first 32 bits of buf." },
1684 { "bloom_contains", bloom_contains, METH_VARARGS,
1685 "Check if a bloom filter of 2^nbits bytes contains an object" },
1686 { "bloom_add", bloom_add, METH_VARARGS,
1687 "Add an object to a bloom filter of 2^nbits bytes" },
1688 { "extract_bits", extract_bits, METH_VARARGS,
1689 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1690 { "merge_into", merge_into, METH_VARARGS,
1691 "Merges a bunch of idx and midx files into a single midx." },
1692 { "write_idx", write_idx, METH_VARARGS,
1693 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1694 { "write_random", write_random, METH_VARARGS,
1695 "Write random bytes to the given file descriptor" },
1696 { "random_sha", random_sha, METH_VARARGS,
1697 "Return a random 20-byte string" },
1698 { "open_noatime", open_noatime, METH_VARARGS,
1699 "open() the given filename for read with O_NOATIME if possible" },
1700 { "fadvise_done", fadvise_done, METH_VARARGS,
1701 "Inform the kernel that we're finished with earlier parts of a file" },
1702 #ifdef BUP_HAVE_FILE_ATTRS
1703 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1704 "Return the Linux attributes for the given file." },
1706 #ifdef BUP_HAVE_FILE_ATTRS
1707 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1708 "Set the Linux attributes for the given file." },
1710 #ifdef HAVE_UTIMENSAT
1711 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1712 "Change path timestamps with nanosecond precision (POSIX)." },
1715 { "bup_utimes", bup_utimes, METH_VARARGS,
1716 "Change path timestamps with microsecond precision." },
1719 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1720 "Change path timestamps with microsecond precision;"
1721 " don't follow symlinks." },
1723 { "stat", bup_stat, METH_VARARGS,
1724 "Extended version of stat." },
1725 { "lstat", bup_lstat, METH_VARARGS,
1726 "Extended version of lstat." },
1727 { "fstat", bup_fstat, METH_VARARGS,
1728 "Extended version of fstat." },
1729 #ifdef HAVE_TM_TM_GMTOFF
1730 { "localtime", bup_localtime, METH_VARARGS,
1731 "Return struct_time elements plus the timezone offset and name." },
1733 { "bytescmp", bup_bytescmp, METH_VARARGS,
1734 "Return a negative value if x < y, zero if equal, positive otherwise."},
1735 #ifdef BUP_MINCORE_BUF_TYPE
1736 { "mincore", bup_mincore, METH_VARARGS,
1737 "For mincore(src, src_n, src_off, dest, dest_off)"
1738 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1740 { NULL, NULL, 0, NULL }, // sentinel
1743 static void test_integral_assignment_fits(void)
1745 assert(sizeof(signed short) == sizeof(unsigned short));
1746 assert(sizeof(signed short) < sizeof(signed long long));
1747 assert(sizeof(signed short) < sizeof(unsigned long long));
1748 assert(sizeof(unsigned short) < sizeof(signed long long));
1749 assert(sizeof(unsigned short) < sizeof(unsigned long long));
1750 assert(sizeof(Py_ssize_t) <= sizeof(size_t));
1752 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
1753 unsigned short us, usmax = USHRT_MAX;
1754 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
1755 unsigned long long ullmax = ULLONG_MAX;
1757 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
1758 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
1759 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
1760 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
1761 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
1762 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
1764 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
1765 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
1766 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
1767 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
1768 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
1772 static int setup_module(PyObject *m)
1774 // FIXME: migrate these tests to configure, or at least don't
1775 // possibly crash the whole application. Check against the type
1776 // we're going to use when passing to python. Other stat types
1777 // are tested at runtime.
1778 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1779 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1780 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1781 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1782 // Just be sure (relevant when passing timestamps back to Python above).
1783 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1784 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1786 test_integral_assignment_fits();
1788 // Originally required by append_sparse_region()
1791 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1793 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1799 #pragma clang diagnostic push
1800 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1803 value = INTEGER_TO_PY(INT_MAX);
1804 PyObject_SetAttrString(m, "INT_MAX", value);
1806 value = INTEGER_TO_PY(UINT_MAX);
1807 PyObject_SetAttrString(m, "UINT_MAX", value);
1810 #ifdef HAVE_UTIMENSAT
1813 value = INTEGER_TO_PY(AT_FDCWD);
1814 PyObject_SetAttrString(m, "AT_FDCWD", value);
1816 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1817 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1819 value = INTEGER_TO_PY(UTIME_NOW);
1820 PyObject_SetAttrString(m, "UTIME_NOW", value);
1824 #ifdef BUP_HAVE_MINCORE_INCORE
1827 value = INTEGER_TO_PY(MINCORE_INCORE);
1828 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1832 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1834 e = getenv("BUP_FORCE_TTY");
1835 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1841 #if PY_MAJOR_VERSION < 3
1843 PyMODINIT_FUNC init_helpers(void)
1845 PyObject *m = Py_InitModule("_helpers", helper_methods);
1849 if (!setup_module(m))
1856 # else // PY_MAJOR_VERSION >= 3
1858 static struct PyModuleDef helpers_def = {
1859 PyModuleDef_HEAD_INIT,
1865 NULL, // helpers_traverse,
1866 NULL, // helpers_clear,
1870 PyMODINIT_FUNC PyInit__helpers(void)
1872 PyObject *module = PyModule_Create(&helpers_def);
1875 if (!setup_module(module))
1883 #endif // PY_MAJOR_VERSION >= 3