13 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
14 #if __WIN32__ || __CYGWIN__
16 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
17 static void unpythonize_argv(void) { }
19 #else // not __WIN32__
21 // For some reason this isn't declared in Python.h
22 extern void Py_GetArgcArgv(int *argc, char ***argv);
24 static void unpythonize_argv(void)
29 Py_GetArgcArgv(&argc, &argv);
31 for (i = 0; i < argc-1; i++)
33 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
35 // The argv block doesn't work the way we expected; it's unsafe
41 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
43 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
47 p = strrchr(argv[1], '/');
53 memmove(argv[0], p, len);
54 memset(arge - diff, 0, diff);
55 for (i = 0; i < argc; i++)
56 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
61 #endif // not __WIN32__ or __CYGWIN__
64 static PyObject *selftest(PyObject *self, PyObject *args)
66 if (!PyArg_ParseTuple(args, ""))
69 return Py_BuildValue("i", !bupsplit_selftest());
73 static PyObject *blobbits(PyObject *self, PyObject *args)
75 if (!PyArg_ParseTuple(args, ""))
77 return Py_BuildValue("i", BUP_BLOBBITS);
81 static PyObject *splitbuf(PyObject *self, PyObject *args)
83 unsigned char *buf = NULL;
84 int len = 0, out = 0, bits = -1;
86 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
88 out = bupsplit_find_ofs(buf, len, &bits);
89 return Py_BuildValue("ii", out, bits);
93 static PyObject *bitmatch(PyObject *self, PyObject *args)
95 unsigned char *buf1 = NULL, *buf2 = NULL;
96 int len1 = 0, len2 = 0;
99 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
103 for (byte = 0; byte < len1 && byte < len2; byte++)
105 int b1 = buf1[byte], b2 = buf2[byte];
108 for (bit = 0; bit < 8; bit++)
109 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
115 return Py_BuildValue("i", byte*8 + bit);
119 static PyObject *firstword(PyObject *self, PyObject *args)
121 unsigned char *buf = NULL;
125 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
131 v = ntohl(*(uint32_t *)buf);
132 return PyLong_FromUnsignedLong(v);
142 static void to_bloom_address_bitmask4(const bits40_t *buf,
143 const int nbits, uint64_t *v, unsigned char *bitmask)
148 mask = (1<<nbits) - 1;
149 raw = (((uint64_t)ntohl(buf->high)) << 8) | buf->low;
150 bit = (raw >> (37-nbits)) & 0x7;
151 *v = (raw >> (40-nbits)) & mask;
155 static void to_bloom_address_bitmask5(const uint32_t *buf,
156 const int nbits, uint32_t *v, unsigned char *bitmask)
161 mask = (1<<nbits) - 1;
163 bit = (raw >> (29-nbits)) & 0x7;
164 *v = (raw >> (32-nbits)) & mask;
169 #define BLOOM_SET_BIT(name, address, itype, otype) \
170 static void name(unsigned char *bloom, const void *buf, const int nbits)\
172 unsigned char bitmask;\
174 address((itype *)buf, nbits, &v, &bitmask);\
175 bloom[16+v] |= bitmask;\
177 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
178 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
181 #define BLOOM_GET_BIT(name, address, itype, otype) \
182 static int name(const unsigned char *bloom, const void *buf, const int nbits)\
184 unsigned char bitmask;\
186 address((itype *)buf, nbits, &v, &bitmask);\
187 return bloom[16+v] & bitmask;\
189 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
190 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
193 static PyObject *bloom_add(PyObject *self, PyObject *args)
195 unsigned char *sha = NULL, *bloom = NULL;
197 int len = 0, blen = 0, nbits = 0, k = 0;
199 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
202 if (blen < 16+(1<<nbits) || len % 20 != 0)
209 for (end = sha + len; sha < end; sha += 20/k)
210 bloom_set_bit5(bloom, sha, nbits);
216 for (end = sha + len; sha < end; sha += 20/k)
217 bloom_set_bit4(bloom, sha, nbits);
223 return Py_BuildValue("i", len/20);
226 static PyObject *bloom_contains(PyObject *self, PyObject *args)
228 unsigned char *sha = NULL, *bloom = NULL;
229 int len = 0, blen = 0, nbits = 0, k = 0;
233 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
243 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
244 if (!bloom_get_bit5(bloom, sha, nbits))
245 return Py_BuildValue("Oi", Py_None, steps);
251 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
252 if (!bloom_get_bit4(bloom, sha, nbits))
253 return Py_BuildValue("Oi", Py_None, steps);
258 return Py_BuildValue("Oi", Py_True, k);
262 static uint32_t _extract_bits(unsigned char *buf, int nbits)
266 mask = (1<<nbits) - 1;
267 v = ntohl(*(uint32_t *)buf);
268 v = (v >> (32-nbits)) & mask;
271 static PyObject *extract_bits(PyObject *self, PyObject *args)
273 unsigned char *buf = NULL;
274 int len = 0, nbits = 0;
276 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
282 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
287 unsigned char bytes[20];
299 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
302 for (i = 0; i < sizeof(struct sha); i++)
303 if (sha1->bytes[i] != sha2->bytes[i])
304 return sha1->bytes[i] - sha2->bytes[i];
309 static void _fix_idx_order(struct idx **idxs, int *last_i)
312 int low, mid, high, c = 0;
315 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
317 idxs[*last_i] = NULL;
330 mid = (low + high) / 2;
331 c = _cmp_sha(idx->cur, idxs[mid]->cur);
343 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
348 static uint32_t _get_idx_i(struct idx *idx)
350 if (idx->cur_name == NULL)
351 return idx->name_base;
352 return ntohl(*idx->cur_name) + idx->name_base;
355 #define MIDX4_HEADERLEN 12
357 static PyObject *merge_into(PyObject *self, PyObject *args)
359 PyObject *ilist = NULL;
360 unsigned char *fmap = NULL;
361 struct sha *sha_ptr, *last = NULL;
362 uint32_t *table_ptr, *name_ptr;
363 struct idx **idxs = NULL;
364 int flen = 0, bits = 0, i;
365 uint32_t total, count, prefix;
369 if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
372 num_i = PyList_Size(ilist);
373 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
375 for (i = 0; i < num_i; i++)
377 long len, sha_ofs, name_map_ofs;
378 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
379 PyObject *itup = PyList_GetItem(ilist, i);
380 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
381 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
383 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
384 idxs[i]->end = &idxs[i]->cur[len];
386 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
388 idxs[i]->cur_name = NULL;
390 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
391 sha_ptr = (struct sha *)&table_ptr[1<<bits];
392 name_ptr = (uint32_t *)&sha_ptr[total];
401 if (count % 102424 == 0 && istty)
402 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
403 count*100.0/total, count, total);
405 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
406 while (prefix < new_prefix)
407 table_ptr[prefix++] = htonl(count);
408 if (last == NULL || _cmp_sha(last, idx->cur) != 0)
410 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
411 *name_ptr++ = htonl(_get_idx_i(idx));
415 if (idx->cur_name != NULL)
417 _fix_idx_order(idxs, &last_i);
420 table_ptr[prefix] = htonl(count);
423 return PyLong_FromUnsignedLong(count);
426 // This function should techniclly be macro'd out if it's going to be used
427 // more than ocasionally. As of this writing, it'll actually never be called
428 // in real world bup scenarios (because our packs are < MAX_INT bytes).
429 static uint64_t htonll(uint64_t value)
431 static const int endian_test = 42;
433 if (*(char *)&endian_test == endian_test) // LSB-MSB
434 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
435 return value; // already in network byte order MSB-LSB
438 #define PACK_IDX_V2_HEADERLEN 8
439 #define FAN_ENTRIES 256
441 static PyObject *write_idx(PyObject *self, PyObject *args)
443 PyObject *pf = NULL, *idx = NULL;
446 unsigned char *fmap = NULL;
450 int i, j, ofs64_count;
451 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
454 if (!PyArg_ParseTuple(args, "Ow#OI", &pf, &fmap, &flen, &idx, &total))
457 fan_ptr = (uint32_t *)&fmap[PACK_IDX_V2_HEADERLEN];
458 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
459 crc_ptr = (uint32_t *)&sha_ptr[total];
460 ofs_ptr = (uint32_t *)&crc_ptr[total];
461 f = PyFile_AsFile(pf);
465 for (i = 0; i < FAN_ENTRIES; ++i)
468 part = PyList_GET_ITEM(idx, i);
470 plen = PyList_GET_SIZE(part);
472 *fan_ptr++ = htonl(count);
473 for (j = 0; j < plen; ++j)
475 unsigned char *sha = NULL;
479 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
480 &sha, &sha_len, &crc, &ofs))
482 if (sha_len != sizeof(struct sha))
484 memcpy(sha_ptr++, sha, sizeof(struct sha));
485 *crc_ptr++ = htonl(crc);
486 if (ofs > 0x7fffffff)
488 uint64_t nofs = htonll(ofs);
489 if (fwrite(&nofs, sizeof(uint64_t), 1, f) != 1)
490 return PyErr_SetFromErrno(PyExc_OSError);
491 ofs = 0x80000000 | ofs64_count++;
493 *ofs_ptr++ = htonl((uint32_t)ofs);
496 return PyLong_FromUnsignedLong(count);
500 // I would have made this a lower-level function that just fills in a buffer
501 // with random values, and then written those values from python. But that's
502 // about 20% slower in my tests, and since we typically generate random
503 // numbers for benchmarking other parts of bup, any slowness in generating
504 // random bytes will make our benchmarks inaccurate. Plus nobody wants
505 // pseudorandom bytes much except for this anyway.
506 static PyObject *write_random(PyObject *self, PyObject *args)
508 uint32_t buf[1024/4];
509 int fd = -1, seed = 0, verbose = 0;
511 long long len = 0, kbytes = 0, written = 0;
513 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
518 for (kbytes = 0; kbytes < len/1024; kbytes++)
521 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
523 ret = write(fd, buf, sizeof(buf));
527 if (ret < (int)sizeof(buf))
529 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
530 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
533 // handle non-multiples of 1024
537 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
539 ret = write(fd, buf, len % 1024);
546 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
547 return Py_BuildValue("L", written);
551 static PyObject *random_sha(PyObject *self, PyObject *args)
553 static int seeded = 0;
554 uint32_t shabuf[20/4];
559 assert(sizeof(shabuf) == 20);
564 if (!PyArg_ParseTuple(args, ""))
567 memset(shabuf, 0, sizeof(shabuf));
568 for (i=0; i < 20/4; i++)
569 shabuf[i] = random();
570 return Py_BuildValue("s#", shabuf, 20);
574 static PyObject *open_noatime(PyObject *self, PyObject *args)
576 char *filename = NULL;
577 int attrs, attrs_noatime, fd;
578 if (!PyArg_ParseTuple(args, "s", &filename))
585 attrs |= O_LARGEFILE;
587 attrs_noatime = attrs;
589 attrs_noatime |= O_NOATIME;
591 fd = open(filename, attrs_noatime);
592 if (fd < 0 && errno == EPERM)
594 // older Linux kernels would return EPERM if you used O_NOATIME
595 // and weren't the file's owner. This pointless restriction was
596 // relaxed eventually, but we have to handle it anyway.
597 // (VERY old kernels didn't recognized O_NOATIME, but they would
598 // just harmlessly ignore it, so this branch won't trigger)
599 fd = open(filename, attrs);
602 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
603 return Py_BuildValue("i", fd);
607 static PyObject *fadvise_done(PyObject *self, PyObject *args)
611 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
613 #ifdef POSIX_FADV_DONTNEED
614 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
616 return Py_BuildValue("");
620 static PyMethodDef faster_methods[] = {
621 { "selftest", selftest, METH_VARARGS,
622 "Check that the rolling checksum rolls correctly (for unit tests)." },
623 { "blobbits", blobbits, METH_VARARGS,
624 "Return the number of bits in the rolling checksum." },
625 { "splitbuf", splitbuf, METH_VARARGS,
626 "Split a list of strings based on a rolling checksum." },
627 { "bitmatch", bitmatch, METH_VARARGS,
628 "Count the number of matching prefix bits between two strings." },
629 { "firstword", firstword, METH_VARARGS,
630 "Return an int corresponding to the first 32 bits of buf." },
631 { "bloom_contains", bloom_contains, METH_VARARGS,
632 "Check if a bloom filter of 2^nbits bytes contains an object" },
633 { "bloom_add", bloom_add, METH_VARARGS,
634 "Add an object to a bloom filter of 2^nbits bytes" },
635 { "extract_bits", extract_bits, METH_VARARGS,
636 "Take the first 'nbits' bits from 'buf' and return them as an int." },
637 { "merge_into", merge_into, METH_VARARGS,
638 "Merges a bunch of idx and midx files into a single midx." },
639 { "write_idx", write_idx, METH_VARARGS,
640 "Write a PackIdxV2 file from an idx list of lists of tuples" },
641 { "write_random", write_random, METH_VARARGS,
642 "Write random bytes to the given file descriptor" },
643 { "random_sha", random_sha, METH_VARARGS,
644 "Return a random 20-byte string" },
645 { "open_noatime", open_noatime, METH_VARARGS,
646 "open() the given filename for read with O_NOATIME if possible" },
647 { "fadvise_done", fadvise_done, METH_VARARGS,
648 "Inform the kernel that we're finished with earlier parts of a file" },
649 { NULL, NULL, 0, NULL }, // sentinel
652 PyMODINIT_FUNC init_helpers(void)
654 Py_InitModule("_helpers", faster_methods);
655 istty = isatty(2) || getenv("BUP_FORCE_TTY");