@matheusbsbs / matheus-bagliano / commits / 3c552873c6
Fork 0

index-pack: compare only the first 20-bytes of the key.

The "union delta_base" is a strange beast. It is a 20-byte binary blob key to search a binary searchable deltas[] array, each element of which uses it to represent its base object with either a full 20-byte SHA-1 or an offset in the pack. Which representation is used is determined by another field of the deltas[] array element, obj->type, so there is no room for confusion, as long as we make sure we compare the keys for the same type only with appropriate length. The code compared the full union with memcmp(). When storing the in-pack offset, the union was first cleared before storing an unsigned long, so comparison worked fine. On 64-bit architectures, however, the union typically is 24-byte long; the code did not clear the remaining 4-byte alignment padding when storing a full 20-byte SHA-1 representation. Using memcmp() to compare the whole union was wrong. This fixes the comparison to look at the first 20-bytes of the union, regardless of the architecture. As long as ulong is smaller than 20-bytes this works fine. Signed-off-by: Nicolas Pitre <nico@cam.org> Signed-off-by: Junio C Hamano <junkio@cox.net>

Nicolas Pitre committed Oct 17, 2006 at 16:23 UTC 3c552873c698117689af4e5159c7e491fe3a89a3
1 file changed +10 -4
index-pack.c
+10 -4
@@ -23,6 +23,12 @@ union delta_base {
23 unsigned long offset;
24 };
25
26 +/*
27 + * Even if sizeof(union delta_base) == 24 on 64-bit archs, we really want
28 + * to memcmp() only the first 20 bytes.
29 + */
30 +#define UNION_BASE_SZ 20
31 +
32 struct delta_entry
33 {
34 struct object_entry *obj;
@@ -211,7 +217,7 @@ static int find_delta(const union delta_base *base)
217 struct delta_entry *delta = &deltas[next];
218 int cmp;
219
214 - cmp = memcmp(base, &delta->base, sizeof(*base));
220 + cmp = memcmp(base, &delta->base, UNION_BASE_SZ);
221 if (!cmp)
222 return next;
223 if (cmp < 0) {
@@ -232,9 +238,9 @@ static int find_delta_childs(const union delta_base *base,
238
239 if (first < 0)
240 return -1;
235 - while (first > 0 && !memcmp(&deltas[first - 1].base, base, sizeof(*base)))
241 + while (first > 0 && !memcmp(&deltas[first - 1].base, base, UNION_BASE_SZ))
242 --first;
237 - while (last < end && !memcmp(&deltas[last + 1].base, base, sizeof(*base)))
243 + while (last < end && !memcmp(&deltas[last + 1].base, base, UNION_BASE_SZ))
244 ++last;
245 *first_index = first;
246 *last_index = last;
@@ -312,7 +318,7 @@ static int compare_delta_entry(const void *a, const void *b)
318 {
319 const struct delta_entry *delta_a = a;
320 const struct delta_entry *delta_b = b;
315 - return memcmp(&delta_a->base, &delta_b->base, sizeof(union delta_base));
321 + return memcmp(&delta_a->base, &delta_b->base, UNION_BASE_SZ);
322 }
323
324 static void parse_pack_objects(void)