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_calloc(size_t n, size_t size)
94 void *result = calloc(n, size);
100 #ifndef BUP_HAVE_BUILTIN_MUL_OVERFLOW
102 #define checked_malloc checked_calloc
104 #else // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
106 static void *checked_malloc(size_t n, size_t size)
109 if (__builtin_mul_overflow(n, size, &total))
111 PyErr_Format(PyExc_OverflowError,
112 "request to allocate %lu items of size %lu is too large",
116 void *result = malloc(total);
118 return PyErr_NoMemory();
122 #endif // defined BUP_HAVE_BUILTIN_MUL_OVERFLOW
126 // This function should technically be macro'd out if it's going to be used
127 // more than ocasionally. As of this writing, it'll actually never be called
128 // in real world bup scenarios (because our packs are < MAX_INT bytes).
129 static uint64_t htonll(uint64_t value)
131 static const int endian_test = 42;
133 if (*(char *)&endian_test == endian_test) // LSB-MSB
134 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
135 return value; // already in network byte order MSB-LSB
140 // Disabling sign-compare here should be fine since we're explicitly
141 // checking for a sign mismatch, i.e. if the signs don't match, then
142 // it doesn't matter what the value comparison says.
143 // FIXME: ... so should we reverse the order?
144 #define INTEGRAL_ASSIGNMENT_FITS(dest, src) \
146 _Pragma("GCC diagnostic push"); \
147 _Pragma("GCC diagnostic ignored \"-Wsign-compare\""); \
149 int result = *(dest) == (src) && (*(dest) < 1) == ((src) < 1); \
150 _Pragma("GCC diagnostic pop"); \
155 // At the moment any code that calls INTEGER_TO_PY() will have to
156 // disable -Wtautological-compare for clang. See below.
158 #define INTEGER_TO_PY(x) \
159 (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
163 #if PY_MAJOR_VERSION < 3
164 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
167 const long tmp = PyInt_AsLong(py);
168 if (tmp == -1 && PyErr_Occurred())
170 if (PyErr_ExceptionMatches(PyExc_OverflowError))
171 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
177 PyErr_Format(PyExc_OverflowError,
178 "negative %s cannot be converted to unsigned long", name);
187 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
189 #if PY_MAJOR_VERSION < 3
191 return bup_ulong_from_pyint(x, py, name);
194 if (!PyLong_Check(py))
196 PyErr_Format(PyExc_TypeError, "expected integer %s", name);
200 const unsigned long tmp = PyLong_AsUnsignedLong(py);
201 if (PyErr_Occurred())
203 if (PyErr_ExceptionMatches(PyExc_OverflowError))
204 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
213 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
216 if (!bup_ulong_from_py(&tmp, py, name))
221 PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
228 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
231 #if PY_MAJOR_VERSION < 3
235 if (bup_ulong_from_pyint(&tmp, py, name))
244 if (!PyLong_Check(py))
246 PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
250 const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
251 if (tmp == (unsigned long long) -1 && PyErr_Occurred())
253 if (PyErr_ExceptionMatches(PyExc_OverflowError))
254 PyErr_Format(PyExc_OverflowError,
255 "%s too big for unsigned long long", name);
263 static PyObject *bup_bytescmp(PyObject *self, PyObject *args)
265 PyObject *py_s1, *py_s2; // This is really a PyBytes/PyString
266 if (!PyArg_ParseTuple(args, "SS", &py_s1, &py_s2))
269 Py_ssize_t s1_len, s2_len;
270 if (PyBytes_AsStringAndSize(py_s1, &s1, &s1_len) == -1)
272 if (PyBytes_AsStringAndSize(py_s2, &s2, &s2_len) == -1)
274 const Py_ssize_t n = (s1_len < s2_len) ? s1_len : s2_len;
275 const int cmp = memcmp(s1, s2, n);
277 return PyLong_FromLong(cmp);
278 if (s1_len == s2_len)
279 return PyLong_FromLong(0);;
280 return PyLong_FromLong((s1_len < s2_len) ? -1 : 1);
284 static PyObject *bup_cat_bytes(PyObject *self, PyObject *args)
286 unsigned char *bufx = NULL, *bufy = NULL;
287 Py_ssize_t bufx_len, bufx_ofs, bufx_n;
288 Py_ssize_t bufy_len, bufy_ofs, bufy_n;
289 if (!PyArg_ParseTuple(args,
292 &bufx, &bufx_len, &bufx_ofs, &bufx_n,
293 &bufy, &bufy_len, &bufy_ofs, &bufy_n))
296 return PyErr_Format(PyExc_ValueError, "negative x offset");
298 return PyErr_Format(PyExc_ValueError, "negative x extent");
299 if (bufx_ofs > bufx_len)
300 return PyErr_Format(PyExc_ValueError, "x offset greater than length");
301 if (bufx_n > bufx_len - bufx_ofs)
302 return PyErr_Format(PyExc_ValueError, "x extent past end of buffer");
305 return PyErr_Format(PyExc_ValueError, "negative y offset");
307 return PyErr_Format(PyExc_ValueError, "negative y extent");
308 if (bufy_ofs > bufy_len)
309 return PyErr_Format(PyExc_ValueError, "y offset greater than length");
310 if (bufy_n > bufy_len - bufy_ofs)
311 return PyErr_Format(PyExc_ValueError, "y extent past end of buffer");
313 if (bufy_n > PY_SSIZE_T_MAX - bufx_n)
314 return PyErr_Format(PyExc_OverflowError, "result length too long");
316 PyObject *result = PyBytes_FromStringAndSize(NULL, bufx_n + bufy_n);
318 return PyErr_NoMemory();
319 char *buf = PyBytes_AS_STRING(result);
320 memcpy(buf, bufx + bufx_ofs, bufx_n);
321 memcpy(buf + bufx_n, bufy + bufy_ofs, bufy_n);
327 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
328 #if __WIN32__ || __CYGWIN__
330 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
331 static void unpythonize_argv(void) { }
333 #else // not __WIN32__
335 // For some reason this isn't declared in Python.h
336 extern void Py_GetArgcArgv(int *argc, char ***argv);
338 static void unpythonize_argv(void)
343 Py_GetArgcArgv(&argc, &argv);
345 for (i = 0; i < argc-1; i++)
347 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
349 // The argv block doesn't work the way we expected; it's unsafe
355 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
357 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
361 p = strrchr(argv[1], '/');
367 memmove(argv[0], p, len);
368 memset(arge - diff, 0, diff);
369 for (i = 0; i < argc; i++)
370 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
375 #endif // not __WIN32__ or __CYGWIN__
378 static int write_all(int fd, const void *buf, const size_t count)
381 while (written < count)
383 const ssize_t rc = write(fd, buf + written, count - written);
392 static int uadd(unsigned long long *dest,
393 const unsigned long long x,
394 const unsigned long long y)
396 const unsigned long long result = x + y;
397 if (result < x || result < y)
404 static PyObject *append_sparse_region(const int fd, unsigned long long n)
409 if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
411 const off_t off = lseek(fd, new_off, SEEK_CUR);
412 if (off == (off_t) -1)
413 return PyErr_SetFromErrno(PyExc_IOError);
420 static PyObject *record_sparse_zeros(unsigned long long *new_pending,
422 unsigned long long prev_pending,
423 const unsigned long long count)
425 // Add count additional sparse zeros to prev_pending and store the
426 // result in new_pending, or if the total won't fit in
427 // new_pending, write some of the zeros to fd sparsely, and store
428 // the remaining sum in new_pending.
429 if (!uadd(new_pending, prev_pending, count))
431 PyObject *err = append_sparse_region(fd, prev_pending);
434 *new_pending = count;
440 static byte* find_not_zero(const byte * const start, const byte * const end)
442 // Return a pointer to first non-zero byte between start and end,
443 // or end if there isn't one.
444 assert(start <= end);
445 const unsigned char *cur = start;
446 while (cur < end && *cur == 0)
452 static byte* find_trailing_zeros(const byte * const start,
453 const byte * const end)
455 // Return a pointer to the start of any trailing run of zeros, or
456 // end if there isn't one.
457 assert(start <= end);
460 const byte * cur = end;
461 while (cur > start && *--cur == 0) {}
465 return (byte *) (cur + 1);
469 static byte *find_non_sparse_end(const byte * const start,
470 const byte * const end,
471 const ptrdiff_t min_len)
473 // Return the first pointer to a min_len sparse block in [start,
474 // end) if there is one, otherwise a pointer to the start of any
475 // trailing run of zeros. If there are no trailing zeros, return
481 // Probe in min_len jumps, searching backward from the jump
482 // destination for a non-zero byte. If such a byte is found, move
483 // just past it and try again.
484 const byte *candidate = start;
485 // End of any run of zeros, starting at candidate, that we've already seen
486 const byte *end_of_known_zeros = candidate;
487 while (end - candidate >= min_len) // Handle all min_len candidate blocks
489 const byte * const probe_end = candidate + min_len;
490 const byte * const trailing_zeros =
491 find_trailing_zeros(end_of_known_zeros, probe_end);
492 if (trailing_zeros == probe_end)
493 end_of_known_zeros = candidate = probe_end;
494 else if (trailing_zeros == end_of_known_zeros)
496 assert(candidate >= start);
497 assert(candidate <= end);
498 assert(*candidate == 0);
499 return (byte *) candidate;
503 candidate = trailing_zeros;
504 end_of_known_zeros = probe_end;
508 if (candidate == end)
511 // No min_len sparse run found, search backward from end
512 const byte * const trailing_zeros = find_trailing_zeros(end_of_known_zeros,
515 if (trailing_zeros == end_of_known_zeros)
517 assert(candidate >= start);
518 assert(candidate < end);
519 assert(*candidate == 0);
520 assert(end - candidate < min_len);
521 return (byte *) candidate;
524 if (trailing_zeros == end)
526 assert(*(end - 1) != 0);
530 assert(end - trailing_zeros < min_len);
531 assert(trailing_zeros >= start);
532 assert(trailing_zeros < end);
533 assert(*trailing_zeros == 0);
534 return (byte *) trailing_zeros;
538 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
541 unsigned char *buf = NULL;
543 PyObject *py_min_sparse_len, *py_prev_sparse_len;
544 if (!PyArg_ParseTuple(args, "i" rbuf_argf "OO",
545 &fd, &buf, &sbuf_len,
546 &py_min_sparse_len, &py_prev_sparse_len))
548 ptrdiff_t min_sparse_len;
549 unsigned long long prev_sparse_len, buf_len, ul_min_sparse_len;
550 if (!bup_ullong_from_py(&ul_min_sparse_len, py_min_sparse_len, "min_sparse_len"))
552 if (!INTEGRAL_ASSIGNMENT_FITS(&min_sparse_len, ul_min_sparse_len))
553 return PyErr_Format(PyExc_OverflowError, "min_sparse_len too large");
554 if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
557 return PyErr_Format(PyExc_ValueError, "negative bufer length");
558 if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
559 return PyErr_Format(PyExc_OverflowError, "buffer length too large");
561 const byte * block = buf; // Start of pending block
562 const byte * const end = buf + buf_len;
563 unsigned long long zeros = prev_sparse_len;
566 assert(block <= end);
568 return PyLong_FromUnsignedLongLong(zeros);
572 // Look for the end of block, i.e. the next sparse run of
573 // at least min_sparse_len zeros, or the end of the
575 const byte * const probe = find_non_sparse_end(block + 1, end,
577 // Either at end of block, or end of non-sparse; write pending data
578 PyObject *err = append_sparse_region(fd, zeros);
581 int rc = write_all(fd, block, probe - block);
583 return PyErr_SetFromErrno(PyExc_IOError);
585 if (end - probe < min_sparse_len)
588 zeros = min_sparse_len;
589 block = probe + zeros;
593 // Should be in the first loop iteration, a sparse run of
594 // zeros, or nearly at the end of the block (within
596 const byte * const zeros_end = find_not_zero(block, end);
597 PyObject *err = record_sparse_zeros(&zeros, fd,
598 zeros, zeros_end - block);
601 assert(block <= zeros_end);
608 static PyObject *selftest(PyObject *self, PyObject *args)
610 if (!PyArg_ParseTuple(args, ""))
613 return Py_BuildValue("i", !bupsplit_selftest());
617 static PyObject *blobbits(PyObject *self, PyObject *args)
619 if (!PyArg_ParseTuple(args, ""))
621 return Py_BuildValue("i", BUP_BLOBBITS);
625 static PyObject *splitbuf(PyObject *self, PyObject *args)
627 // We stick to buffers in python 2 because they appear to be
628 // substantially smaller than memoryviews, and because
629 // zlib.compress() in python 2 can't accept a memoryview
630 // (cf. hashsplit.py).
631 int out = 0, bits = -1;
632 if (PY_MAJOR_VERSION > 2)
635 if (!PyArg_ParseTuple(args, "y*", &buf))
637 assert(buf.len <= INT_MAX);
638 out = bupsplit_find_ofs(buf.buf, buf.len, &bits);
639 PyBuffer_Release(&buf);
643 unsigned char *buf = NULL;
645 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
647 assert(len <= INT_MAX);
648 out = bupsplit_find_ofs(buf, len, &bits);
650 if (out) assert(bits >= BUP_BLOBBITS);
651 return Py_BuildValue("ii", out, bits);
655 static PyObject *bitmatch(PyObject *self, PyObject *args)
657 unsigned char *buf1 = NULL, *buf2 = NULL;
658 Py_ssize_t len1 = 0, len2 = 0;
662 if (!PyArg_ParseTuple(args, rbuf_argf rbuf_argf, &buf1, &len1, &buf2, &len2))
666 for (byte = 0; byte < len1 && byte < len2; byte++)
668 int b1 = buf1[byte], b2 = buf2[byte];
671 for (bit = 0; bit < 8; bit++)
672 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
678 assert(byte <= (INT_MAX >> 3));
679 return Py_BuildValue("i", byte*8 + bit);
683 static PyObject *firstword(PyObject *self, PyObject *args)
685 unsigned char *buf = NULL;
689 if (!PyArg_ParseTuple(args, rbuf_argf, &buf, &len))
695 v = ntohl(*(uint32_t *)buf);
696 return PyLong_FromUnsignedLong(v);
700 #define BLOOM2_HEADERLEN 16
702 static void to_bloom_address_bitmask4(const unsigned char *buf,
703 const int nbits, uint64_t *v, unsigned char *bitmask)
709 memcpy(&high, buf, 4);
710 mask = (1<<nbits) - 1;
711 raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
712 bit = (raw >> (37-nbits)) & 0x7;
713 *v = (raw >> (40-nbits)) & mask;
717 static void to_bloom_address_bitmask5(const unsigned char *buf,
718 const int nbits, uint32_t *v, unsigned char *bitmask)
724 memcpy(&high, buf, 4);
725 mask = (1<<nbits) - 1;
727 bit = (raw >> (29-nbits)) & 0x7;
728 *v = (raw >> (32-nbits)) & mask;
732 #define BLOOM_SET_BIT(name, address, otype) \
733 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
735 unsigned char bitmask;\
737 address(buf, nbits, &v, &bitmask);\
738 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
740 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
741 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
744 #define BLOOM_GET_BIT(name, address, otype) \
745 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
747 unsigned char bitmask;\
749 address(buf, nbits, &v, &bitmask);\
750 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
752 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
753 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
756 static PyObject *bloom_add(PyObject *self, PyObject *args)
758 Py_buffer bloom, sha;
759 int nbits = 0, k = 0;
760 if (!PyArg_ParseTuple(args, wbuf_argf wbuf_argf "ii",
761 &bloom, &sha, &nbits, &k))
764 PyObject *result = NULL;
766 if (bloom.len < 16+(1<<nbits) || sha.len % 20 != 0)
767 goto clean_and_return;
772 goto clean_and_return;
773 unsigned char *cur = sha.buf;
775 for (end = cur + sha.len; cur < end; cur += 20/k)
776 bloom_set_bit5(bloom.buf, cur, nbits);
781 goto clean_and_return;
782 unsigned char *cur = sha.buf;
783 unsigned char *end = cur + sha.len;
784 for (; cur < end; cur += 20/k)
785 bloom_set_bit4(bloom.buf, cur, nbits);
788 goto clean_and_return;
790 result = Py_BuildValue("n", sha.len / 20);
793 PyBuffer_Release(&bloom);
794 PyBuffer_Release(&sha);
798 static PyObject *bloom_contains(PyObject *self, PyObject *args)
801 unsigned char *sha = NULL;
803 int nbits = 0, k = 0;
804 if (!PyArg_ParseTuple(args, wbuf_argf rbuf_argf "ii",
805 &bloom, &sha, &len, &nbits, &k))
808 PyObject *result = NULL;
811 goto clean_and_return;
816 goto clean_and_return;
819 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
820 if (!bloom_get_bit5(bloom.buf, sha, nbits))
822 result = Py_BuildValue("Oi", Py_None, steps);
823 goto clean_and_return;
829 goto clean_and_return;
832 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
833 if (!bloom_get_bit4(bloom.buf, sha, nbits))
835 result = Py_BuildValue("Oi", Py_None, steps);
836 goto clean_and_return;
840 goto clean_and_return;
842 result = Py_BuildValue("ii", 1, k);
845 PyBuffer_Release(&bloom);
850 static uint32_t _extract_bits(unsigned char *buf, int nbits)
854 mask = (1<<nbits) - 1;
855 v = ntohl(*(uint32_t *)buf);
856 v = (v >> (32-nbits)) & mask;
861 static PyObject *extract_bits(PyObject *self, PyObject *args)
863 unsigned char *buf = NULL;
867 if (!PyArg_ParseTuple(args, rbuf_argf "i", &buf, &len, &nbits))
873 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
878 unsigned char bytes[20];
881 static inline int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
883 return memcmp(sha1->bytes, sha2->bytes, sizeof(sha1->bytes));
896 static void _fix_idx_order(struct idx **idxs, Py_ssize_t *last_i)
899 int low, mid, high, c = 0;
902 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
904 idxs[*last_i] = NULL;
917 mid = (low + high) / 2;
918 c = _cmp_sha(idx->cur, idxs[mid]->cur);
930 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
935 static uint32_t _get_idx_i(struct idx *idx)
937 if (idx->cur_name == NULL)
938 return idx->name_base;
939 return ntohl(*idx->cur_name) + idx->name_base;
942 #define MIDX4_HEADERLEN 12
944 static PyObject *merge_into(PyObject *self, PyObject *args)
946 struct sha *sha_ptr, *sha_start = NULL;
947 uint32_t *table_ptr, *name_ptr, *name_start;
950 uint32_t count, prefix;
955 PyObject *py_total, *ilist = NULL;
956 if (!PyArg_ParseTuple(args, wbuf_argf "iOO",
957 &fmap, &bits, &py_total, &ilist))
960 PyObject *result = NULL;
961 struct idx **idxs = NULL;
962 Py_ssize_t num_i = 0;
963 int *idx_buf_init = NULL;
964 Py_buffer *idx_buf = NULL;
966 if (!bup_uint_from_py(&total, py_total, "total"))
967 goto clean_and_return;
969 num_i = PyList_Size(ilist);
971 if (!(idxs = checked_malloc(num_i, sizeof(struct idx *))))
972 goto clean_and_return;
973 if (!(idx_buf_init = checked_calloc(num_i, sizeof(int))))
974 goto clean_and_return;
975 if (!(idx_buf = checked_malloc(num_i, sizeof(Py_buffer))))
976 goto clean_and_return;
978 for (i = 0; i < num_i; i++)
980 long len, sha_ofs, name_map_ofs;
981 if (!(idxs[i] = checked_malloc(1, sizeof(struct idx))))
982 goto clean_and_return;
983 PyObject *itup = PyList_GetItem(ilist, i);
984 if (!PyArg_ParseTuple(itup, wbuf_argf "llli",
985 &(idx_buf[i]), &len, &sha_ofs, &name_map_ofs,
986 &idxs[i]->name_base))
989 idxs[i]->map = idx_buf[i].buf;
990 idxs[i]->bytes = idx_buf[i].len;
991 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
992 idxs[i]->end = &idxs[i]->cur[len];
994 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
996 idxs[i]->cur_name = NULL;
998 table_ptr = (uint32_t *) &((unsigned char *) fmap.buf)[MIDX4_HEADERLEN];
999 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
1000 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
1002 Py_ssize_t last_i = num_i - 1;
1008 uint32_t new_prefix;
1009 if (count % 102424 == 0 && get_state(self)->istty2)
1010 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
1011 count*100.0/total, count, total);
1013 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
1014 while (prefix < new_prefix)
1015 table_ptr[prefix++] = htonl(count);
1016 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
1017 *name_ptr++ = htonl(_get_idx_i(idx));
1019 if (idx->cur_name != NULL)
1021 _fix_idx_order(idxs, &last_i);
1024 while (prefix < ((uint32_t) 1 << bits))
1025 table_ptr[prefix++] = htonl(count);
1026 assert(count == total);
1027 assert(prefix == ((uint32_t) 1 << bits));
1028 assert(sha_ptr == sha_start+count);
1029 assert(name_ptr == name_start+count);
1031 result = PyLong_FromUnsignedLong(count);
1036 for (i = 0; i < num_i; i++)
1037 if (idx_buf_init[i])
1038 PyBuffer_Release(&(idx_buf[i]));
1044 for (i = 0; i < num_i; i++)
1048 PyBuffer_Release(&fmap);
1052 #define FAN_ENTRIES 256
1054 static PyObject *write_idx(PyObject *self, PyObject *args)
1056 char *filename = NULL;
1057 PyObject *py_total, *idx = NULL;
1059 unsigned int total = 0;
1061 int i, j, ofs64_count;
1062 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
1063 uint64_t *ofs64_ptr;
1064 struct sha *sha_ptr;
1067 if (!PyArg_ParseTuple(args, cstr_argf wbuf_argf "OO",
1068 &filename, &fmap, &idx, &py_total))
1071 PyObject *result = NULL;
1073 if (!bup_uint_from_py(&total, py_total, "total"))
1074 goto clean_and_return;
1076 if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
1078 result = PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
1080 goto clean_and_return;
1083 const char idx_header[] = "\377tOc\0\0\0\002";
1084 memcpy (fmap.buf, idx_header, sizeof(idx_header) - 1);
1086 fan_ptr = (uint32_t *)&((unsigned char *)fmap.buf)[sizeof(idx_header) - 1];
1087 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
1088 crc_ptr = (uint32_t *)&sha_ptr[total];
1089 ofs_ptr = (uint32_t *)&crc_ptr[total];
1090 ofs64_ptr = (uint64_t *)&ofs_ptr[total];
1094 for (i = 0; i < FAN_ENTRIES; ++i)
1097 part = PyList_GET_ITEM(idx, i);
1099 plen = PyList_GET_SIZE(part);
1101 *fan_ptr++ = htonl(count);
1102 for (j = 0; j < plen; ++j)
1104 unsigned char *sha = NULL;
1105 Py_ssize_t sha_len = 0;
1106 PyObject *crc_py, *ofs_py;
1108 unsigned PY_LONG_LONG ofs_ull;
1110 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), rbuf_argf "OO",
1111 &sha, &sha_len, &crc_py, &ofs_py))
1112 goto clean_and_return;
1113 if(!bup_uint_from_py(&crc, crc_py, "crc"))
1114 goto clean_and_return;
1115 if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
1116 goto clean_and_return;
1117 assert(crc <= UINT32_MAX);
1118 assert(ofs_ull <= UINT64_MAX);
1120 if (sha_len != sizeof(struct sha))
1121 goto clean_and_return;
1122 memcpy(sha_ptr++, sha, sizeof(struct sha));
1123 *crc_ptr++ = htonl(crc);
1124 if (ofs > 0x7fffffff)
1126 *ofs64_ptr++ = htonll(ofs);
1127 ofs = 0x80000000 | ofs64_count++;
1129 *ofs_ptr++ = htonl((uint32_t)ofs);
1133 int rc = msync(fmap.buf, fmap.len, MS_ASYNC);
1136 result = PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1137 goto clean_and_return;
1140 result = PyLong_FromUnsignedLong(count);
1143 PyBuffer_Release(&fmap);
1148 // I would have made this a lower-level function that just fills in a buffer
1149 // with random values, and then written those values from python. But that's
1150 // about 20% slower in my tests, and since we typically generate random
1151 // numbers for benchmarking other parts of bup, any slowness in generating
1152 // random bytes will make our benchmarks inaccurate. Plus nobody wants
1153 // pseudorandom bytes much except for this anyway.
1154 static PyObject *write_random(PyObject *self, PyObject *args)
1156 uint32_t buf[1024/4];
1157 int fd = -1, seed = 0, verbose = 0;
1159 long long len = 0, kbytes = 0, written = 0;
1161 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
1166 for (kbytes = 0; kbytes < len/1024; kbytes++)
1169 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1171 ret = write(fd, buf, sizeof(buf));
1175 if (ret < (int)sizeof(buf))
1177 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
1178 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
1181 // handle non-multiples of 1024
1185 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
1187 ret = write(fd, buf, len % 1024);
1193 if (kbytes/1024 > 0)
1194 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
1195 return Py_BuildValue("L", written);
1199 static PyObject *random_sha(PyObject *self, PyObject *args)
1201 static int seeded = 0;
1202 uint32_t shabuf[20/4];
1207 assert(sizeof(shabuf) == 20);
1208 srandom(time(NULL));
1212 if (!PyArg_ParseTuple(args, ""))
1215 memset(shabuf, 0, sizeof(shabuf));
1216 for (i=0; i < 20/4; i++)
1217 shabuf[i] = random();
1218 return Py_BuildValue(rbuf_argf, shabuf, 20);
1222 static int _open_noatime(const char *filename, int attrs)
1224 int attrs_noatime, fd;
1227 attrs |= O_NOFOLLOW;
1230 attrs |= O_LARGEFILE;
1232 attrs_noatime = attrs;
1234 attrs_noatime |= O_NOATIME;
1236 fd = open(filename, attrs_noatime);
1237 if (fd < 0 && errno == EPERM)
1239 // older Linux kernels would return EPERM if you used O_NOATIME
1240 // and weren't the file's owner. This pointless restriction was
1241 // relaxed eventually, but we have to handle it anyway.
1242 // (VERY old kernels didn't recognized O_NOATIME, but they would
1243 // just harmlessly ignore it, so this branch won't trigger)
1244 fd = open(filename, attrs);
1250 static PyObject *open_noatime(PyObject *self, PyObject *args)
1252 char *filename = NULL;
1254 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1256 fd = _open_noatime(filename, 0);
1258 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1259 return Py_BuildValue("i", fd);
1263 static PyObject *fadvise_done(PyObject *self, PyObject *args)
1266 long long llofs, lllen = 0;
1267 if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
1270 if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
1271 return PyErr_Format(PyExc_OverflowError,
1272 "fadvise offset overflows off_t");
1273 if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
1274 return PyErr_Format(PyExc_OverflowError,
1275 "fadvise length overflows off_t");
1276 #ifdef POSIX_FADV_DONTNEED
1277 posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
1279 return Py_BuildValue("");
1283 // Currently the Linux kernel and FUSE disagree over the type for
1284 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS. The kernel actually uses int,
1285 // but FUSE chose long (matching the declaration in linux/fs.h). So
1286 // if you use int, and then traverse a FUSE filesystem, you may
1287 // corrupt the stack. But if you use long, then you may get invalid
1288 // results on big-endian systems.
1290 // For now, we just use long, and then disable Linux attrs entirely
1291 // (with a warning) in helpers.py on systems that are affected.
1293 #ifdef BUP_HAVE_FILE_ATTRS
1294 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
1301 if (!PyArg_ParseTuple(args, cstr_argf, &path))
1304 fd = _open_noatime(path, O_NONBLOCK);
1306 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1308 attr = 0; // Handle int/long mismatch (see above)
1309 rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
1313 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1316 assert(attr <= UINT_MAX); // Kernel type is actually int
1317 return PyLong_FromUnsignedLong(attr);
1319 #endif /* def BUP_HAVE_FILE_ATTRS */
1323 #ifdef BUP_HAVE_FILE_ATTRS
1324 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1327 unsigned long orig_attr;
1333 if (!PyArg_ParseTuple(args, cstr_argf "O", &path, &py_attr))
1336 if (!bup_uint_from_py(&attr, py_attr, "attr"))
1339 fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1341 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1343 // Restrict attr to modifiable flags acdeijstuADST -- see
1344 // chattr(1) and the e2fsprogs source. Letter to flag mapping is
1345 // in pf.c flags_array[].
1346 attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1347 | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1348 | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1349 | FS_TOPDIR_FL | FS_NOCOW_FL;
1351 // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1352 orig_attr = 0; // Handle int/long mismatch (see above)
1353 rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1357 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1359 assert(orig_attr <= UINT_MAX); // Kernel type is actually int
1360 attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1362 rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1366 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1370 return Py_BuildValue("O", Py_None);
1372 #endif /* def BUP_HAVE_FILE_ATTRS */
1375 #ifndef HAVE_UTIMENSAT
1377 #error "cannot find utimensat or utimes()"
1379 #ifndef HAVE_LUTIMES
1380 #error "cannot find utimensat or lutimes()"
1384 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1388 const long long lltmp = PyLong_AsLongLong(pylong); \
1389 if (lltmp == -1 && PyErr_Occurred()) \
1391 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1393 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1394 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1396 if (PyErr_ExceptionMatches(PyExc_OverflowError)) \
1402 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp)) \
1410 if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp)) \
1419 #ifdef HAVE_UTIMENSAT
1421 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1426 PyObject *access_py, *modification_py;
1427 struct timespec ts[2];
1429 if (!PyArg_ParseTuple(args, "i" cstr_argf "((Ol)(Ol))i",
1432 &access_py, &(ts[0].tv_nsec),
1433 &modification_py, &(ts[1].tv_nsec),
1438 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1441 PyErr_SetString(PyExc_ValueError,
1442 "unable to convert access time seconds for utimensat");
1445 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1448 PyErr_SetString(PyExc_ValueError,
1449 "unable to convert modification time seconds for utimensat");
1452 rc = utimensat(fd, path, ts, flag);
1454 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1456 return Py_BuildValue("O", Py_None);
1459 #endif /* def HAVE_UTIMENSAT */
1462 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1464 static int bup_parse_xutimes_args(char **path,
1465 struct timeval tv[2],
1468 PyObject *access_py, *modification_py;
1469 long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1471 if (!PyArg_ParseTuple(args, cstr_argf "((OL)(OL))",
1473 &access_py, &access_us,
1474 &modification_py, &modification_us))
1478 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1481 PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1484 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1486 PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1489 if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1492 PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1495 if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1497 PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1503 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1507 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1510 struct timeval tv[2];
1511 if (!bup_parse_xutimes_args(&path, tv, args))
1513 int rc = utimes(path, tv);
1515 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1516 return Py_BuildValue("O", Py_None);
1518 #endif /* def HAVE_UTIMES */
1522 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1525 struct timeval tv[2];
1526 if (!bup_parse_xutimes_args(&path, tv, args))
1528 int rc = lutimes(path, tv);
1530 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1532 return Py_BuildValue("O", Py_None);
1534 #endif /* def HAVE_LUTIMES */
1537 #ifdef HAVE_STAT_ST_ATIM
1538 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1539 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1540 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1541 #elif defined HAVE_STAT_ST_ATIMENSEC
1542 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1543 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1544 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1546 # define BUP_STAT_ATIME_NS(st) 0
1547 # define BUP_STAT_MTIME_NS(st) 0
1548 # define BUP_STAT_CTIME_NS(st) 0
1552 #pragma clang diagnostic push
1553 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1555 static PyObject *stat_struct_to_py(const struct stat *st,
1556 const char *filename,
1559 // We can check the known (via POSIX) signed and unsigned types at
1560 // compile time, but not (easily) the unspecified types, so handle
1561 // those via INTEGER_TO_PY(). Assumes ns values will fit in a
1563 return Py_BuildValue("NKNNNNNL(Nl)(Nl)(Nl)",
1564 INTEGER_TO_PY(st->st_mode),
1565 (unsigned PY_LONG_LONG) st->st_ino,
1566 INTEGER_TO_PY(st->st_dev),
1567 INTEGER_TO_PY(st->st_nlink),
1568 INTEGER_TO_PY(st->st_uid),
1569 INTEGER_TO_PY(st->st_gid),
1570 INTEGER_TO_PY(st->st_rdev),
1571 (PY_LONG_LONG) st->st_size,
1572 INTEGER_TO_PY(st->st_atime),
1573 (long) BUP_STAT_ATIME_NS(st),
1574 INTEGER_TO_PY(st->st_mtime),
1575 (long) BUP_STAT_MTIME_NS(st),
1576 INTEGER_TO_PY(st->st_ctime),
1577 (long) BUP_STAT_CTIME_NS(st));
1580 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1582 static PyObject *bup_stat(PyObject *self, PyObject *args)
1587 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1591 rc = stat(filename, &st);
1593 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1594 return stat_struct_to_py(&st, filename, 0);
1598 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1603 if (!PyArg_ParseTuple(args, cstr_argf, &filename))
1607 rc = lstat(filename, &st);
1609 return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1610 return stat_struct_to_py(&st, filename, 0);
1614 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1618 if (!PyArg_ParseTuple(args, "i", &fd))
1622 rc = fstat(fd, &st);
1624 return PyErr_SetFromErrno(PyExc_OSError);
1625 return stat_struct_to_py(&st, NULL, fd);
1629 #ifdef HAVE_TM_TM_GMTOFF
1630 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1634 if (!PyArg_ParseTuple(args, "L", &lltime))
1636 if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1637 return PyErr_Format(PyExc_OverflowError, "time value too large");
1641 if(localtime_r(&ttime, &tm) == NULL)
1642 return PyErr_SetFromErrno(PyExc_OSError);
1644 // Match the Python struct_time values.
1645 return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1646 1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1647 tm.tm_hour, tm.tm_min, tm.tm_sec,
1648 tm.tm_wday, tm.tm_yday + 1,
1649 tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1651 #endif /* def HAVE_TM_TM_GMTOFF */
1654 #ifdef BUP_MINCORE_BUF_TYPE
1655 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1657 Py_buffer src, dest;
1658 PyObject *py_src_n, *py_src_off, *py_dest_off;
1660 if (!PyArg_ParseTuple(args, cstr_argf "*OOw*O",
1661 &src, &py_src_n, &py_src_off,
1662 &dest, &py_dest_off))
1665 PyObject *result = NULL;
1667 unsigned long long src_n, src_off, dest_off;
1668 if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1669 && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1670 && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1671 goto clean_and_return;
1673 unsigned long long src_region_end;
1674 if (!uadd(&src_region_end, src_off, src_n)) {
1675 result = PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1676 goto clean_and_return;
1678 assert(src.len >= 0);
1679 if (src_region_end > (unsigned long long) src.len) {
1680 result = PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1681 goto clean_and_return;
1684 unsigned long long dest_size;
1685 if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len)) {
1686 result = PyErr_Format(PyExc_OverflowError, "invalid dest size");
1687 goto clean_and_return;
1689 if (dest_off > dest_size) {
1690 result = PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1691 goto clean_and_return;
1695 if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n)) {
1696 result = PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1697 goto clean_and_return;
1699 int rc = mincore((void *)(src.buf + src_off), src_n,
1700 (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1702 result = PyErr_SetFromErrno(PyExc_OSError);
1703 goto clean_and_return;
1705 result = Py_BuildValue("O", Py_None);
1708 PyBuffer_Release(&src);
1709 PyBuffer_Release(&dest);
1712 #endif /* def BUP_MINCORE_BUF_TYPE */
1715 static PyMethodDef helper_methods[] = {
1716 { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1717 "Write buf excepting zeros at the end. Return trailing zero count." },
1718 { "selftest", selftest, METH_VARARGS,
1719 "Check that the rolling checksum rolls correctly (for unit tests)." },
1720 { "blobbits", blobbits, METH_VARARGS,
1721 "Return the number of bits in the rolling checksum." },
1722 { "splitbuf", splitbuf, METH_VARARGS,
1723 "Split a list of strings based on a rolling checksum." },
1724 { "bitmatch", bitmatch, METH_VARARGS,
1725 "Count the number of matching prefix bits between two strings." },
1726 { "firstword", firstword, METH_VARARGS,
1727 "Return an int corresponding to the first 32 bits of buf." },
1728 { "bloom_contains", bloom_contains, METH_VARARGS,
1729 "Check if a bloom filter of 2^nbits bytes contains an object" },
1730 { "bloom_add", bloom_add, METH_VARARGS,
1731 "Add an object to a bloom filter of 2^nbits bytes" },
1732 { "extract_bits", extract_bits, METH_VARARGS,
1733 "Take the first 'nbits' bits from 'buf' and return them as an int." },
1734 { "merge_into", merge_into, METH_VARARGS,
1735 "Merges a bunch of idx and midx files into a single midx." },
1736 { "write_idx", write_idx, METH_VARARGS,
1737 "Write a PackIdxV2 file from an idx list of lists of tuples" },
1738 { "write_random", write_random, METH_VARARGS,
1739 "Write random bytes to the given file descriptor" },
1740 { "random_sha", random_sha, METH_VARARGS,
1741 "Return a random 20-byte string" },
1742 { "open_noatime", open_noatime, METH_VARARGS,
1743 "open() the given filename for read with O_NOATIME if possible" },
1744 { "fadvise_done", fadvise_done, METH_VARARGS,
1745 "Inform the kernel that we're finished with earlier parts of a file" },
1746 #ifdef BUP_HAVE_FILE_ATTRS
1747 { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1748 "Return the Linux attributes for the given file." },
1750 #ifdef BUP_HAVE_FILE_ATTRS
1751 { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1752 "Set the Linux attributes for the given file." },
1754 #ifdef HAVE_UTIMENSAT
1755 { "bup_utimensat", bup_utimensat, METH_VARARGS,
1756 "Change path timestamps with nanosecond precision (POSIX)." },
1759 { "bup_utimes", bup_utimes, METH_VARARGS,
1760 "Change path timestamps with microsecond precision." },
1763 { "bup_lutimes", bup_lutimes, METH_VARARGS,
1764 "Change path timestamps with microsecond precision;"
1765 " don't follow symlinks." },
1767 { "stat", bup_stat, METH_VARARGS,
1768 "Extended version of stat." },
1769 { "lstat", bup_lstat, METH_VARARGS,
1770 "Extended version of lstat." },
1771 { "fstat", bup_fstat, METH_VARARGS,
1772 "Extended version of fstat." },
1773 #ifdef HAVE_TM_TM_GMTOFF
1774 { "localtime", bup_localtime, METH_VARARGS,
1775 "Return struct_time elements plus the timezone offset and name." },
1777 { "bytescmp", bup_bytescmp, METH_VARARGS,
1778 "Return a negative value if x < y, zero if equal, positive otherwise."},
1779 { "cat_bytes", bup_cat_bytes, METH_VARARGS,
1780 "For (x_bytes, x_ofs, x_n, y_bytes, y_ofs, y_n) arguments, return their concatenation."},
1781 #ifdef BUP_MINCORE_BUF_TYPE
1782 { "mincore", bup_mincore, METH_VARARGS,
1783 "For mincore(src, src_n, src_off, dest, dest_off)"
1784 " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1786 { NULL, NULL, 0, NULL }, // sentinel
1789 static void test_integral_assignment_fits(void)
1791 assert(sizeof(signed short) == sizeof(unsigned short));
1792 assert(sizeof(signed short) < sizeof(signed long long));
1793 assert(sizeof(signed short) < sizeof(unsigned long long));
1794 assert(sizeof(unsigned short) < sizeof(signed long long));
1795 assert(sizeof(unsigned short) < sizeof(unsigned long long));
1796 assert(sizeof(Py_ssize_t) <= sizeof(size_t));
1798 signed short ss, ssmin = SHRT_MIN, ssmax = SHRT_MAX;
1799 unsigned short us, usmax = USHRT_MAX;
1800 signed long long sllmin = LLONG_MIN, sllmax = LLONG_MAX;
1801 unsigned long long ullmax = ULLONG_MAX;
1803 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmax));
1804 assert(INTEGRAL_ASSIGNMENT_FITS(&ss, ssmin));
1805 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, usmax));
1806 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmin));
1807 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, sllmax));
1808 assert(!INTEGRAL_ASSIGNMENT_FITS(&ss, ullmax));
1810 assert(INTEGRAL_ASSIGNMENT_FITS(&us, usmax));
1811 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ssmin));
1812 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmin));
1813 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, sllmax));
1814 assert(!INTEGRAL_ASSIGNMENT_FITS(&us, ullmax));
1818 static int setup_module(PyObject *m)
1820 // FIXME: migrate these tests to configure, or at least don't
1821 // possibly crash the whole application. Check against the type
1822 // we're going to use when passing to python. Other stat types
1823 // are tested at runtime.
1824 assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1825 assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1826 assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1827 assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1828 // Just be sure (relevant when passing timestamps back to Python above).
1829 assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1830 assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1832 test_integral_assignment_fits();
1834 // Originally required by append_sparse_region()
1837 if (!INTEGRAL_ASSIGNMENT_FITS(&probe, INT_MAX))
1839 fprintf(stderr, "off_t can't hold INT_MAX; please report.\n");
1845 #pragma clang diagnostic push
1846 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1849 value = INTEGER_TO_PY(INT_MAX);
1850 PyObject_SetAttrString(m, "INT_MAX", value);
1852 value = INTEGER_TO_PY(UINT_MAX);
1853 PyObject_SetAttrString(m, "UINT_MAX", value);
1856 #ifdef HAVE_UTIMENSAT
1859 value = INTEGER_TO_PY(AT_FDCWD);
1860 PyObject_SetAttrString(m, "AT_FDCWD", value);
1862 value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1863 PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1865 value = INTEGER_TO_PY(UTIME_NOW);
1866 PyObject_SetAttrString(m, "UTIME_NOW", value);
1870 #ifdef BUP_HAVE_MINCORE_INCORE
1873 value = INTEGER_TO_PY(MINCORE_INCORE);
1874 PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1878 #pragma clang diagnostic pop // ignored "-Wtautological-compare"
1880 e = getenv("BUP_FORCE_TTY");
1881 get_state(m)->istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1887 #if PY_MAJOR_VERSION < 3
1889 PyMODINIT_FUNC init_helpers(void)
1891 PyObject *m = Py_InitModule("_helpers", helper_methods);
1895 if (!setup_module(m))
1902 # else // PY_MAJOR_VERSION >= 3
1904 static struct PyModuleDef helpers_def = {
1905 PyModuleDef_HEAD_INIT,
1911 NULL, // helpers_traverse,
1912 NULL, // helpers_clear,
1916 PyMODINIT_FUNC PyInit__helpers(void)
1918 PyObject *module = PyModule_Create(&helpers_def);
1921 if (!setup_module(module))
1929 #endif // PY_MAJOR_VERSION >= 3