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 static PyObject *bup_cat_bytes(PyObject *self, PyObject *args)
278 unsigned char *bufx = NULL, *bufy = NULL;
279 Py_ssize_t bufx_len, bufx_ofs, bufx_n;
280 Py_ssize_t bufy_len, bufy_ofs, bufy_n;
281 if (!PyArg_ParseTuple(args,
284 &bufx, &bufx_len, &bufx_ofs, &bufx_n,
285 &bufy, &bufy_len, &bufy_ofs, &bufy_n))
288 return PyErr_Format(PyExc_ValueError, "negative x offset");
290 return PyErr_Format(PyExc_ValueError, "negative x extent");
291 if (bufx_ofs > bufx_len)
292 return PyErr_Format(PyExc_ValueError, "x offset greater than length");
293 if (bufx_n > bufx_len - bufx_ofs)
294 return PyErr_Format(PyExc_ValueError, "x extent past end of buffer");
297 return PyErr_Format(PyExc_ValueError, "negative y offset");
299 return PyErr_Format(PyExc_ValueError, "negative y extent");
300 if (bufy_ofs > bufy_len)
301 return PyErr_Format(PyExc_ValueError, "y offset greater than length");
302 if (bufy_n > bufy_len - bufy_ofs)
303 return PyErr_Format(PyExc_ValueError, "y extent past end of buffer");
305 if (bufy_n > PY_SSIZE_T_MAX - bufx_n)
306 return PyErr_Format(PyExc_OverflowError, "result length too long");
308 PyObject *result = PyBytes_FromStringAndSize(NULL, bufx_n + bufy_n);
310 return PyErr_NoMemory();
311 char *buf = PyBytes_AS_STRING(result);
312 memcpy(buf, bufx + bufx_ofs, bufx_n);
313 memcpy(buf + bufx_n, bufy + bufy_ofs, bufy_n);
319 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
320 #if __WIN32__ || __CYGWIN__
322 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
323 static void unpythonize_argv(void) { }
325 #else // not __WIN32__
327 // For some reason this isn't declared in Python.h
328 extern void Py_GetArgcArgv(int *argc, char ***argv);
330 static void unpythonize_argv(void)
335 Py_GetArgcArgv(&argc, &argv);
337 for (i = 0; i < argc-1; i++)
339 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
341 // The argv block doesn't work the way we expected; it's unsafe
347 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
349 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
353 p = strrchr(argv[1], '/');
359 memmove(argv[0], p, len);
360 memset(arge - diff, 0, diff);
361 for (i = 0; i < argc; i++)
362 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
367 #endif // not __WIN32__ or __CYGWIN__
370 static int write_all(int fd, const void *buf, const size_t count)
373 while (written < count)
375 const ssize_t rc = write(fd, buf + written, count - written);
384 static int uadd(unsigned long long *dest,
385 const unsigned long long x,
386 const unsigned long long y)
388 const unsigned long long result = x + y;
389 if (result < x || result < y)
396 static PyObject *append_sparse_region(const int fd, unsigned long long n)
401 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
403 const off_t off = lseek(fd, new_off, SEEK_CUR);
404 if (off == (off_t) -1)
405 return PyErr_SetFromErrno(PyExc_IOError);
412 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
414 unsigned long long prev_pending,
415 const unsigned long long count)
417 // Add count additional sparse zeros to prev_pending and store the
418 // result in new_pending, or if the total won't fit in
419 // new_pending, write some of the zeros to fd sparsely, and store
420 // the remaining sum in new_pending.
421 if (!uadd(new_pending, prev_pending, count))
423 PyObject *err = append_sparse_region(fd, prev_pending);
426 *new_pending = count;
432 static byte* find_not_zero(const byte * const start, const byte * const end)
434 // Return a pointer to first non-zero byte between start and end,
435 // or end if there isn't one.
436 assert(start <= end);
437 const unsigned char *cur = start;
438 while (cur < end && *cur == 0)
444 static byte* find_trailing_zeros(const byte * const start,
445 const byte * const end)
447 // Return a pointer to the start of any trailing run of zeros, or
448 // end if there isn't one.
449 assert(start <= end);
452 const byte * cur = end;
453 while (cur > start && *--cur == 0) {}
457 return (byte *) (cur + 1);
461 static byte *find_non_sparse_end(const byte * const start,
462 const byte * const end,
463 const ptrdiff_t min_len)
465 // Return the first pointer to a min_len sparse block in [start,
466 // end) if there is one, otherwise a pointer to the start of any
467 // trailing run of zeros. If there are no trailing zeros, return
473 // Probe in min_len jumps, searching backward from the jump
474 // destination for a non-zero byte. If such a byte is found, move
475 // just past it and try again.
476 const byte *candidate = start;
477 // End of any run of zeros, starting at candidate, that we've already seen
478 const byte *end_of_known_zeros = candidate;
479 while (end - candidate >= min_len) // Handle all min_len candidate blocks
481 const byte * const probe_end = candidate + min_len;
482 const byte * const trailing_zeros =
483 find_trailing_zeros(end_of_known_zeros, probe_end);
484 if (trailing_zeros == probe_end)
485 end_of_known_zeros = candidate = probe_end;
486 else if (trailing_zeros == end_of_known_zeros)
488 assert(candidate >= start);
489 assert(candidate <= end);
490 assert(*candidate == 0);
491 return (byte *) candidate;
495 candidate = trailing_zeros;
496 end_of_known_zeros = probe_end;
500 if (candidate == end)
503 // No min_len sparse run found, search backward from end
504 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
507 if (trailing_zeros == end_of_known_zeros)
509 assert(candidate >= start);
510 assert(candidate < end);
511 assert(*candidate == 0);
512 assert(end - candidate < min_len);
513 return (byte *) candidate;
516 if (trailing_zeros == end)
518 assert(*(end - 1) != 0);
522 assert(end - trailing_zeros < min_len);
523 assert(trailing_zeros >= start);
524 assert(trailing_zeros < end);
525 assert(*trailing_zeros == 0);
526 return (byte *) trailing_zeros;
530 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
533 unsigned char *buf = NULL;
535 PyObject *py_min_sparse_len, *py_prev_sparse_len;
536 if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
537 &fd, &buf, &sbuf_len,
538 &py_min_sparse_len, &py_prev_sparse_len))
540 ptrdiff_t min_sparse_len;
541 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
542 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
544 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
545 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
546 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
549 return PyErr_Format(PyExc_ValueError, "negative bufer length");
550 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
551 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
553 const byte * block = buf; // Start of pending block
554 const byte * const end = buf + buf_len;
555 unsigned long long zeros = prev_sparse_len;
558 assert(block <= end);
560 return PyLong_FromUnsignedLongLong(zeros);
564 // Look for the end of block, i.e. the next sparse run of
565 // at least min_sparse_len zeros, or the end of the
567 const byte * const probe = find_non_sparse_end(block + 1, end,
569 // Either at end of block, or end of non-sparse; write pending data
570 PyObject *err = append_sparse_region(fd, zeros);
573 int rc = write_all(fd, block, probe - block);
575 return PyErr_SetFromErrno(PyExc_IOError);
577 if (end - probe < min_sparse_len)
580 zeros = min_sparse_len;
581 block = probe + zeros;
585 // Should be in the first loop iteration, a sparse run of
586 // zeros, or nearly at the end of the block (within
588 const byte * const zeros_end = find_not_zero(block, end);
589 PyObject *err = record_sparse_zeros(&zeros, fd,
590 zeros, zeros_end - block);
593 assert(block <= zeros_end);
600 static PyObject *selftest(PyObject *self, PyObject *args)
602 if (!PyArg_ParseTuple(args, ""))
605 return Py_BuildValue("i", !bupsplit_selftest());
609 static PyObject *blobbits(PyObject *self, PyObject *args)
611 if (!PyArg_ParseTuple(args, ""))
613 return Py_BuildValue("i", BUP_BLOBBITS);
617 static PyObject *splitbuf(PyObject *self, PyObject *args)
619 // We stick to buffers in python 2 because they appear to be
620 // substantially smaller than memoryviews, and because
621 // zlib.compress() in python 2 can't accept a memoryview
622 // (cf. hashsplit.py).
623 int out = 0, bits = -1;
624 if (PY_MAJOR_VERSION > 2)
627 if (!PyArg_ParseTuple(args, "y*", &buf))
629 assert(buf.len <= INT_MAX);
630 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
631 PyBuffer_Release(&buf);
635 unsigned char *buf = NULL;
637 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
639 assert(len <= INT_MAX);
640 out = bupsplit_find_ofs(buf, len, &bits);
642 if (out) assert(bits >= BUP_BLOBBITS);
643 return Py_BuildValue("ii", out, bits);
647 static PyObject *bitmatch(PyObject *self, PyObject *args)
649 unsigned char *buf1 = NULL, *buf2 = NULL;
650 Py_ssize_t len1 = 0, len2 = 0;
654 if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
658 for (byte = 0; byte < len1 && byte < len2; byte++)
660 int b1 = buf1[byte], b2 = buf2[byte];
663 for (bit = 0; bit < 8; bit++)
664 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
670 assert(byte <= (INT_MAX >> 3));
671 return Py_BuildValue("i", byte*8 + bit);
675 static PyObject *firstword(PyObject *self, PyObject *args)
677 unsigned char *buf = NULL;
681 if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
687 v = ntohl(*(uint32_t *)buf);
688 return PyLong_FromUnsignedLong(v);
692 #define BLOOM2_HEADERLEN 16
694 static void to_bloom_address_bitmask4(const unsigned char *buf,
695 const int nbits, uint64_t *v, unsigned char *bitmask)
701 memcpy(&high, buf, 4);
702 mask = (1<<nbits) - 1;
703 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
704 bit = (raw >> (37-nbits)) & 0x7;
705 *v = (raw >> (40-nbits)) & mask;
709 static void to_bloom_address_bitmask5(const unsigned char *buf,
710 const int nbits, uint32_t *v, unsigned char *bitmask)
716 memcpy(&high, buf, 4);
717 mask = (1<<nbits) - 1;
719 bit = (raw >> (29-nbits)) & 0x7;
720 *v = (raw >> (32-nbits)) & mask;
724 #define BLOOM_SET_BIT(name, address, otype) \
725 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
727 unsigned char bitmask;\
729 address(buf, nbits, &v, &bitmask);\
730 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
732 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
733 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
736 #define BLOOM_GET_BIT(name, address, otype) \
737 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
739 unsigned char bitmask;\
741 address(buf, nbits, &v, &bitmask);\
742 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
744 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
745 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
748 static PyObject *bloom_add(PyObject *self, PyObject *args)
750 Py_buffer bloom, sha;
751 int nbits = 0, k = 0;
752 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
753 &bloom, &sha, &nbits, &k))
756 PyObject *result = NULL;
758 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
759 goto clean_and_return;
764 goto clean_and_return;
765 unsigned char *cur = sha.buf;
767 for (end = cur + sha.len; cur < end; cur += 20/k)
768 bloom_set_bit5(bloom.buf, cur, nbits);
773 goto clean_and_return;
774 unsigned char *cur = sha.buf;
775 unsigned char *end = cur + sha.len;
776 for (; cur < end; cur += 20/k)
777 bloom_set_bit4(bloom.buf, cur, nbits);
780 goto clean_and_return;
782 result = Py_BuildValue("n", sha.len / 20);
785 PyBuffer_Release(&bloom);
786 PyBuffer_Release(&sha);
790 static PyObject *bloom_contains(PyObject *self, PyObject *args)
793 unsigned char *sha = NULL;
795 int nbits = 0, k = 0;
796 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
797 &bloom, &sha, &len, &nbits, &k))
800 PyObject *result = NULL;
803 goto clean_and_return;
808 goto clean_and_return;
811 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
812 if (!bloom_get_bit5(bloom.buf, sha, nbits))
814 result = Py_BuildValue("Oi", Py_None, steps);
815 goto clean_and_return;
821 goto clean_and_return;
824 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
825 if (!bloom_get_bit4(bloom.buf, sha, nbits))
827 result = Py_BuildValue("Oi", Py_None, steps);
828 goto clean_and_return;
832 goto clean_and_return;
834 result = Py_BuildValue("ii", 1, k);
837 PyBuffer_Release(&bloom);
842 static uint32_t _extract_bits(unsigned char *buf, int nbits)
846 mask = (1<<nbits) - 1;
847 v = ntohl(*(uint32_t *)buf);
848 v = (v >> (32-nbits)) & mask;
853 static PyObject *extract_bits(PyObject *self, PyObject *args)
855 unsigned char *buf = NULL;
859 if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
865 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
870 unsigned char bytes[20];
873 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
875 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
888 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
891 int low, mid, high, c = 0;
894 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
896 idxs[*last_i] = NULL;
909 mid = (low + high) / 2;
910 c = _cmp_sha(idx->cur, idxs[mid]->cur);
922 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
927 static uint32_t _get_idx_i(struct idx *idx)
929 if (idx->cur_name == NULL)
930 return idx->name_base;
931 return ntohl(*idx->cur_name) + idx->name_base;
934 #define MIDX4_HEADERLEN 12
936 static PyObject *merge_into(PyObject *self, PyObject *args)
938 struct sha *sha_ptr, *sha_start = NULL;
939 uint32_t *table_ptr, *name_ptr, *name_start;
942 uint32_t count, prefix;
947 PyObject *py_total, *ilist = NULL;
948 if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
949 &fmap, &bits, &py_total, &ilist))
952 PyObject *result = NULL;
953 struct idx **idxs = NULL;
954 Py_ssize_t num_i = 0;
955 int *idx_buf_init = NULL;
956 Py_buffer *idx_buf = NULL;
958 if (!bup_uint_from_py(&total, py_total, "total"))
959 goto clean_and_return;
961 num_i = PyList_Size(ilist);
963 if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
964 goto clean_and_return;
965 if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
966 goto clean_and_return;
967 if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
968 goto clean_and_return;
970 for (i = 0; i < num_i; i++)
972 long len, sha_ofs, name_map_ofs;
973 if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
974 goto clean_and_return;
975 PyObject *itup = PyList_GetItem(ilist, i);
976 if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
977 &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
978 &idxs[i]->name_base))
981 idxs[i]->map = idx_buf[i].buf;
982 idxs[i]->bytes = idx_buf[i].len;
983 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
984 idxs[i]->end = &idxs[i]->cur[len];
986 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
988 idxs[i]->cur_name = NULL;
990 table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
991 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
992 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
994 Py_ssize_t last_i = num_i - 1;
1000 uint32_t new_prefix;
1001 if (count % 102424 == 0 && get_state(self)->istty2)
1002 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
1003 count*100.0/total, count, total);
1005 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
1006 while (prefix < new_prefix)
1007 table_ptr[prefix++] = htonl(count);
1008 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
1009 *name_ptr++ = htonl(_get_idx_i(idx));
1011 if (idx->cur_name != NULL)
1013 _fix_idx_order(idxs, &last_i);
1016 while (prefix < ((uint32_t) 1 << bits))
1017 table_ptr[prefix++] = htonl(count);
1018 assert(count == total);
1019 assert(prefix == ((uint32_t) 1 << bits));
1020 assert(sha_ptr == sha_start+count);
1021 assert(name_ptr == name_start+count);
1023 result = PyLong_FromUnsignedLong(count);
1028 for (i = 0; i < num_i; i++)
1029 if (idx_buf_init[i])
1030 PyBuffer_Release(&(idx_buf[i]));
1036 for (i = 0; i < num_i; i++)
1040 PyBuffer_Release(&fmap);
1044 #define FAN_ENTRIES 256
1046 static PyObject *write_idx(PyObject *self, PyObject *args)
1048 char *filename = NULL;
1049 PyObject *py_total, *idx = NULL;
1051 unsigned int total = 0;
1053 int i, j, ofs64_count;
1054 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1055 uint64_t *ofs64_ptr;
1056 struct sha *sha_ptr;
1059 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1060 &filename, &fmap, &idx, &py_total))
1063 PyObject *result = NULL;
1065 if (!bup_uint_from_py(&total, py_total, "total"))
1066 goto clean_and_return;
1068 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1070 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1072 goto clean_and_return;
1075 const char idx_header[] = "\377tOc\0\0\0\002";
1076 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1078 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1079 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1080 crc_ptr = (uint32_t *)&sha_ptr[total];
1081 ofs_ptr = (uint32_t *)&crc_ptr[total];
1082 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1086 for (i = 0; i < FAN_ENTRIES; ++i)
1089 part = PyList_GET_ITEM(idx, i);
1091 plen = PyList_GET_SIZE(part);
1093 *fan_ptr++ = htonl(count);
1094 for (j = 0; j < plen; ++j)
1096 unsigned char *sha = NULL;
1097 Py_ssize_t sha_len = 0;
1098 PyObject *crc_py, *ofs_py;
1100 unsigned PY_LONG_LONG ofs_ull;
1102 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1103 &sha, &sha_len, &crc_py, &ofs_py))
1104 goto clean_and_return;
1105 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1106 goto clean_and_return;
1107 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1108 goto clean_and_return;
1109 assert(crc <= UINT32_MAX);
1110 assert(ofs_ull <= UINT64_MAX);
1112 if (sha_len != sizeof(struct sha))
1113 goto clean_and_return;
1114 memcpy(sha_ptr++, sha, sizeof(struct sha));
1115 *crc_ptr++ = htonl(crc);
1116 if (ofs > 0x7fffffff)
1118 *ofs64_ptr++ = htonll(ofs);
1119 ofs = 0x80000000 | ofs64_count++;
1121 *ofs_ptr++ = htonl((uint32_t)ofs);
1125 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1128 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1129 goto clean_and_return;
1132 result = PyLong_FromUnsignedLong(count);
1135 PyBuffer_Release(&fmap);
1140 // I would have made this a lower-level function that just fills in a buffer
1141 // with random values, and then written those values from python. But that's
1142 // about 20% slower in my tests, and since we typically generate random
1143 // numbers for benchmarking other parts of bup, any slowness in generating
1144 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1145 // pseudorandom bytes much except for this anyway.
1146 static PyObject *write_random(PyObject *self, PyObject *args)
1148 uint32_t buf[1024/4];
1149 int fd = -1, seed = 0, verbose = 0;
1151 long long len = 0, kbytes = 0, written = 0;
1153 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1158 for (kbytes = 0; kbytes < len/1024; kbytes++)
1161 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1163 ret = write(fd, buf, sizeof(buf));
1167 if (ret < (int)sizeof(buf))
1169 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1170 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1173 // handle non-multiples of 1024
1177 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1179 ret = write(fd, buf, len % 1024);
1185 if (kbytes/1024 > 0)
1186 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1187 return Py_BuildValue("L", written);
1191 static PyObject *random_sha(PyObject *self, PyObject *args)
1193 static int seeded = 0;
1194 uint32_t shabuf[20/4];
1199 assert(sizeof(shabuf) == 20);
1200 srandom(time(NULL));
1204 if (!PyArg_ParseTuple(args, ""))
1207 memset(shabuf, 0, sizeof(shabuf));
1208 for (i=0; i < 20/4; i++)
1209 shabuf[i] = random();
1210 return Py_BuildValue(rbuf_argf, shabuf, 20);
1214 static int _open_noatime(const char *filename, int attrs)
1216 int attrs_noatime, fd;
1219 attrs |= O_NOFOLLOW;
1222 attrs |= O_LARGEFILE;
1224 attrs_noatime = attrs;
1226 attrs_noatime |= O_NOATIME;
1228 fd = open(filename, attrs_noatime);
1229 if (fd < 0 && errno == EPERM)
1231 // older Linux kernels would return EPERM if you used O_NOATIME
1232 // and weren't the file's owner. This pointless restriction was
1233 // relaxed eventually, but we have to handle it anyway.
1234 // (VERY old kernels didn't recognized O_NOATIME, but they would
1235 // just harmlessly ignore it, so this branch won't trigger)
1236 fd = open(filename, attrs);
1242 static PyObject *open_noatime(PyObject *self, PyObject *args)
1244 char *filename = NULL;
1246 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1248 fd = _open_noatime(filename, 0);
1250 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1251 return Py_BuildValue("i", fd);
1255 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1258 long long llofs, lllen = 0;
1259 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1262 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1263 return PyErr_Format(PyExc_OverflowError,
1264 "fadvise offset overflows off_t");
1265 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1266 return PyErr_Format(PyExc_OverflowError,
1267 "fadvise length overflows off_t");
1268 #ifdef POSIX_FADV_DONTNEED
1269 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1271 return Py_BuildValue("");
1275 // Currently the Linux kernel and FUSE disagree over the type for
1276 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1277 // but FUSE chose long (matching the declaration in linux/fs.h). So
1278 // if you use int, and then traverse a FUSE filesystem, you may
1279 // corrupt the stack. But if you use long, then you may get invalid
1280 // results on big-endian systems.
1282 // For now, we just use long, and then disable Linux attrs entirely
1283 // (with a warning) in helpers.py on systems that are affected.
1285 #ifdef BUP_HAVE_FILE_ATTRS
1286 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1293 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1296 fd = _open_noatime(path, O_NONBLOCK);
1298 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1300 attr = 0; // Handle int/long mismatch (see above)
1301 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1305 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1308 assert(attr <= UINT_MAX); // Kernel type is actually int
1309 return PyLong_FromUnsignedLong(attr);
1311 #endif /* def BUP_HAVE_FILE_ATTRS */
1315 #ifdef BUP_HAVE_FILE_ATTRS
1316 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1319 unsigned long orig_attr;
1325 if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1328 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1331 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1333 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1335 // Restrict attr to modifiable flags acdeijstuADST -- see
1336 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1337 // in pf.c flags_array[].
1338 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1339 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1340 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1341 | FS_TOPDIR_FL | FS_NOCOW_FL;
1343 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1344 orig_attr = 0; // Handle int/long mismatch (see above)
1345 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1349 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1351 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1352 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1354 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1358 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1362 return Py_BuildValue("O", Py_None);
1364 #endif /* def BUP_HAVE_FILE_ATTRS */
1367 #ifndef HAVE_UTIMENSAT
1369 #error "cannot find utimensat or utimes()"
1371 #ifndef HAVE_LUTIMES
1372 #error "cannot find utimensat or lutimes()"
1376 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1380 const long long lltmp = PyLong_AsLongLong(pylong); \
1381 if (lltmp == -1 && PyErr_Occurred()) \
1383 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1385 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1386 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1388 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1394 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1402 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1411 #ifdef HAVE_UTIMENSAT
1413 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1418 PyObject *access_py, *modification_py;
1419 struct timespec ts[2];
1421 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1424 &access_py, &(ts[0].tv_nsec),
1425 &modification_py, &(ts[1].tv_nsec),
1430 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1433 PyErr_SetString(PyExc_ValueError,
1434 "unable to convert access time seconds for utimensat");
1437 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1440 PyErr_SetString(PyExc_ValueError,
1441 "unable to convert modification time seconds for utimensat");
1444 rc = utimensat(fd, path, ts, flag);
1446 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1448 return Py_BuildValue("O", Py_None);
1451 #endif /* def HAVE_UTIMENSAT */
1454 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1456 static int bup_parse_xutimes_args(char **path,
1457 struct timeval tv[2],
1460 PyObject *access_py, *modification_py;
1461 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1463 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1465 &access_py, &access_us,
1466 &modification_py, &modification_us))
1470 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1473 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1476 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1478 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1481 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1484 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1487 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1489 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1495 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1499 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1502 struct timeval tv[2];
1503 if (!bup_parse_xutimes_args(&path, tv, args))
1505 int rc = utimes(path, tv);
1507 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1508 return Py_BuildValue("O", Py_None);
1510 #endif /* def HAVE_UTIMES */
1514 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1517 struct timeval tv[2];
1518 if (!bup_parse_xutimes_args(&path, tv, args))
1520 int rc = lutimes(path, tv);
1522 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1524 return Py_BuildValue("O", Py_None);
1526 #endif /* def HAVE_LUTIMES */
1529 #ifdef HAVE_STAT_ST_ATIM
1530 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1531 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1532 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1533 #elif defined HAVE_STAT_ST_ATIMENSEC
1534 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1535 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1536 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1538 # define BUP_STAT_ATIME_NS(st) 0
1539 # define BUP_STAT_MTIME_NS(st) 0
1540 # define BUP_STAT_CTIME_NS(st) 0
1544 #pragma clang diagnostic push
1545 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1547 static PyObject *stat_struct_to_py(const struct stat *st,
1548 const char *filename,
1551 // We can check the known (via POSIX) signed and unsigned types at
1552 // compile time, but not (easily) the unspecified types, so handle
1553 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1555 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1556 INTEGER_TO_PY(st->st_mode),
1557 (unsigned PY_LONG_LONG) st->st_ino,
1558 INTEGER_TO_PY(st->st_dev),
1559 INTEGER_TO_PY(st->st_nlink),
1560 INTEGER_TO_PY(st->st_uid),
1561 INTEGER_TO_PY(st->st_gid),
1562 INTEGER_TO_PY(st->st_rdev),
1563 (PY_LONG_LONG) st->st_size,
1564 INTEGER_TO_PY(st->st_atime),
1565 (long) BUP_STAT_ATIME_NS(st),
1566 INTEGER_TO_PY(st->st_mtime),
1567 (long) BUP_STAT_MTIME_NS(st),
1568 INTEGER_TO_PY(st->st_ctime),
1569 (long) BUP_STAT_CTIME_NS(st));
1572 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1574 static PyObject *bup_stat(PyObject *self, PyObject *args)
1579 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1583 rc = stat(filename, &st);
1585 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1586 return stat_struct_to_py(&st, filename, 0);
1590 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1595 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1599 rc = lstat(filename, &st);
1601 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1602 return stat_struct_to_py(&st, filename, 0);
1606 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1610 if (!PyArg_ParseTuple(args, "i", &fd))
1614 rc = fstat(fd, &st);
1616 return PyErr_SetFromErrno(PyExc_OSError);
1617 return stat_struct_to_py(&st, NULL, fd);
1621 #ifdef HAVE_TM_TM_GMTOFF
1622 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1626 if (!PyArg_ParseTuple(args, "L", &lltime))
1628 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1629 return PyErr_Format(PyExc_OverflowError, "time value too large");
1633 if(localtime_r(&ttime, &tm) == NULL)
1634 return PyErr_SetFromErrno(PyExc_OSError);
1636 // Match the Python struct_time values.
1637 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1638 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1639 tm.tm_hour, tm.tm_min, tm.tm_sec,
1640 tm.tm_wday, tm.tm_yday + 1,
1641 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1643 #endif /* def HAVE_TM_TM_GMTOFF */
1646 #ifdef BUP_MINCORE_BUF_TYPE
1647 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1649 Py_buffer src, dest;
1650 PyObject *py_src_n, *py_src_off, *py_dest_off;
1652 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1653 &src, &py_src_n, &py_src_off,
1654 &dest, &py_dest_off))
1657 PyObject *result = NULL;
1659 unsigned long long src_n, src_off, dest_off;
1660 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1661 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1662 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1663 goto clean_and_return;
1665 unsigned long long src_region_end;
1666 if (!uadd(&src_region_end, src_off, src_n)) {
1667 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1668 goto clean_and_return;
1670 assert(src.len >= 0);
1671 if (src_region_end > (unsigned long long) src.len) {
1672 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1673 goto clean_and_return;
1676 unsigned long long dest_size;
1677 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1678 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1679 goto clean_and_return;
1681 if (dest_off > dest_size) {
1682 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1683 goto clean_and_return;
1687 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1688 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1689 goto clean_and_return;
1691 int rc = mincore((void *)(src.buf + src_off), src_n,
1692 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1694 result = PyErr_SetFromErrno(PyExc_OSError);
1695 goto clean_and_return;
1697 result = Py_BuildValue("O", Py_None);
1700 PyBuffer_Release(&src);
1701 PyBuffer_Release(&dest);
1704 #endif /* def BUP_MINCORE_BUF_TYPE */
1707 static PyMethodDef helper_methods[] = {
1708 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1709 "Write buf excepting zeros at the end. Return trailing zero count." },
1710 { "selftest", selftest, METH_VARARGS,
1711 "Check that the rolling checksum rolls correctly (for unit tests)." },
1712 { "blobbits", blobbits, METH_VARARGS,
1713 "Return the number of bits in the rolling checksum." },
1714 { "splitbuf", splitbuf, METH_VARARGS,
1715 "Split a list of strings based on a rolling checksum." },
1716 { "bitmatch", bitmatch, METH_VARARGS,
1717 "Count the number of matching prefix bits between two strings." },
1718 { "firstword", firstword, METH_VARARGS,
1719 "Return an int corresponding to the first 32 bits of buf." },
1720 { "bloom_contains", bloom_contains, METH_VARARGS,
1721 "Check if a bloom filter of 2^nbits bytes contains an object" },
1722 { "bloom_add", bloom_add, METH_VARARGS,
1723 "Add an object to a bloom filter of 2^nbits bytes" },
1724 { "extract_bits", extract_bits, METH_VARARGS,
1725 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1726 { "merge_into", merge_into, METH_VARARGS,
1727 "Merges a bunch of idx and midx files into a single midx." },
1728 { "write_idx", write_idx, METH_VARARGS,
1729 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1730 { "write_random", write_random, METH_VARARGS,
1731 "Write random bytes to the given file descriptor" },
1732 { "random_sha", random_sha, METH_VARARGS,
1733 "Return a random 20-byte string" },
1734 { "open_noatime", open_noatime, METH_VARARGS,
1735 "open() the given filename for read with O_NOATIME if possible" },
1736 { "fadvise_done", fadvise_done, METH_VARARGS,
1737 "Inform the kernel that we're finished with earlier parts of a file" },
1738 #ifdef BUP_HAVE_FILE_ATTRS
1739 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1740 "Return the Linux attributes for the given file." },
1742 #ifdef BUP_HAVE_FILE_ATTRS
1743 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1744 "Set the Linux attributes for the given file." },
1746 #ifdef HAVE_UTIMENSAT
1747 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1748 "Change path timestamps with nanosecond precision (POSIX)." },
1751 { "bup_utimes", bup_utimes, METH_VARARGS,
1752 "Change path timestamps with microsecond precision." },
1755 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1756 "Change path timestamps with microsecond precision;"
1757 " don't follow symlinks." },
1759 { "stat", bup_stat, METH_VARARGS,
1760 "Extended version of stat." },
1761 { "lstat", bup_lstat, METH_VARARGS,
1762 "Extended version of lstat." },
1763 { "fstat", bup_fstat, METH_VARARGS,
1764 "Extended version of fstat." },
1765 #ifdef HAVE_TM_TM_GMTOFF
1766 { "localtime", bup_localtime, METH_VARARGS,
1767 "Return struct_time elements plus the timezone offset and name." },
1769 { "bytescmp", bup_bytescmp, METH_VARARGS,
1770 "Return a negative value if x < y, zero if equal, positive otherwise."},
1771 { "cat_bytes", bup_cat_bytes, METH_VARARGS,
1772 "For (x_bytes, x_ofs, x_n, y_bytes, y_ofs, y_n) arguments, return their concatenation."},
1773 #ifdef BUP_MINCORE_BUF_TYPE
1774 { "mincore", bup_mincore, METH_VARARGS,
1775 "For mincore(src, src_n, src_off, dest, dest_off)"
1776 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1778 { NULL, NULL, 0, NULL }, // sentinel
1781 static void test_integral_assignment_fits(void)
1783 assert(sizeof(signed short) == sizeof(unsigned short));
1784 assert(sizeof(signed short) < sizeof(signed long long));
1785 assert(sizeof(signed short) < sizeof(unsigned long long));
1786 assert(sizeof(unsigned short) < sizeof(signed long long));
1787 assert(sizeof(unsigned short) < sizeof(unsigned long long));
1788 assert(sizeof(Py_ssize_t) <= sizeof(size_t));
1790 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
1791 unsigned short us, usmax = USHRT_MAX;
1792 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
1793 unsigned long long ullmax = ULLONG_MAX;
1795 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
1796 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
1797 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
1798 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
1799 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
1800 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
1802 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
1803 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
1804 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
1805 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
1806 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
1810 static int setup_module(PyObject *m)
1812 // FIXME: migrate these tests to configure, or at least don't
1813 // possibly crash the whole application. Check against the type
1814 // we're going to use when passing to python. Other stat types
1815 // are tested at runtime.
1816 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1817 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1818 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1819 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1820 // Just be sure (relevant when passing timestamps back to Python above).
1821 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1822 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1824 test_integral_assignment_fits();
1826 // Originally required by append_sparse_region()
1829 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1831 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1837 #pragma clang diagnostic push
1838 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1841 value = INTEGER_TO_PY(INT_MAX);
1842 PyObject_SetAttrString(m, "INT_MAX", value);
1844 value = INTEGER_TO_PY(UINT_MAX);
1845 PyObject_SetAttrString(m, "UINT_MAX", value);
1848 #ifdef HAVE_UTIMENSAT
1851 value = INTEGER_TO_PY(AT_FDCWD);
1852 PyObject_SetAttrString(m, "AT_FDCWD", value);
1854 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1855 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1857 value = INTEGER_TO_PY(UTIME_NOW);
1858 PyObject_SetAttrString(m, "UTIME_NOW", value);
1862 #ifdef BUP_HAVE_MINCORE_INCORE
1865 value = INTEGER_TO_PY(MINCORE_INCORE);
1866 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1870 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1872 e = getenv("BUP_FORCE_TTY");
1873 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1879 #if PY_MAJOR_VERSION < 3
1881 PyMODINIT_FUNC init_helpers(void)
1883 PyObject *m = Py_InitModule("_helpers", helper_methods);
1887 if (!setup_module(m))
1894 # else // PY_MAJOR_VERSION >= 3
1896 static struct PyModuleDef helpers_def = {
1897 PyModuleDef_HEAD_INIT,
1903 NULL, // helpers_traverse,
1904 NULL, // helpers_clear,
1908 PyMODINIT_FUNC PyInit__helpers(void)
1910 PyObject *module = PyModule_Create(&helpers_def);
1913 if (!setup_module(module))
1921 #endif // PY_MAJOR_VERSION >= 3