14 // Probably we should use autoconf or something and set HAVE_PY_GETARGCARGV...
15 #if __WIN32__ || __CYGWIN__
17 // There's no 'ps' on win32 anyway, and Py_GetArgcArgv() isn't available.
18 static void unpythonize_argv(void) { }
20 #else // not __WIN32__
22 // For some reason this isn't declared in Python.h
23 extern void Py_GetArgcArgv(int *argc, char ***argv);
25 static void unpythonize_argv(void)
30 Py_GetArgcArgv(&argc, &argv);
32 for (i = 0; i < argc-1; i++)
34 if (argv[i] + strlen(argv[i]) + 1 != argv[i+1])
36 // The argv block doesn't work the way we expected; it's unsafe
42 arge = argv[argc-1] + strlen(argv[argc-1]) + 1;
44 if (strstr(argv[0], "python") && argv[1] == argv[0] + strlen(argv[0]) + 1)
48 p = strrchr(argv[1], '/');
54 memmove(argv[0], p, len);
55 memset(arge - diff, 0, diff);
56 for (i = 0; i < argc; i++)
57 argv[i] = argv[i+1] ? argv[i+1]-diff : NULL;
62 #endif // not __WIN32__ or __CYGWIN__
65 static PyObject *selftest(PyObject *self, PyObject *args)
67 if (!PyArg_ParseTuple(args, ""))
70 return Py_BuildValue("i", !bupsplit_selftest());
74 static PyObject *blobbits(PyObject *self, PyObject *args)
76 if (!PyArg_ParseTuple(args, ""))
78 return Py_BuildValue("i", BUP_BLOBBITS);
82 static PyObject *splitbuf(PyObject *self, PyObject *args)
84 unsigned char *buf = NULL;
85 int len = 0, out = 0, bits = -1;
87 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
89 out = bupsplit_find_ofs(buf, len, &bits);
90 return Py_BuildValue("ii", out, bits);
94 static PyObject *bitmatch(PyObject *self, PyObject *args)
96 unsigned char *buf1 = NULL, *buf2 = NULL;
97 int len1 = 0, len2 = 0;
100 if (!PyArg_ParseTuple(args, "t#t#", &buf1, &len1, &buf2, &len2))
104 for (byte = 0; byte < len1 && byte < len2; byte++)
106 int b1 = buf1[byte], b2 = buf2[byte];
109 for (bit = 0; bit < 8; bit++)
110 if ( (b1 & (0x80 >> bit)) != (b2 & (0x80 >> bit)) )
116 return Py_BuildValue("i", byte*8 + bit);
120 static PyObject *firstword(PyObject *self, PyObject *args)
122 unsigned char *buf = NULL;
126 if (!PyArg_ParseTuple(args, "t#", &buf, &len))
132 v = ntohl(*(uint32_t *)buf);
133 return PyLong_FromUnsignedLong(v);
137 #define BLOOM2_HEADERLEN 16
144 static void to_bloom_address_bitmask4(const bits40_t *buf,
145 const int nbits, uint64_t *v, unsigned char *bitmask)
150 mask = (1<<nbits) - 1;
151 raw = (((uint64_t)ntohl(buf->high)) << 8) | buf->low;
152 bit = (raw >> (37-nbits)) & 0x7;
153 *v = (raw >> (40-nbits)) & mask;
157 static void to_bloom_address_bitmask5(const uint32_t *buf,
158 const int nbits, uint32_t *v, unsigned char *bitmask)
163 mask = (1<<nbits) - 1;
165 bit = (raw >> (29-nbits)) & 0x7;
166 *v = (raw >> (32-nbits)) & mask;
170 #define BLOOM_SET_BIT(name, address, itype, otype) \
171 static void name(unsigned char *bloom, const void *buf, const int nbits)\
173 unsigned char bitmask;\
175 address((itype *)buf, nbits, &v, &bitmask);\
176 bloom[BLOOM2_HEADERLEN+v] |= bitmask;\
178 BLOOM_SET_BIT(bloom_set_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
179 BLOOM_SET_BIT(bloom_set_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
182 #define BLOOM_GET_BIT(name, address, itype, otype) \
183 static int name(const unsigned char *bloom, const void *buf, const int nbits)\
185 unsigned char bitmask;\
187 address((itype *)buf, nbits, &v, &bitmask);\
188 return bloom[BLOOM2_HEADERLEN+v] & bitmask;\
190 BLOOM_GET_BIT(bloom_get_bit4, to_bloom_address_bitmask4, bits40_t, uint64_t)
191 BLOOM_GET_BIT(bloom_get_bit5, to_bloom_address_bitmask5, uint32_t, uint32_t)
194 static PyObject *bloom_add(PyObject *self, PyObject *args)
196 unsigned char *sha = NULL, *bloom = NULL;
198 int len = 0, blen = 0, nbits = 0, k = 0;
200 if (!PyArg_ParseTuple(args, "w#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
203 if (blen < 16+(1<<nbits) || len % 20 != 0)
210 for (end = sha + len; sha < end; sha += 20/k)
211 bloom_set_bit5(bloom, sha, nbits);
217 for (end = sha + len; sha < end; sha += 20/k)
218 bloom_set_bit4(bloom, sha, nbits);
224 return Py_BuildValue("i", len/20);
227 static PyObject *bloom_contains(PyObject *self, PyObject *args)
229 unsigned char *sha = NULL, *bloom = NULL;
230 int len = 0, blen = 0, nbits = 0, k = 0;
234 if (!PyArg_ParseTuple(args, "t#s#ii", &bloom, &blen, &sha, &len, &nbits, &k))
244 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
245 if (!bloom_get_bit5(bloom, sha, nbits))
246 return Py_BuildValue("Oi", Py_None, steps);
252 for (steps = 1, end = sha + 20; sha < end; sha += 20/k, steps++)
253 if (!bloom_get_bit4(bloom, sha, nbits))
254 return Py_BuildValue("Oi", Py_None, steps);
259 return Py_BuildValue("Oi", Py_True, k);
263 static uint32_t _extract_bits(unsigned char *buf, int nbits)
267 mask = (1<<nbits) - 1;
268 v = ntohl(*(uint32_t *)buf);
269 v = (v >> (32-nbits)) & mask;
272 static PyObject *extract_bits(PyObject *self, PyObject *args)
274 unsigned char *buf = NULL;
275 int len = 0, nbits = 0;
277 if (!PyArg_ParseTuple(args, "t#i", &buf, &len, &nbits))
283 return PyLong_FromUnsignedLong(_extract_bits(buf, nbits));
288 unsigned char bytes[20];
300 static int _cmp_sha(const struct sha *sha1, const struct sha *sha2)
303 for (i = 0; i < sizeof(struct sha); i++)
304 if (sha1->bytes[i] != sha2->bytes[i])
305 return sha1->bytes[i] - sha2->bytes[i];
310 static void _fix_idx_order(struct idx **idxs, int *last_i)
313 int low, mid, high, c = 0;
316 if (idxs[*last_i]->cur >= idxs[*last_i]->end)
318 idxs[*last_i] = NULL;
331 mid = (low + high) / 2;
332 c = _cmp_sha(idx->cur, idxs[mid]->cur);
344 memmove(&idxs[mid+1], &idxs[mid], (*last_i-mid)*sizeof(struct idx *));
349 static uint32_t _get_idx_i(struct idx *idx)
351 if (idx->cur_name == NULL)
352 return idx->name_base;
353 return ntohl(*idx->cur_name) + idx->name_base;
356 #define MIDX4_HEADERLEN 12
358 static PyObject *merge_into(PyObject *self, PyObject *args)
360 PyObject *ilist = NULL;
361 unsigned char *fmap = NULL;
362 struct sha *sha_ptr, *sha_start, *last = NULL;
363 uint32_t *table_ptr, *name_ptr, *name_start;
364 struct idx **idxs = NULL;
365 int flen = 0, bits = 0, i;
366 uint32_t total, count, prefix;
370 if (!PyArg_ParseTuple(args, "w#iIO", &fmap, &flen, &bits, &total, &ilist))
373 num_i = PyList_Size(ilist);
374 idxs = (struct idx **)PyMem_Malloc(num_i * sizeof(struct idx *));
376 for (i = 0; i < num_i; i++)
378 long len, sha_ofs, name_map_ofs;
379 idxs[i] = (struct idx *)PyMem_Malloc(sizeof(struct idx));
380 PyObject *itup = PyList_GetItem(ilist, i);
381 if (!PyArg_ParseTuple(itup, "t#llli", &idxs[i]->map, &idxs[i]->bytes,
382 &len, &sha_ofs, &name_map_ofs, &idxs[i]->name_base))
384 idxs[i]->cur = (struct sha *)&idxs[i]->map[sha_ofs];
385 idxs[i]->end = &idxs[i]->cur[len];
387 idxs[i]->cur_name = (uint32_t *)&idxs[i]->map[name_map_ofs];
389 idxs[i]->cur_name = NULL;
391 table_ptr = (uint32_t *)&fmap[MIDX4_HEADERLEN];
392 sha_start = sha_ptr = (struct sha *)&table_ptr[1<<bits];
393 name_start = name_ptr = (uint32_t *)&sha_ptr[total];
402 if (count % 102424 == 0 && istty)
403 fprintf(stderr, "midx: writing %.2f%% (%d/%d)\r",
404 count*100.0/total, count, total);
406 new_prefix = _extract_bits((unsigned char *)idx->cur, bits);
407 while (prefix < new_prefix)
408 table_ptr[prefix++] = htonl(count);
409 memcpy(sha_ptr++, idx->cur, sizeof(struct sha));
410 *name_ptr++ = htonl(_get_idx_i(idx));
413 if (idx->cur_name != NULL)
415 _fix_idx_order(idxs, &last_i);
418 while (prefix < (1<<bits))
419 table_ptr[prefix++] = htonl(count);
420 assert(count == total);
421 assert(prefix == (1<<bits));
422 assert(sha_ptr == sha_start+count);
423 assert(name_ptr == name_start+count);
426 return PyLong_FromUnsignedLong(count);
429 // This function should technically be macro'd out if it's going to be used
430 // more than ocasionally. As of this writing, it'll actually never be called
431 // in real world bup scenarios (because our packs are < MAX_INT bytes).
432 static uint64_t htonll(uint64_t value)
434 static const int endian_test = 42;
436 if (*(char *)&endian_test == endian_test) // LSB-MSB
437 return ((uint64_t)htonl(value & 0xFFFFFFFF) << 32) | htonl(value >> 32);
438 return value; // already in network byte order MSB-LSB
441 #define PACK_IDX_V2_HEADERLEN 8
442 #define FAN_ENTRIES 256
444 static PyObject *write_idx(PyObject *self, PyObject *args)
446 PyObject *pf = NULL, *idx = NULL;
449 unsigned char *fmap = NULL;
453 int i, j, ofs64_count;
454 uint32_t *fan_ptr, *crc_ptr, *ofs_ptr;
457 if (!PyArg_ParseTuple(args, "Ow#OI", &pf, &fmap, &flen, &idx, &total))
460 fan_ptr = (uint32_t *)&fmap[PACK_IDX_V2_HEADERLEN];
461 sha_ptr = (struct sha *)&fan_ptr[FAN_ENTRIES];
462 crc_ptr = (uint32_t *)&sha_ptr[total];
463 ofs_ptr = (uint32_t *)&crc_ptr[total];
464 f = PyFile_AsFile(pf);
468 for (i = 0; i < FAN_ENTRIES; ++i)
471 part = PyList_GET_ITEM(idx, i);
473 plen = PyList_GET_SIZE(part);
475 *fan_ptr++ = htonl(count);
476 for (j = 0; j < plen; ++j)
478 unsigned char *sha = NULL;
482 if (!PyArg_ParseTuple(PyList_GET_ITEM(part, j), "t#IK",
483 &sha, &sha_len, &crc, &ofs))
485 if (sha_len != sizeof(struct sha))
487 memcpy(sha_ptr++, sha, sizeof(struct sha));
488 *crc_ptr++ = htonl(crc);
489 if (ofs > 0x7fffffff)
491 uint64_t nofs = htonll(ofs);
492 if (fwrite(&nofs, sizeof(uint64_t), 1, f) != 1)
493 return PyErr_SetFromErrno(PyExc_OSError);
494 ofs = 0x80000000 | ofs64_count++;
496 *ofs_ptr++ = htonl((uint32_t)ofs);
499 return PyLong_FromUnsignedLong(count);
503 // I would have made this a lower-level function that just fills in a buffer
504 // with random values, and then written those values from python. But that's
505 // about 20% slower in my tests, and since we typically generate random
506 // numbers for benchmarking other parts of bup, any slowness in generating
507 // random bytes will make our benchmarks inaccurate. Plus nobody wants
508 // pseudorandom bytes much except for this anyway.
509 static PyObject *write_random(PyObject *self, PyObject *args)
511 uint32_t buf[1024/4];
512 int fd = -1, seed = 0, verbose = 0;
514 long long len = 0, kbytes = 0, written = 0;
516 if (!PyArg_ParseTuple(args, "iLii", &fd, &len, &seed, &verbose))
521 for (kbytes = 0; kbytes < len/1024; kbytes++)
524 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
526 ret = write(fd, buf, sizeof(buf));
530 if (ret < (int)sizeof(buf))
532 if (verbose && kbytes/1024 > 0 && !(kbytes%1024))
533 fprintf(stderr, "Random: %lld Mbytes\r", kbytes/1024);
536 // handle non-multiples of 1024
540 for (i = 0; i < sizeof(buf)/sizeof(buf[0]); i++)
542 ret = write(fd, buf, len % 1024);
549 fprintf(stderr, "Random: %lld Mbytes, done.\n", kbytes/1024);
550 return Py_BuildValue("L", written);
554 static PyObject *random_sha(PyObject *self, PyObject *args)
556 static int seeded = 0;
557 uint32_t shabuf[20/4];
562 assert(sizeof(shabuf) == 20);
567 if (!PyArg_ParseTuple(args, ""))
570 memset(shabuf, 0, sizeof(shabuf));
571 for (i=0; i < 20/4; i++)
572 shabuf[i] = random();
573 return Py_BuildValue("s#", shabuf, 20);
577 static PyObject *open_noatime(PyObject *self, PyObject *args)
579 char *filename = NULL;
580 int attrs, attrs_noatime, fd;
581 if (!PyArg_ParseTuple(args, "s", &filename))
588 attrs |= O_LARGEFILE;
590 attrs_noatime = attrs;
592 attrs_noatime |= O_NOATIME;
594 fd = open(filename, attrs_noatime);
595 if (fd < 0 && errno == EPERM)
597 // older Linux kernels would return EPERM if you used O_NOATIME
598 // and weren't the file's owner. This pointless restriction was
599 // relaxed eventually, but we have to handle it anyway.
600 // (VERY old kernels didn't recognized O_NOATIME, but they would
601 // just harmlessly ignore it, so this branch won't trigger)
602 fd = open(filename, attrs);
605 return PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
606 return Py_BuildValue("i", fd);
610 static PyObject *fadvise_done(PyObject *self, PyObject *args)
614 if (!PyArg_ParseTuple(args, "iL", &fd, &ofs))
616 #ifdef POSIX_FADV_DONTNEED
617 posix_fadvise(fd, 0, ofs, POSIX_FADV_DONTNEED);
619 return Py_BuildValue("");
623 static PyMethodDef faster_methods[] = {
624 { "selftest", selftest, METH_VARARGS,
625 "Check that the rolling checksum rolls correctly (for unit tests)." },
626 { "blobbits", blobbits, METH_VARARGS,
627 "Return the number of bits in the rolling checksum." },
628 { "splitbuf", splitbuf, METH_VARARGS,
629 "Split a list of strings based on a rolling checksum." },
630 { "bitmatch", bitmatch, METH_VARARGS,
631 "Count the number of matching prefix bits between two strings." },
632 { "firstword", firstword, METH_VARARGS,
633 "Return an int corresponding to the first 32 bits of buf." },
634 { "bloom_contains", bloom_contains, METH_VARARGS,
635 "Check if a bloom filter of 2^nbits bytes contains an object" },
636 { "bloom_add", bloom_add, METH_VARARGS,
637 "Add an object to a bloom filter of 2^nbits bytes" },
638 { "extract_bits", extract_bits, METH_VARARGS,
639 "Take the first 'nbits' bits from 'buf' and return them as an int." },
640 { "merge_into", merge_into, METH_VARARGS,
641 "Merges a bunch of idx and midx files into a single midx." },
642 { "write_idx", write_idx, METH_VARARGS,
643 "Write a PackIdxV2 file from an idx list of lists of tuples" },
644 { "write_random", write_random, METH_VARARGS,
645 "Write random bytes to the given file descriptor" },
646 { "random_sha", random_sha, METH_VARARGS,
647 "Return a random 20-byte string" },
648 { "open_noatime", open_noatime, METH_VARARGS,
649 "open() the given filename for read with O_NOATIME if possible" },
650 { "fadvise_done", fadvise_done, METH_VARARGS,
651 "Inform the kernel that we're finished with earlier parts of a file" },
652 { NULL, NULL, 0, NULL }, // sentinel
655 PyMODINIT_FUNC init_helpers(void)
657 Py_InitModule("_helpers", faster_methods);
658 istty = isatty(2) || getenv("BUP_FORCE_TTY");