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