]> arthur.barton.de Git - bup.git/blob - lib/bup/_helpers.c
index: raise children_n limit to struct 'I' max
[bup.git] / lib / bup / _helpers.c
1 #define _LARGEFILE64_SOURCE 1
2 #define PY_SSIZE_T_CLEAN 1
3 #undef NDEBUG
4 #include "../../config/config.h"
5
6 // According to Python, its header has to go first:
7 //   http://docs.python.org/2/c-api/intro.html#include-files
8 #include <Python.h>
9
10 #include <assert.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <arpa/inet.h>
14 #include <stdint.h>
15 #include <stdlib.h>
16 #include <stdio.h>
17
18 #ifdef HAVE_SYS_MMAN_H
19 #include <sys/mman.h>
20 #endif
21 #ifdef HAVE_SYS_TYPES_H
22 #include <sys/types.h>
23 #endif
24 #ifdef HAVE_SYS_STAT_H
25 #include <sys/stat.h>
26 #endif
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30
31 #ifdef HAVE_LINUX_FS_H
32 #include <linux/fs.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37
38 #ifdef HAVE_TM_TM_GMTOFF
39 #include <time.h>
40 #endif
41
42 #include "bupsplit.h"
43
44 #if defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS)
45 #define BUP_HAVE_FILE_ATTRS 1
46 #endif
47
48 /*
49  * Check for incomplete UTIMENSAT support (NetBSD 6), and if so,
50  * pretend we don't have it.
51  */
52 #if !defined(AT_FDCWD) || !defined(AT_SYMLINK_NOFOLLOW)
53 #undef HAVE_UTIMENSAT
54 #endif
55
56 #ifndef FS_NOCOW_FL
57 // Of course, this assumes it's a bitfield value.
58 #define FS_NOCOW_FL 0
59 #endif
60
61 static int istty2 = 0;
62
63
64 #ifndef htonll
65 // This function should technically be macro'd out if it's going to be used
66 // more than ocasionally.  As of this writing, it'll actually never be called
67 // in real world bup scenarios (because our packs are < MAX_INT bytes).
68 static uint64_t htonll(uint64_t value)
69 {
70     static const int endian_test = 42;
71
72     if (*(char *)&endian_test == endian_test) // LSB-MSB
73         return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
74     return value; // already in network byte order MSB-LSB
75 }
76 #endif
77
78
79 #define INTEGRAL_ASSIGNMENT_FITS(dest, src)                             \
80     ({                                                                  \
81         *(dest) = (src);                                                \
82         *(dest) == (src) && (*(dest) < 1) == ((src) < 1);               \
83     })
84
85
86 // At the moment any code that calls INTGER_TO_PY() will have to
87 // disable -Wtautological-compare for clang.  See below.
88
89 #define INTEGER_TO_PY(x) \
90     (((x) >= 0) ? PyLong_FromUnsignedLongLong(x) : PyLong_FromLongLong(x))
91
92
93 static int bup_ulong_from_pyint(unsigned long *x, PyObject *py,
94                                 const char *name)
95 {
96     const long tmp = PyInt_AsLong(py);
97     if (tmp == -1 && PyErr_Occurred())
98     {
99         if (PyErr_ExceptionMatches(PyExc_OverflowError))
100             PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
101                          name);
102         return 0;
103     }
104     if (tmp < 0)
105     {
106         PyErr_Format(PyExc_OverflowError,
107                      "negative %s cannot be converted to unsigned long", name);
108         return 0;
109     }
110     *x = tmp;
111     return 1;
112 }
113
114
115 static int bup_ulong_from_py(unsigned long *x, PyObject *py, const char *name)
116 {
117     if (PyInt_Check(py))
118         return bup_ulong_from_pyint(x, py, name);
119
120     if (!PyLong_Check(py))
121     {
122         PyErr_Format(PyExc_TypeError, "expected integer %s", name);
123         return 0;
124     }
125
126     const unsigned long tmp = PyLong_AsUnsignedLong(py);
127     if (PyErr_Occurred())
128     {
129         if (PyErr_ExceptionMatches(PyExc_OverflowError))
130             PyErr_Format(PyExc_OverflowError, "%s too big for unsigned long",
131                          name);
132         return 0;
133     }
134     *x = tmp;
135     return 1;
136 }
137
138
139 static int bup_uint_from_py(unsigned int *x, PyObject *py, const char *name)
140 {
141     unsigned long tmp;
142     if (!bup_ulong_from_py(&tmp, py, name))
143         return 0;
144
145     if (tmp > UINT_MAX)
146     {
147         PyErr_Format(PyExc_OverflowError, "%s too big for unsigned int", name);
148         return 0;
149     }
150     *x = tmp;
151     return 1;
152 }
153
154 static int bup_ullong_from_py(unsigned PY_LONG_LONG *x, PyObject *py,
155                               const char *name)
156 {
157     if (PyInt_Check(py))
158     {
159         unsigned long tmp;
160         if (bup_ulong_from_pyint(&tmp, py, name))
161         {
162             *x = tmp;
163             return 1;
164         }
165         return 0;
166     }
167
168     if (!PyLong_Check(py))
169     {
170         PyErr_Format(PyExc_TypeError, "integer argument expected for %s", name);
171         return 0;
172     }
173
174     const unsigned PY_LONG_LONG tmp = PyLong_AsUnsignedLongLong(py);
175     if (tmp == (unsigned long long) -1 && PyErr_Occurred())
176     {
177         if (PyErr_ExceptionMatches(PyExc_OverflowError))
178             PyErr_Format(PyExc_OverflowError,
179                          "%s too big for unsigned long long", name);
180         return 0;
181     }
182     *x = tmp;
183     return 1;
184 }
185
186
187 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
188 #if __WIN32__ || __CYGWIN__
189
190 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
191 static void unpythonize_argv(void) { }
192
193 #else // not __WIN32__
194
195 // For some reason this isn't declared in Python.h
196 extern void Py_GetArgcArgv(int *argc, char ***argv);
197
198 static void unpythonize_argv(void)
199 {
200     int argc, i;
201     char **argv, *arge;
202     
203     Py_GetArgcArgv(&argc, &argv);
204     
205     for (i = 0; i < argc-1; i++)
206     {
207         if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
208         {
209             // The argv block doesn't work the way we expected; it's unsafe
210             // to mess with it.
211             return;
212         }
213     }
214     
215     arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
216     
217     if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
218     {
219         char *p;
220         size_t len, diff;
221         p = strrchr(argv[1], '/');
222         if (p)
223         {
224             p++;
225             diff = p - argv[0];
226             len = arge - p;
227             memmove(argv[0], p, len);
228             memset(arge - diff, 0, diff);
229             for (i = 0; i < argc; i++)
230                 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
231         }
232     }
233 }
234
235 #endif // not __WIN32__ or __CYGWIN__
236
237
238 static unsigned long long count_leading_zeros(const unsigned char * const buf,
239                                               unsigned long long len)
240 {
241     const unsigned char *cur = buf;
242     while(len-- && *cur == 0)
243         cur++;
244     return cur - buf;
245 }
246
247
248 static int write_all(int fd, const void *buf, const size_t count)
249 {
250     size_t written = 0;
251     while (written < count)
252     {
253         const ssize_t rc = write(fd, buf + written, count - written);
254         if (rc == -1)
255             return -1;
256         written += rc;
257     }
258     return 0;
259 }
260
261
262 static int uadd(unsigned long long *dest,
263                 const unsigned long long x,
264                 const unsigned long long y)
265 {
266     const unsigned long long result = x + y;
267     if (result < x || result < y)
268         return 0;
269     *dest = result;
270     return 1;
271 }
272
273 static PyObject *append_sparse_region(const int fd, unsigned long long n)
274 {
275     while(n)
276     {
277         off_t new_off;
278         if (!INTEGRAL_ASSIGNMENT_FITS(&new_off, n))
279             new_off = INT_MAX;
280         const off_t off = lseek(fd, new_off, SEEK_CUR);
281         if (off == (off_t) -1)
282             return PyErr_SetFromErrno(PyExc_IOError);
283         n -= new_off;
284     }
285     return NULL;
286 }
287
288
289 static PyObject *bup_write_sparsely(PyObject *self, PyObject *args)
290 {
291     int fd;
292     unsigned char *buf = NULL;
293     Py_ssize_t sbuf_len;
294     PyObject *py_min_sparse_len, *py_prev_sparse_len;
295     if (!PyArg_ParseTuple(args, "it#OO",
296                           &fd, &buf, &sbuf_len,
297                           &py_min_sparse_len, &py_prev_sparse_len))
298         return NULL;
299     unsigned long long min_sparse_len, prev_sparse_len, buf_len;
300     if (!bup_ullong_from_py(&min_sparse_len, py_min_sparse_len, "min_sparse_len"))
301         return NULL;
302     if (!bup_ullong_from_py(&prev_sparse_len, py_prev_sparse_len, "prev_sparse_len"))
303         return NULL;
304     if (sbuf_len < 0)
305         return PyErr_Format(PyExc_ValueError, "negative bufer length");
306     if (!INTEGRAL_ASSIGNMENT_FITS(&buf_len, sbuf_len))
307         return PyErr_Format(PyExc_OverflowError, "buffer length too large");
308
309     // The value of zeros_read indicates the number of zeros read from
310     // buf that haven't been accounted for yet (with respect to cur),
311     // while zeros indicates the total number of pending zeros, which
312     // could be larger in the first iteration if prev_sparse_len
313     // wasn't zero.
314     int rc;
315     unsigned long long unexamined = buf_len;
316     unsigned char *block_start = buf, *cur = buf;
317     unsigned long long zeros, zeros_read = count_leading_zeros(cur, unexamined);
318     assert(zeros_read <= unexamined);
319     unexamined -= zeros_read;
320     if (!uadd(&zeros, prev_sparse_len, zeros_read))
321     {
322         PyObject *err = append_sparse_region(fd, prev_sparse_len);
323         if (err != NULL)
324             return err;
325         zeros = zeros_read;
326     }
327
328     while(unexamined)
329     {
330         if (zeros < min_sparse_len)
331             cur += zeros_read;
332         else
333         {
334             rc = write_all(fd, block_start, cur - block_start);
335             if (rc)
336                 return PyErr_SetFromErrno(PyExc_IOError);
337             PyObject *err = append_sparse_region(fd, zeros);
338             if (err != NULL)
339                 return err;
340             cur += zeros_read;
341             block_start = cur;
342         }
343         // Pending zeros have ether been made sparse, or are going to
344         // be rolled into the next non-sparse block since we know we
345         // now have at least one unexamined non-zero byte.
346         assert(unexamined && *cur != 0);
347         zeros = zeros_read = 0;
348         while (unexamined && *cur != 0)
349         {
350             cur++; unexamined--;
351         }
352         if (unexamined)
353         {
354             zeros_read = count_leading_zeros(cur, unexamined);
355             assert(zeros_read <= unexamined);
356             unexamined -= zeros_read;
357             zeros = zeros_read;
358         }
359     }
360     rc = write_all(fd, block_start, cur - block_start);
361     if (rc)
362         return PyErr_SetFromErrno(PyExc_IOError);
363     return PyLong_FromUnsignedLongLong(zeros);
364 }
365
366
367 static PyObject *selftest(PyObject *self, PyObject *args)
368 {
369     if (!PyArg_ParseTuple(args, ""))
370         return NULL;
371     
372     return Py_BuildValue("i", !bupsplit_selftest());
373 }
374
375
376 static PyObject *blobbits(PyObject *self, PyObject *args)
377 {
378     if (!PyArg_ParseTuple(args, ""))
379         return NULL;
380     return Py_BuildValue("i", BUP_BLOBBITS);
381 }
382
383
384 static PyObject *splitbuf(PyObject *self, PyObject *args)
385 {
386     unsigned char *buf = NULL;
387     Py_ssize_t len = 0;
388     int out = 0, bits = -1;
389
390     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
391         return NULL;
392     assert(len <= INT_MAX);
393     out = bupsplit_find_ofs(buf, len, &bits);
394     if (out) assert(bits >= BUP_BLOBBITS);
395     return Py_BuildValue("ii", out, bits);
396 }
397
398
399 static PyObject *bitmatch(PyObject *self, PyObject *args)
400 {
401     unsigned char *buf1 = NULL, *buf2 = NULL;
402     Py_ssize_t len1 = 0, len2 = 0;
403     Py_ssize_t byte;
404     int bit;
405
406     if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
407         return NULL;
408     
409     bit = 0;
410     for (byte = 0; byte < len1 && byte < len2; byte++)
411     {
412         int b1 = buf1[byte], b2 = buf2[byte];
413         if (b1 != b2)
414         {
415             for (bit = 0; bit < 8; bit++)
416                 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
417                     break;
418             break;
419         }
420     }
421     
422     assert(byte <= (INT_MAX >> 3));
423     return Py_BuildValue("i", byte*8 + bit);
424 }
425
426
427 static PyObject *firstword(PyObject *self, PyObject *args)
428 {
429     unsigned char *buf = NULL;
430     Py_ssize_t len = 0;
431     uint32_t v;
432
433     if (!PyArg_ParseTuple(args, "t#", &buf, &len))
434         return NULL;
435     
436     if (len < 4)
437         return NULL;
438     
439     v = ntohl(*(uint32_t *)buf);
440     return PyLong_FromUnsignedLong(v);
441 }
442
443
444 #define BLOOM2_HEADERLEN 16
445
446 static void to_bloom_address_bitmask4(const unsigned char *buf,
447         const int nbits, uint64_t *v, unsigned char *bitmask)
448 {
449     int bit;
450     uint32_t high;
451     uint64_t raw, mask;
452
453     memcpy(&high, buf, 4);
454     mask = (1<<nbits) - 1;
455     raw = (((uint64_t)ntohl(high) << 8) | buf[4]);
456     bit = (raw >> (37-nbits)) & 0x7;
457     *v = (raw >> (40-nbits)) & mask;
458     *bitmask = 1 << bit;
459 }
460
461 static void to_bloom_address_bitmask5(const unsigned char *buf,
462         const int nbits, uint32_t *v, unsigned char *bitmask)
463 {
464     int bit;
465     uint32_t high;
466     uint32_t raw, mask;
467
468     memcpy(&high, buf, 4);
469     mask = (1<<nbits) - 1;
470     raw = ntohl(high);
471     bit = (raw >> (29-nbits)) & 0x7;
472     *v = (raw >> (32-nbits)) & mask;
473     *bitmask = 1 << bit;
474 }
475
476 #define BLOOM_SET_BIT(name, address, otype) \
477 static void name(unsigned char *bloom, const unsigned char *buf, const int nbits)\
478 {\
479     unsigned char bitmask;\
480     otype v;\
481     address(buf, nbits, &v, &bitmask);\
482     bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
483 }
484 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, uint64_t)
485 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t)
486
487
488 #define BLOOM_GET_BIT(name, address, otype) \
489 static int name(const unsigned char *bloom, const unsigned char *buf, const int nbits)\
490 {\
491     unsigned char bitmask;\
492     otype v;\
493     address(buf, nbits, &v, &bitmask);\
494     return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
495 }
496 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, uint64_t)
497 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t)
498
499
500 static PyObject *bloom_add(PyObject *self, PyObject *args)
501 {
502     unsigned char *sha = NULL, *bloom = NULL;
503     unsigned char *end;
504     Py_ssize_t len = 0, blen = 0;
505     int nbits = 0, k = 0;
506
507     if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
508         return NULL;
509
510     if (blen < 16+(1<<nbits) || len % 20 != 0)
511         return NULL;
512
513     if (k == 5)
514     {
515         if (nbits > 29)
516             return NULL;
517         for (end = sha + len; sha < end; sha += 20/k)
518             bloom_set_bit5(bloom, sha, nbits);
519     }
520     else if (k == 4)
521     {
522         if (nbits > 37)
523             return NULL;
524         for (end = sha + len; sha < end; sha += 20/k)
525             bloom_set_bit4(bloom, sha, nbits);
526     }
527     else
528         return NULL;
529
530
531     return Py_BuildValue("n", len/20);
532 }
533
534 static PyObject *bloom_contains(PyObject *self, PyObject *args)
535 {
536     unsigned char *sha = NULL, *bloom = NULL;
537     Py_ssize_t len = 0, blen = 0;
538     int nbits = 0, k = 0;
539     unsigned char *end;
540     int steps;
541
542     if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
543         return NULL;
544
545     if (len != 20)
546         return NULL;
547
548     if (k == 5)
549     {
550         if (nbits > 29)
551             return NULL;
552         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
553             if (!bloom_get_bit5(bloom, sha, nbits))
554                 return Py_BuildValue("Oi", Py_None, steps);
555     }
556     else if (k == 4)
557     {
558         if (nbits > 37)
559             return NULL;
560         for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
561             if (!bloom_get_bit4(bloom, sha, nbits))
562                 return Py_BuildValue("Oi", Py_None, steps);
563     }
564     else
565         return NULL;
566
567     return Py_BuildValue("ii", 1, k);
568 }
569
570
571 static uint32_t _extract_bits(unsigned char *buf, int nbits)
572 {
573     uint32_t v, mask;
574
575     mask = (1<<nbits) - 1;
576     v = ntohl(*(uint32_t *)buf);
577     v = (v >> (32-nbits)) & mask;
578     return v;
579 }
580
581
582 static PyObject *extract_bits(PyObject *self, PyObject *args)
583 {
584     unsigned char *buf = NULL;
585     Py_ssize_t len = 0;
586     int nbits = 0;
587
588     if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
589         return NULL;
590     
591     if (len < 4)
592         return NULL;
593     
594     return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
595 }
596
597
598 struct sha {
599     unsigned char bytes[20];
600 };
601
602
603 struct idx {
604     unsigned char *map;
605     struct sha *cur;
606     struct sha *end;
607     uint32_t *cur_name;
608     Py_ssize_t bytes;
609     int name_base;
610 };
611
612
613 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
614 {
615     int i;
616     for (i = 0; i < sizeof(struct sha); i++)
617         if (sha1->bytes[i] != sha2->bytes[i])
618             return sha1->bytes[i] - sha2->bytes[i];
619     return 0;
620 }
621
622
623 static void _fix_idx_order(struct idx **idxs, int *last_i)
624 {
625     struct idx *idx;
626     int low, mid, high, c = 0;
627
628     idx = idxs[*last_i];
629     if (idxs[*last_i]->cur >= idxs[*last_i]->end)
630     {
631         idxs[*last_i] = NULL;
632         PyMem_Free(idx);
633         --*last_i;
634         return;
635     }
636     if (*last_i == 0)
637         return;
638
639     low = *last_i-1;
640     mid = *last_i;
641     high = 0;
642     while (low >= high)
643     {
644         mid = (low + high) / 2;
645         c = _cmp_sha(idx->cur, idxs[mid]->cur);
646         if (c < 0)
647             high = mid + 1;
648         else if (c > 0)
649             low = mid - 1;
650         else
651             break;
652     }
653     if (c < 0)
654         ++mid;
655     if (mid == *last_i)
656         return;
657     memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
658     idxs[mid] = idx;
659 }
660
661
662 static uint32_t _get_idx_i(struct idx *idx)
663 {
664     if (idx->cur_name == NULL)
665         return idx->name_base;
666     return ntohl(*idx->cur_name) + idx->name_base;
667 }
668
669 #define MIDX4_HEADERLEN 12
670
671 static PyObject *merge_into(PyObject *self, PyObject *args)
672 {
673     PyObject *py_total, *ilist = NULL;
674     unsigned char *fmap = NULL;
675     struct sha *sha_ptr, *sha_start = NULL;
676     uint32_t *table_ptr, *name_ptr, *name_start;
677     struct idx **idxs = NULL;
678     Py_ssize_t flen = 0;
679     int bits = 0, i;
680     unsigned int total;
681     uint32_t count, prefix;
682     int num_i;
683     int last_i;
684
685     if (!PyArg_ParseTuple(args, "w#iOO",
686                           &fmap, &flen, &bits, &py_total, &ilist))
687         return NULL;
688
689     if (!bup_uint_from_py(&total, py_total, "total"))
690         return NULL;
691
692     num_i = PyList_Size(ilist);
693     idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
694
695     for (i = 0; i < num_i; i++)
696     {
697         long len, sha_ofs, name_map_ofs;
698         idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
699         PyObject *itup = PyList_GetItem(ilist, i);
700         if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
701                     &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
702             return NULL;
703         idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
704         idxs[i]->end = &idxs[i]->cur[len];
705         if (name_map_ofs)
706             idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
707         else
708             idxs[i]->cur_name = NULL;
709     }
710     table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
711     sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
712     name_start = name_ptr = (uint32_t *)&sha_ptr[total];
713
714     last_i = num_i-1;
715     count = 0;
716     prefix = 0;
717     while (last_i >= 0)
718     {
719         struct idx *idx;
720         uint32_t new_prefix;
721         if (count % 102424 == 0 && istty2)
722             fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
723                     count*100.0/total, count, total);
724         idx = idxs[last_i];
725         new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
726         while (prefix < new_prefix)
727             table_ptr[prefix++] = htonl(count);
728         memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
729         *name_ptr++ = htonl(_get_idx_i(idx));
730         ++idx->cur;
731         if (idx->cur_name != NULL)
732             ++idx->cur_name;
733         _fix_idx_order(idxs, &last_i);
734         ++count;
735     }
736     while (prefix < (1<<bits))
737         table_ptr[prefix++] = htonl(count);
738     assert(count == total);
739     assert(prefix == (1<<bits));
740     assert(sha_ptr == sha_start+count);
741     assert(name_ptr == name_start+count);
742
743     PyMem_Free(idxs);
744     return PyLong_FromUnsignedLong(count);
745 }
746
747 #define FAN_ENTRIES 256
748
749 static PyObject *write_idx(PyObject *self, PyObject *args)
750 {
751     char *filename = NULL;
752     PyObject *py_total, *idx = NULL;
753     PyObject *part;
754     unsigned char *fmap = NULL;
755     Py_ssize_t flen = 0;
756     unsigned int total = 0;
757     uint32_t count;
758     int i, j, ofs64_count;
759     uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
760     uint64_t *ofs64_ptr;
761     struct sha *sha_ptr;
762
763     if (!PyArg_ParseTuple(args, "sw#OO",
764                           &filename, &fmap, &flen, &idx, &py_total))
765         return NULL;
766
767     if (!bup_uint_from_py(&total, py_total, "total"))
768         return NULL;
769
770     if (PyList_Size (idx) != FAN_ENTRIES) // Check for list of the right length.
771         return PyErr_Format (PyExc_TypeError, "idx must contain %d entries",
772                              FAN_ENTRIES);
773
774     const char idx_header[] = "\377tOc\0\0\0\002";
775     memcpy (fmap, idx_header, sizeof(idx_header) - 1);
776
777     fan_ptr = (uint32_t *)&fmap[sizeof(idx_header) - 1];
778     sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
779     crc_ptr = (uint32_t *)&sha_ptr[total];
780     ofs_ptr = (uint32_t *)&crc_ptr[total];
781     ofs64_ptr = (uint64_t *)&ofs_ptr[total];
782
783     count = 0;
784     ofs64_count = 0;
785     for (i = 0; i < FAN_ENTRIES; ++i)
786     {
787         int plen;
788         part = PyList_GET_ITEM(idx, i);
789         PyList_Sort(part);
790         plen = PyList_GET_SIZE(part);
791         count += plen;
792         *fan_ptr++ = htonl(count);
793         for (j = 0; j < plen; ++j)
794         {
795             unsigned char *sha = NULL;
796             Py_ssize_t sha_len = 0;
797             PyObject *crc_py, *ofs_py;
798             unsigned int crc;
799             unsigned PY_LONG_LONG ofs_ull;
800             uint64_t ofs;
801             if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#OO",
802                                   &sha, &sha_len, &crc_py, &ofs_py))
803                 return NULL;
804             if(!bup_uint_from_py(&crc, crc_py, "crc"))
805                 return NULL;
806             if(!bup_ullong_from_py(&ofs_ull, ofs_py, "ofs"))
807                 return NULL;
808             assert(crc <= UINT32_MAX);
809             assert(ofs_ull <= UINT64_MAX);
810             ofs = ofs_ull;
811             if (sha_len != sizeof(struct sha))
812                 return NULL;
813             memcpy(sha_ptr++, sha, sizeof(struct sha));
814             *crc_ptr++ = htonl(crc);
815             if (ofs > 0x7fffffff)
816             {
817                 *ofs64_ptr++ = htonll(ofs);
818                 ofs = 0x80000000 | ofs64_count++;
819             }
820             *ofs_ptr++ = htonl((uint32_t)ofs);
821         }
822     }
823
824     int rc = msync(fmap, flen, MS_ASYNC);
825     if (rc != 0)
826         return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
827
828     return PyLong_FromUnsignedLong(count);
829 }
830
831
832 // I would have made this a lower-level function that just fills in a buffer
833 // with random values, and then written those values from python.  But that's
834 // about 20% slower in my tests, and since we typically generate random
835 // numbers for benchmarking other parts of bup, any slowness in generating
836 // random bytes will make our benchmarks inaccurate.  Plus nobody wants
837 // pseudorandom bytes much except for this anyway.
838 static PyObject *write_random(PyObject *self, PyObject *args)
839 {
840     uint32_t buf[1024/4];
841     int fd = -1, seed = 0, verbose = 0;
842     ssize_t ret;
843     long long len = 0, kbytes = 0, written = 0;
844
845     if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
846         return NULL;
847     
848     srandom(seed);
849     
850     for (kbytes = 0; kbytes < len/1024; kbytes++)
851     {
852         unsigned i;
853         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
854             buf[i] = random();
855         ret = write(fd, buf, sizeof(buf));
856         if (ret < 0)
857             ret = 0;
858         written += ret;
859         if (ret < (int)sizeof(buf))
860             break;
861         if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
862             fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
863     }
864     
865     // handle non-multiples of 1024
866     if (len % 1024)
867     {
868         unsigned i;
869         for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
870             buf[i] = random();
871         ret = write(fd, buf, len % 1024);
872         if (ret < 0)
873             ret = 0;
874         written += ret;
875     }
876     
877     if (kbytes/1024 > 0)
878         fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
879     return Py_BuildValue("L", written);
880 }
881
882
883 static PyObject *random_sha(PyObject *self, PyObject *args)
884 {
885     static int seeded = 0;
886     uint32_t shabuf[20/4];
887     int i;
888     
889     if (!seeded)
890     {
891         assert(sizeof(shabuf) == 20);
892         srandom(time(NULL));
893         seeded = 1;
894     }
895     
896     if (!PyArg_ParseTuple(args, ""))
897         return NULL;
898     
899     memset(shabuf, 0, sizeof(shabuf));
900     for (i=0; i < 20/4; i++)
901         shabuf[i] = random();
902     return Py_BuildValue("s#", shabuf, 20);
903 }
904
905
906 static int _open_noatime(const char *filename, int attrs)
907 {
908     int attrs_noatime, fd;
909     attrs |= O_RDONLY;
910 #ifdef O_NOFOLLOW
911     attrs |= O_NOFOLLOW;
912 #endif
913 #ifdef O_LARGEFILE
914     attrs |= O_LARGEFILE;
915 #endif
916     attrs_noatime = attrs;
917 #ifdef O_NOATIME
918     attrs_noatime |= O_NOATIME;
919 #endif
920     fd = open(filename, attrs_noatime);
921     if (fd < 0 && errno == EPERM)
922     {
923         // older Linux kernels would return EPERM if you used O_NOATIME
924         // and weren't the file's owner.  This pointless restriction was
925         // relaxed eventually, but we have to handle it anyway.
926         // (VERY old kernels didn't recognized O_NOATIME, but they would
927         // just harmlessly ignore it, so this branch won't trigger)
928         fd = open(filename, attrs);
929     }
930     return fd;
931 }
932
933
934 static PyObject *open_noatime(PyObject *self, PyObject *args)
935 {
936     char *filename = NULL;
937     int fd;
938     if (!PyArg_ParseTuple(args, "s", &filename))
939         return NULL;
940     fd = _open_noatime(filename, 0);
941     if (fd < 0)
942         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
943     return Py_BuildValue("i", fd);
944 }
945
946
947 static PyObject *fadvise_done(PyObject *self, PyObject *args)
948 {
949     int fd = -1;
950     long long llofs, lllen = 0;
951     if (!PyArg_ParseTuple(args, "iLL", &fd, &llofs, &lllen))
952         return NULL;
953     off_t ofs, len;
954     if (!INTEGRAL_ASSIGNMENT_FITS(&ofs, llofs))
955         return PyErr_Format(PyExc_OverflowError,
956                             "fadvise offset overflows off_t");
957     if (!INTEGRAL_ASSIGNMENT_FITS(&len, lllen))
958         return PyErr_Format(PyExc_OverflowError,
959                             "fadvise length overflows off_t");
960 #ifdef POSIX_FADV_DONTNEED
961     posix_fadvise(fd, ofs, len, POSIX_FADV_DONTNEED);
962 #endif    
963     return Py_BuildValue("");
964 }
965
966
967 // Currently the Linux kernel and FUSE disagree over the type for
968 // FS_IOC_GETFLAGS and FS_IOC_SETFLAGS.  The kernel actually uses int,
969 // but FUSE chose long (matching the declaration in linux/fs.h).  So
970 // if you use int, and then traverse a FUSE filesystem, you may
971 // corrupt the stack.  But if you use long, then you may get invalid
972 // results on big-endian systems.
973 //
974 // For now, we just use long, and then disable Linux attrs entirely
975 // (with a warning) in helpers.py on systems that are affected.
976
977 #ifdef BUP_HAVE_FILE_ATTRS
978 static PyObject *bup_get_linux_file_attr(PyObject *self, PyObject *args)
979 {
980     int rc;
981     unsigned long attr;
982     char *path;
983     int fd;
984
985     if (!PyArg_ParseTuple(args, "s", &path))
986         return NULL;
987
988     fd = _open_noatime(path, O_NONBLOCK);
989     if (fd == -1)
990         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
991
992     attr = 0;  // Handle int/long mismatch (see above)
993     rc = ioctl(fd, FS_IOC_GETFLAGS, &attr);
994     if (rc == -1)
995     {
996         close(fd);
997         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
998     }
999     close(fd);
1000     assert(attr <= UINT_MAX);  // Kernel type is actually int
1001     return PyLong_FromUnsignedLong(attr);
1002 }
1003 #endif /* def BUP_HAVE_FILE_ATTRS */
1004
1005
1006
1007 #ifdef BUP_HAVE_FILE_ATTRS
1008 static PyObject *bup_set_linux_file_attr(PyObject *self, PyObject *args)
1009 {
1010     int rc;
1011     unsigned long orig_attr;
1012     unsigned int attr;
1013     char *path;
1014     PyObject *py_attr;
1015     int fd;
1016
1017     if (!PyArg_ParseTuple(args, "sO", &path, &py_attr))
1018         return NULL;
1019
1020     if (!bup_uint_from_py(&attr, py_attr, "attr"))
1021         return NULL;
1022
1023     fd = open(path, O_RDONLY | O_NONBLOCK | O_LARGEFILE | O_NOFOLLOW);
1024     if (fd == -1)
1025         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1026
1027     // Restrict attr to modifiable flags acdeijstuADST -- see
1028     // chattr(1) and the e2fsprogs source.  Letter to flag mapping is
1029     // in pf.c flags_array[].
1030     attr &= FS_APPEND_FL | FS_COMPR_FL | FS_NODUMP_FL | FS_EXTENT_FL
1031     | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | FS_SECRM_FL | FS_NOTAIL_FL
1032     | FS_UNRM_FL | FS_NOATIME_FL | FS_DIRSYNC_FL | FS_SYNC_FL
1033     | FS_TOPDIR_FL | FS_NOCOW_FL;
1034
1035     // The extents flag can't be removed, so don't (see chattr(1) and chattr.c).
1036     orig_attr = 0; // Handle int/long mismatch (see above)
1037     rc = ioctl(fd, FS_IOC_GETFLAGS, &orig_attr);
1038     assert(orig_attr <= UINT_MAX);  // Kernel type is actually int
1039     if (rc == -1)
1040     {
1041         close(fd);
1042         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1043     }
1044     attr |= ((unsigned int) orig_attr) & FS_EXTENT_FL;
1045
1046     rc = ioctl(fd, FS_IOC_SETFLAGS, &attr);
1047     if (rc == -1)
1048     {
1049         close(fd);
1050         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1051     }
1052
1053     close(fd);
1054     return Py_BuildValue("O", Py_None);
1055 }
1056 #endif /* def BUP_HAVE_FILE_ATTRS */
1057
1058
1059 #ifndef HAVE_UTIMENSAT
1060 #ifndef HAVE_UTIMES
1061 #error "cannot find utimensat or utimes()"
1062 #endif
1063 #ifndef HAVE_LUTIMES
1064 #error "cannot find utimensat or lutimes()"
1065 #endif
1066 #endif
1067
1068 #define ASSIGN_PYLONG_TO_INTEGRAL(dest, pylong, overflow) \
1069     ({                                                     \
1070         int result = 0;                                                 \
1071         *(overflow) = 0;                                                \
1072         const long long lltmp = PyLong_AsLongLong(pylong);              \
1073         if (lltmp == -1 && PyErr_Occurred())                            \
1074         {                                                               \
1075             if (PyErr_ExceptionMatches(PyExc_OverflowError))            \
1076             {                                                           \
1077                 const unsigned long long ulltmp = PyLong_AsUnsignedLongLong(pylong); \
1078                 if (ulltmp == (unsigned long long) -1 && PyErr_Occurred()) \
1079                 {                                                       \
1080                     if (PyErr_ExceptionMatches(PyExc_OverflowError))    \
1081                     {                                                   \
1082                         PyErr_Clear();                                  \
1083                         *(overflow) = 1;                                \
1084                     }                                                   \
1085                 }                                                       \
1086                 if (INTEGRAL_ASSIGNMENT_FITS((dest), ulltmp))           \
1087                     result = 1;                                         \
1088                 else                                                    \
1089                     *(overflow) = 1;                                    \
1090             }                                                           \
1091         }                                                               \
1092         else                                                            \
1093         {                                                               \
1094             if (INTEGRAL_ASSIGNMENT_FITS((dest), lltmp))                \
1095                 result = 1;                                             \
1096             else                                                        \
1097                 *(overflow) = 1;                                        \
1098         }                                                               \
1099         result;                                                         \
1100         })
1101
1102
1103 #ifdef HAVE_UTIMENSAT
1104
1105 static PyObject *bup_utimensat(PyObject *self, PyObject *args)
1106 {
1107     int rc;
1108     int fd, flag;
1109     char *path;
1110     PyObject *access_py, *modification_py;
1111     struct timespec ts[2];
1112
1113     if (!PyArg_ParseTuple(args, "is((Ol)(Ol))i",
1114                           &fd,
1115                           &path,
1116                           &access_py, &(ts[0].tv_nsec),
1117                           &modification_py, &(ts[1].tv_nsec),
1118                           &flag))
1119         return NULL;
1120
1121     int overflow;
1122     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[0].tv_sec), access_py, &overflow))
1123     {
1124         if (overflow)
1125             PyErr_SetString(PyExc_ValueError,
1126                             "unable to convert access time seconds for utimensat");
1127         return NULL;
1128     }
1129     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(ts[1].tv_sec), modification_py, &overflow))
1130     {
1131         if (overflow)
1132             PyErr_SetString(PyExc_ValueError,
1133                             "unable to convert modification time seconds for utimensat");
1134         return NULL;
1135     }
1136     rc = utimensat(fd, path, ts, flag);
1137     if (rc != 0)
1138         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1139
1140     return Py_BuildValue("O", Py_None);
1141 }
1142
1143 #endif /* def HAVE_UTIMENSAT */
1144
1145
1146 #if defined(HAVE_UTIMES) || defined(HAVE_LUTIMES)
1147
1148 static int bup_parse_xutimes_args(char **path,
1149                                   struct timeval tv[2],
1150                                   PyObject *args)
1151 {
1152     PyObject *access_py, *modification_py;
1153     long long access_us, modification_us; // POSIX guarantees tv_usec is signed.
1154
1155     if (!PyArg_ParseTuple(args, "s((OL)(OL))",
1156                           path,
1157                           &access_py, &access_us,
1158                           &modification_py, &modification_us))
1159         return 0;
1160
1161     int overflow;
1162     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[0].tv_sec), access_py, &overflow))
1163     {
1164         if (overflow)
1165             PyErr_SetString(PyExc_ValueError, "unable to convert access time seconds to timeval");
1166         return 0;
1167     }
1168     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[0].tv_usec), access_us))
1169     {
1170         PyErr_SetString(PyExc_ValueError, "unable to convert access time nanoseconds to timeval");
1171         return 0;
1172     }
1173     if (!ASSIGN_PYLONG_TO_INTEGRAL(&(tv[1].tv_sec), modification_py, &overflow))
1174     {
1175         if (overflow)
1176             PyErr_SetString(PyExc_ValueError, "unable to convert modification time seconds to timeval");
1177         return 0;
1178     }
1179     if (!INTEGRAL_ASSIGNMENT_FITS(&(tv[1].tv_usec), modification_us))
1180     {
1181         PyErr_SetString(PyExc_ValueError, "unable to convert modification time nanoseconds to timeval");
1182         return 0;
1183     }
1184     return 1;
1185 }
1186
1187 #endif /* defined(HAVE_UTIMES) || defined(HAVE_LUTIMES) */
1188
1189
1190 #ifdef HAVE_UTIMES
1191 static PyObject *bup_utimes(PyObject *self, PyObject *args)
1192 {
1193     char *path;
1194     struct timeval tv[2];
1195     if (!bup_parse_xutimes_args(&path, tv, args))
1196         return NULL;
1197     int rc = utimes(path, tv);
1198     if (rc != 0)
1199         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1200     return Py_BuildValue("O", Py_None);
1201 }
1202 #endif /* def HAVE_UTIMES */
1203
1204
1205 #ifdef HAVE_LUTIMES
1206 static PyObject *bup_lutimes(PyObject *self, PyObject *args)
1207 {
1208     char *path;
1209     struct timeval tv[2];
1210     if (!bup_parse_xutimes_args(&path, tv, args))
1211         return NULL;
1212     int rc = lutimes(path, tv);
1213     if (rc != 0)
1214         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
1215
1216     return Py_BuildValue("O", Py_None);
1217 }
1218 #endif /* def HAVE_LUTIMES */
1219
1220
1221 #ifdef HAVE_STAT_ST_ATIM
1222 # define BUP_STAT_ATIME_NS(st) (st)->st_atim.tv_nsec
1223 # define BUP_STAT_MTIME_NS(st) (st)->st_mtim.tv_nsec
1224 # define BUP_STAT_CTIME_NS(st) (st)->st_ctim.tv_nsec
1225 #elif defined HAVE_STAT_ST_ATIMENSEC
1226 # define BUP_STAT_ATIME_NS(st) (st)->st_atimespec.tv_nsec
1227 # define BUP_STAT_MTIME_NS(st) (st)->st_mtimespec.tv_nsec
1228 # define BUP_STAT_CTIME_NS(st) (st)->st_ctimespec.tv_nsec
1229 #else
1230 # define BUP_STAT_ATIME_NS(st) 0
1231 # define BUP_STAT_MTIME_NS(st) 0
1232 # define BUP_STAT_CTIME_NS(st) 0
1233 #endif
1234
1235
1236 #pragma clang diagnostic push
1237 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1238
1239 static PyObject *stat_struct_to_py(const struct stat *st,
1240                                    const char *filename,
1241                                    int fd)
1242 {
1243     // We can check the known (via POSIX) signed and unsigned types at
1244     // compile time, but not (easily) the unspecified types, so handle
1245     // those via INTEGER_TO_PY().  Assumes ns values will fit in a
1246     // long.
1247     return Py_BuildValue("OKOOOOOL(Ol)(Ol)(Ol)",
1248                          INTEGER_TO_PY(st->st_mode),
1249                          (unsigned PY_LONG_LONG) st->st_ino,
1250                          INTEGER_TO_PY(st->st_dev),
1251                          INTEGER_TO_PY(st->st_nlink),
1252                          INTEGER_TO_PY(st->st_uid),
1253                          INTEGER_TO_PY(st->st_gid),
1254                          INTEGER_TO_PY(st->st_rdev),
1255                          (PY_LONG_LONG) st->st_size,
1256                          INTEGER_TO_PY(st->st_atime),
1257                          (long) BUP_STAT_ATIME_NS(st),
1258                          INTEGER_TO_PY(st->st_mtime),
1259                          (long) BUP_STAT_MTIME_NS(st),
1260                          INTEGER_TO_PY(st->st_ctime),
1261                          (long) BUP_STAT_CTIME_NS(st));
1262 }
1263
1264 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1265
1266 static PyObject *bup_stat(PyObject *self, PyObject *args)
1267 {
1268     int rc;
1269     char *filename;
1270
1271     if (!PyArg_ParseTuple(args, "s", &filename))
1272         return NULL;
1273
1274     struct stat st;
1275     rc = stat(filename, &st);
1276     if (rc != 0)
1277         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1278     return stat_struct_to_py(&st, filename, 0);
1279 }
1280
1281
1282 static PyObject *bup_lstat(PyObject *self, PyObject *args)
1283 {
1284     int rc;
1285     char *filename;
1286
1287     if (!PyArg_ParseTuple(args, "s", &filename))
1288         return NULL;
1289
1290     struct stat st;
1291     rc = lstat(filename, &st);
1292     if (rc != 0)
1293         return PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1294     return stat_struct_to_py(&st, filename, 0);
1295 }
1296
1297
1298 static PyObject *bup_fstat(PyObject *self, PyObject *args)
1299 {
1300     int rc, fd;
1301
1302     if (!PyArg_ParseTuple(args, "i", &fd))
1303         return NULL;
1304
1305     struct stat st;
1306     rc = fstat(fd, &st);
1307     if (rc != 0)
1308         return PyErr_SetFromErrno(PyExc_OSError);
1309     return stat_struct_to_py(&st, NULL, fd);
1310 }
1311
1312
1313 #ifdef HAVE_TM_TM_GMTOFF
1314 static PyObject *bup_localtime(PyObject *self, PyObject *args)
1315 {
1316     long long lltime;
1317     time_t ttime;
1318     if (!PyArg_ParseTuple(args, "L", &lltime))
1319         return NULL;
1320     if (!INTEGRAL_ASSIGNMENT_FITS(&ttime, lltime))
1321         return PyErr_Format(PyExc_OverflowError, "time value too large");
1322
1323     struct tm tm;
1324     tzset();
1325     if(localtime_r(&ttime, &tm) == NULL)
1326         return PyErr_SetFromErrno(PyExc_OSError);
1327
1328     // Match the Python struct_time values.
1329     return Py_BuildValue("[i,i,i,i,i,i,i,i,i,i,s]",
1330                          1900 + tm.tm_year, tm.tm_mon + 1, tm.tm_mday,
1331                          tm.tm_hour, tm.tm_min, tm.tm_sec,
1332                          tm.tm_wday, tm.tm_yday + 1,
1333                          tm.tm_isdst, tm.tm_gmtoff, tm.tm_zone);
1334 }
1335 #endif /* def HAVE_TM_TM_GMTOFF */
1336
1337
1338 #ifdef BUP_MINCORE_BUF_TYPE
1339 static PyObject *bup_mincore(PyObject *self, PyObject *args)
1340 {
1341     const char *src;
1342     Py_ssize_t src_ssize;
1343     Py_buffer dest;
1344     PyObject *py_src_n, *py_src_off, *py_dest_off;
1345     if (!PyArg_ParseTuple(args, "s#OOw*O",
1346                           &src, &src_ssize, &py_src_n, &py_src_off,
1347                           &dest, &py_dest_off))
1348         return NULL;
1349
1350     unsigned long long src_size, src_n, src_off, dest_size, dest_off;
1351     if (!(bup_ullong_from_py(&src_n, py_src_n, "src_n")
1352           && bup_ullong_from_py(&src_off, py_src_off, "src_off")
1353           && bup_ullong_from_py(&dest_off, py_dest_off, "dest_off")))
1354         return NULL;
1355
1356     if (!INTEGRAL_ASSIGNMENT_FITS(&src_size, src_ssize))
1357         return PyErr_Format(PyExc_OverflowError, "invalid src size");
1358     unsigned long long src_region_end;
1359
1360     if (!uadd(&src_region_end, src_off, src_n))
1361         return PyErr_Format(PyExc_OverflowError, "(src_off + src_n) too large");
1362     if (src_region_end > src_size)
1363         return PyErr_Format(PyExc_OverflowError, "region runs off end of src");
1364
1365     if (!INTEGRAL_ASSIGNMENT_FITS(&dest_size, dest.len))
1366         return PyErr_Format(PyExc_OverflowError, "invalid dest size");
1367     if (dest_off > dest_size)
1368         return PyErr_Format(PyExc_OverflowError, "region runs off end of dest");
1369
1370     size_t length;
1371     if (!INTEGRAL_ASSIGNMENT_FITS(&length, src_n))
1372         return PyErr_Format(PyExc_OverflowError, "src_n overflows size_t");
1373     int rc = mincore((void *)(src + src_off), src_n,
1374                      (BUP_MINCORE_BUF_TYPE *) (dest.buf + dest_off));
1375     if (rc != 0)
1376         return PyErr_SetFromErrno(PyExc_OSError);
1377     return Py_BuildValue("O", Py_None);
1378 }
1379 #endif /* def BUP_MINCORE_BUF_TYPE */
1380
1381
1382 static PyMethodDef helper_methods[] = {
1383     { "write_sparsely", bup_write_sparsely, METH_VARARGS,
1384       "Write buf excepting zeros at the end. Return trailing zero count." },
1385     { "selftest", selftest, METH_VARARGS,
1386         "Check that the rolling checksum rolls correctly (for unit tests)." },
1387     { "blobbits", blobbits, METH_VARARGS,
1388         "Return the number of bits in the rolling checksum." },
1389     { "splitbuf", splitbuf, METH_VARARGS,
1390         "Split a list of strings based on a rolling checksum." },
1391     { "bitmatch", bitmatch, METH_VARARGS,
1392         "Count the number of matching prefix bits between two strings." },
1393     { "firstword", firstword, METH_VARARGS,
1394         "Return an int corresponding to the first 32 bits of buf." },
1395     { "bloom_contains", bloom_contains, METH_VARARGS,
1396         "Check if a bloom filter of 2^nbits bytes contains an object" },
1397     { "bloom_add", bloom_add, METH_VARARGS,
1398         "Add an object to a bloom filter of 2^nbits bytes" },
1399     { "extract_bits", extract_bits, METH_VARARGS,
1400         "Take the first 'nbits' bits from 'buf' and return them as an int." },
1401     { "merge_into", merge_into, METH_VARARGS,
1402         "Merges a bunch of idx and midx files into a single midx." },
1403     { "write_idx", write_idx, METH_VARARGS,
1404         "Write a PackIdxV2 file from an idx list of lists of tuples" },
1405     { "write_random", write_random, METH_VARARGS,
1406         "Write random bytes to the given file descriptor" },
1407     { "random_sha", random_sha, METH_VARARGS,
1408         "Return a random 20-byte string" },
1409     { "open_noatime", open_noatime, METH_VARARGS,
1410         "open() the given filename for read with O_NOATIME if possible" },
1411     { "fadvise_done", fadvise_done, METH_VARARGS,
1412         "Inform the kernel that we're finished with earlier parts of a file" },
1413 #ifdef BUP_HAVE_FILE_ATTRS
1414     { "get_linux_file_attr", bup_get_linux_file_attr, METH_VARARGS,
1415       "Return the Linux attributes for the given file." },
1416 #endif
1417 #ifdef BUP_HAVE_FILE_ATTRS
1418     { "set_linux_file_attr", bup_set_linux_file_attr, METH_VARARGS,
1419       "Set the Linux attributes for the given file." },
1420 #endif
1421 #ifdef HAVE_UTIMENSAT
1422     { "bup_utimensat", bup_utimensat, METH_VARARGS,
1423       "Change path timestamps with nanosecond precision (POSIX)." },
1424 #endif
1425 #ifdef HAVE_UTIMES
1426     { "bup_utimes", bup_utimes, METH_VARARGS,
1427       "Change path timestamps with microsecond precision." },
1428 #endif
1429 #ifdef HAVE_LUTIMES
1430     { "bup_lutimes", bup_lutimes, METH_VARARGS,
1431       "Change path timestamps with microsecond precision;"
1432       " don't follow symlinks." },
1433 #endif
1434     { "stat", bup_stat, METH_VARARGS,
1435       "Extended version of stat." },
1436     { "lstat", bup_lstat, METH_VARARGS,
1437       "Extended version of lstat." },
1438     { "fstat", bup_fstat, METH_VARARGS,
1439       "Extended version of fstat." },
1440 #ifdef HAVE_TM_TM_GMTOFF
1441     { "localtime", bup_localtime, METH_VARARGS,
1442       "Return struct_time elements plus the timezone offset and name." },
1443 #endif
1444 #ifdef BUP_MINCORE_BUF_TYPE
1445     { "mincore", bup_mincore, METH_VARARGS,
1446       "For mincore(src, src_n, src_off, dest, dest_off)"
1447       " call the system mincore(src + src_off, src_n, &dest[dest_off])." },
1448 #endif
1449     { NULL, NULL, 0, NULL },  // sentinel
1450 };
1451
1452
1453 PyMODINIT_FUNC init_helpers(void)
1454 {
1455     // FIXME: migrate these tests to configure.  Check against the
1456     // type we're going to use when passing to python.  Other stat
1457     // types are tested at runtime.
1458     assert(sizeof(ino_t) <= sizeof(unsigned PY_LONG_LONG));
1459     assert(sizeof(off_t) <= sizeof(PY_LONG_LONG));
1460     assert(sizeof(blksize_t) <= sizeof(PY_LONG_LONG));
1461     assert(sizeof(blkcnt_t) <= sizeof(PY_LONG_LONG));
1462     // Just be sure (relevant when passing timestamps back to Python above).
1463     assert(sizeof(PY_LONG_LONG) <= sizeof(long long));
1464     assert(sizeof(unsigned PY_LONG_LONG) <= sizeof(unsigned long long));
1465
1466     if (sizeof(off_t) < sizeof(int))
1467     {
1468         // Originally required by append_sparse_region().
1469         fprintf(stderr, "sizeof(off_t) < sizeof(int); please report.\n");
1470         exit(1);
1471     }
1472
1473     char *e;
1474     PyObject *m = Py_InitModule("_helpers", helper_methods);
1475     if (m == NULL)
1476         return;
1477
1478 #pragma clang diagnostic push
1479 #pragma clang diagnostic ignored "-Wtautological-compare" // For INTEGER_TO_PY().
1480     {
1481         PyObject *value;
1482         value = INTEGER_TO_PY(INT_MAX);
1483         PyObject_SetAttrString(m, "INT_MAX", value);
1484         Py_DECREF(value);
1485         value = INTEGER_TO_PY(UINT_MAX);
1486         PyObject_SetAttrString(m, "UINT_MAX", value);
1487         Py_DECREF(value);
1488     }
1489 #ifdef HAVE_UTIMENSAT
1490     {
1491         PyObject *value;
1492         value = INTEGER_TO_PY(AT_FDCWD);
1493         PyObject_SetAttrString(m, "AT_FDCWD", value);
1494         Py_DECREF(value);
1495         value = INTEGER_TO_PY(AT_SYMLINK_NOFOLLOW);
1496         PyObject_SetAttrString(m, "AT_SYMLINK_NOFOLLOW", value);
1497         Py_DECREF(value);
1498         value = INTEGER_TO_PY(UTIME_NOW);
1499         PyObject_SetAttrString(m, "UTIME_NOW", value);
1500         Py_DECREF(value);
1501     }
1502 #endif
1503 #ifdef BUP_HAVE_MINCORE_INCORE
1504     {
1505         PyObject *value;
1506         value = INTEGER_TO_PY(MINCORE_INCORE);
1507         PyObject_SetAttrString(m, "MINCORE_INCORE", value);
1508         Py_DECREF(value);
1509     }
1510 #endif
1511 #pragma clang diagnostic pop  // ignored "-Wtautological-compare"
1512
1513     e = getenv("BUP_FORCE_TTY");
1514     istty2 = isatty(2) || (atoi(e ? e : "0") & 2);
1515     unpythonize_argv();
1516 }