1 #include "tdb2-source.h"
2 #include "tap-interface.h"
6 static int check(TDB_DATA key, TDB_DATA data, void *private)
8 unsigned int *sizes = private;
10 if (key.dsize > strlen("hello"))
12 if (memcmp(key.dptr, "hello", key.dsize) != 0)
15 if (data.dsize != strlen("world"))
17 if (memcmp(data.dptr, "world", data.dsize) != 0)
20 sizes[0] += key.dsize;
21 sizes[1] += data.dsize;
25 static void tdb1_flip_bit(struct tdb_context *tdb, unsigned int bit)
27 unsigned int off = bit / CHAR_BIT;
28 unsigned char mask = (1 << (bit % CHAR_BIT));
30 if (tdb->file->map_ptr)
31 ((unsigned char *)tdb->file->map_ptr)[off] ^= mask;
34 if (pread(tdb->file->fd, &c, 1, off) != 1)
37 if (pwrite(tdb->file->fd, &c, 1, off) != 1)
42 static void check_test(struct tdb_context *tdb)
45 unsigned int i, verifiable, corrupt, sizes[2], dsize, ksize;
47 ok1(tdb_check(tdb, NULL, NULL) == TDB_SUCCESS);
49 key = tdb_mkdata("hello", strlen("hello"));
50 data = tdb_mkdata("world", strlen("world"));
52 /* Key and data size respectively. */
55 /* 5 keys in hash size 2 means we'll have multichains. */
56 for (key.dsize = 1; key.dsize <= 5; key.dsize++) {
59 if (tdb_store(tdb, key, data, TDB_INSERT) != TDB_SUCCESS)
63 /* This is how many bytes we expect to be verifiable. */
64 /* From the file header. */
65 verifiable = strlen(TDB_MAGIC_FOOD) + 1
66 + 2 * sizeof(uint32_t) + 2 * sizeof(tdb1_off_t)
67 + 2 * sizeof(uint32_t);
68 /* From the free list chain and hash chains. */
69 verifiable += 3 * sizeof(tdb1_off_t);
70 /* From the record headers & tailer */
71 verifiable += 5 * (sizeof(struct tdb1_record) + sizeof(uint32_t));
72 /* The free block: we ignore datalen, keylen, full_hash. */
73 verifiable += sizeof(struct tdb1_record) - 3*sizeof(uint32_t) +
75 /* Our check function verifies the key and data. */
76 verifiable += ksize + dsize;
78 /* Flip one bit at a time, make sure it detects verifiable bytes. */
79 for (i = 0, corrupt = 0; i < tdb->file->map_size * CHAR_BIT; i++) {
80 tdb1_flip_bit(tdb, i);
81 memset(sizes, 0, sizeof(sizes));
82 if (tdb_check(tdb, check, sizes) == TDB_ERR_CORRUPT)
84 else if (sizes[0] != ksize || sizes[1] != dsize)
86 tdb1_flip_bit(tdb, i);
88 ok(corrupt == verifiable * CHAR_BIT, "corrupt %u should be %u",
89 corrupt, verifiable * CHAR_BIT);
92 int main(int argc, char *argv[])
94 struct tdb_context *tdb;
95 union tdb_attribute hsize;
97 hsize.base.attr = TDB_ATTRIBUTE_TDB1_HASHSIZE;
98 hsize.base.next = &tap_log_attr;
99 hsize.tdb1_hashsize.hsize = 2;
102 /* This should use mmap. */
103 tdb = tdb_open("run-corrupt.tdb1", TDB_VERSION1,
104 O_CREAT|O_TRUNC|O_RDWR, 0600, &hsize);
111 /* This should not. */
112 tdb = tdb_open("run-corrupt.tdb1", TDB_VERSION1|TDB_NOMMAP,
113 O_CREAT|O_TRUNC|O_RDWR, 0600, &hsize);
120 return exit_status();