1 /*
2  * Copyright (C) the libgit2 contributors. All rights reserved.
3  *
4  * This file is part of libgit2, distributed under the GNU GPL v2 with
5  * a Linking Exception. For full terms see the included COPYING file.
6  */
7 
8 #include "oid.h"
9 
10 #include "git2/oid.h"
11 #include "repository.h"
12 #include "threadstate.h"
13 #include <string.h>
14 #include <limits.h>
15 
16 static char to_hex[] = "0123456789abcdef";
17 
oid_error_invalid(const char * msg)18 static int oid_error_invalid(const char *msg)
19 {
20 	git_error_set(GIT_ERROR_INVALID, "unable to parse OID - %s", msg);
21 	return -1;
22 }
23 
git_oid_fromstrn(git_oid * out,const char * str,size_t length)24 int git_oid_fromstrn(git_oid *out, const char *str, size_t length)
25 {
26 	size_t p;
27 	int v;
28 
29 	GIT_ASSERT_ARG(out);
30 	GIT_ASSERT_ARG(str);
31 
32 	if (!length)
33 		return oid_error_invalid("too short");
34 
35 	if (length > GIT_OID_HEXSZ)
36 		return oid_error_invalid("too long");
37 
38 	memset(out->id, 0, GIT_OID_RAWSZ);
39 
40 	for (p = 0; p < length; p++) {
41 		v = git__fromhex(str[p]);
42 		if (v < 0)
43 			return oid_error_invalid("contains invalid characters");
44 
45 		out->id[p / 2] |= (unsigned char)(v << (p % 2 ? 0 : 4));
46 	}
47 
48 	return 0;
49 }
50 
git_oid_fromstrp(git_oid * out,const char * str)51 int git_oid_fromstrp(git_oid *out, const char *str)
52 {
53 	return git_oid_fromstrn(out, str, strlen(str));
54 }
55 
git_oid_fromstr(git_oid * out,const char * str)56 int git_oid_fromstr(git_oid *out, const char *str)
57 {
58 	return git_oid_fromstrn(out, str, GIT_OID_HEXSZ);
59 }
60 
GIT_INLINE(char)61 GIT_INLINE(char) *fmt_one(char *str, unsigned int val)
62 {
63 	*str++ = to_hex[val >> 4];
64 	*str++ = to_hex[val & 0xf];
65 	return str;
66 }
67 
git_oid_nfmt(char * str,size_t n,const git_oid * oid)68 int git_oid_nfmt(char *str, size_t n, const git_oid *oid)
69 {
70 	size_t i, max_i;
71 
72 	if (!oid) {
73 		memset(str, 0, n);
74 		return 0;
75 	}
76 	if (n > GIT_OID_HEXSZ) {
77 		memset(&str[GIT_OID_HEXSZ], 0, n - GIT_OID_HEXSZ);
78 		n = GIT_OID_HEXSZ;
79 	}
80 
81 	max_i = n / 2;
82 
83 	for (i = 0; i < max_i; i++)
84 		str = fmt_one(str, oid->id[i]);
85 
86 	if (n & 1)
87 		*str++ = to_hex[oid->id[i] >> 4];
88 
89 	return 0;
90 }
91 
git_oid_fmt(char * str,const git_oid * oid)92 int git_oid_fmt(char *str, const git_oid *oid)
93 {
94 	return git_oid_nfmt(str, GIT_OID_HEXSZ, oid);
95 }
96 
git_oid_pathfmt(char * str,const git_oid * oid)97 int git_oid_pathfmt(char *str, const git_oid *oid)
98 {
99 	size_t i;
100 
101 	str = fmt_one(str, oid->id[0]);
102 	*str++ = '/';
103 	for (i = 1; i < sizeof(oid->id); i++)
104 		str = fmt_one(str, oid->id[i]);
105 
106 	return 0;
107 }
108 
git_oid_tostr_s(const git_oid * oid)109 char *git_oid_tostr_s(const git_oid *oid)
110 {
111 	char *str = GIT_THREADSTATE->oid_fmt;
112 	git_oid_nfmt(str, GIT_OID_HEXSZ + 1, oid);
113 	return str;
114 }
115 
git_oid_allocfmt(const git_oid * oid)116 char *git_oid_allocfmt(const git_oid *oid)
117 {
118 	char *str = git__malloc(GIT_OID_HEXSZ + 1);
119 	if (!str)
120 		return NULL;
121 	git_oid_nfmt(str, GIT_OID_HEXSZ + 1, oid);
122 	return str;
123 }
124 
git_oid_tostr(char * out,size_t n,const git_oid * oid)125 char *git_oid_tostr(char *out, size_t n, const git_oid *oid)
126 {
127 	if (!out || n == 0)
128 		return "";
129 
130 	if (n > GIT_OID_HEXSZ + 1)
131 		n = GIT_OID_HEXSZ + 1;
132 
133 	git_oid_nfmt(out, n - 1, oid); /* allow room for terminating NUL */
134 	out[n - 1] = '\0';
135 
136 	return out;
137 }
138 
git_oid__parse(git_oid * oid,const char ** buffer_out,const char * buffer_end,const char * header)139 int git_oid__parse(
140 	git_oid *oid, const char **buffer_out,
141 	const char *buffer_end, const char *header)
142 {
143 	const size_t sha_len = GIT_OID_HEXSZ;
144 	const size_t header_len = strlen(header);
145 
146 	const char *buffer = *buffer_out;
147 
148 	if (buffer + (header_len + sha_len + 1) > buffer_end)
149 		return -1;
150 
151 	if (memcmp(buffer, header, header_len) != 0)
152 		return -1;
153 
154 	if (buffer[header_len + sha_len] != '\n')
155 		return -1;
156 
157 	if (git_oid_fromstr(oid, buffer + header_len) < 0)
158 		return -1;
159 
160 	*buffer_out = buffer + (header_len + sha_len + 1);
161 
162 	return 0;
163 }
164 
git_oid__writebuf(git_buf * buf,const char * header,const git_oid * oid)165 void git_oid__writebuf(git_buf *buf, const char *header, const git_oid *oid)
166 {
167 	char hex_oid[GIT_OID_HEXSZ];
168 
169 	git_oid_fmt(hex_oid, oid);
170 	git_buf_puts(buf, header);
171 	git_buf_put(buf, hex_oid, GIT_OID_HEXSZ);
172 	git_buf_putc(buf, '\n');
173 }
174 
git_oid_fromraw(git_oid * out,const unsigned char * raw)175 int git_oid_fromraw(git_oid *out, const unsigned char *raw)
176 {
177 	memcpy(out->id, raw, sizeof(out->id));
178 	return 0;
179 }
180 
git_oid_cpy(git_oid * out,const git_oid * src)181 int git_oid_cpy(git_oid *out, const git_oid *src)
182 {
183 	memcpy(out->id, src->id, sizeof(out->id));
184 	return 0;
185 }
186 
git_oid_cmp(const git_oid * a,const git_oid * b)187 int git_oid_cmp(const git_oid *a, const git_oid *b)
188 {
189 	return git_oid__cmp(a, b);
190 }
191 
git_oid_equal(const git_oid * a,const git_oid * b)192 int git_oid_equal(const git_oid *a, const git_oid *b)
193 {
194 	return (git_oid__cmp(a, b) == 0);
195 }
196 
git_oid_ncmp(const git_oid * oid_a,const git_oid * oid_b,size_t len)197 int git_oid_ncmp(const git_oid *oid_a, const git_oid *oid_b, size_t len)
198 {
199 	const unsigned char *a = oid_a->id;
200 	const unsigned char *b = oid_b->id;
201 
202 	if (len > GIT_OID_HEXSZ)
203 		len = GIT_OID_HEXSZ;
204 
205 	while (len > 1) {
206 		if (*a != *b)
207 			return 1;
208 		a++;
209 		b++;
210 		len -= 2;
211 	};
212 
213 	if (len)
214 		if ((*a ^ *b) & 0xf0)
215 			return 1;
216 
217 	return 0;
218 }
219 
git_oid_strcmp(const git_oid * oid_a,const char * str)220 int git_oid_strcmp(const git_oid *oid_a, const char *str)
221 {
222 	const unsigned char *a;
223 	unsigned char strval;
224 	int hexval;
225 
226 	for (a = oid_a->id; *str && (a - oid_a->id) < GIT_OID_RAWSZ; ++a) {
227 		if ((hexval = git__fromhex(*str++)) < 0)
228 			return -1;
229 		strval = (unsigned char)(hexval << 4);
230 		if (*str) {
231 			if ((hexval = git__fromhex(*str++)) < 0)
232 				return -1;
233 			strval |= hexval;
234 		}
235 		if (*a != strval)
236 			return (*a - strval);
237 	}
238 
239 	return 0;
240 }
241 
git_oid_streq(const git_oid * oid_a,const char * str)242 int git_oid_streq(const git_oid *oid_a, const char *str)
243 {
244 	return git_oid_strcmp(oid_a, str) == 0 ? 0 : -1;
245 }
246 
git_oid_is_zero(const git_oid * oid_a)247 int git_oid_is_zero(const git_oid *oid_a)
248 {
249 	const unsigned char *a = oid_a->id;
250 	unsigned int i;
251 	for (i = 0; i < GIT_OID_RAWSZ; ++i, ++a)
252 		if (*a != 0)
253 			return 0;
254 	return 1;
255 }
256 
257 #ifndef GIT_DEPRECATE_HARD
git_oid_iszero(const git_oid * oid_a)258 int git_oid_iszero(const git_oid *oid_a)
259 {
260 	return git_oid_is_zero(oid_a);
261 }
262 #endif
263 
264 typedef short node_index;
265 
266 typedef union {
267 	const char *tail;
268 	node_index children[16];
269 } trie_node;
270 
271 struct git_oid_shorten {
272 	trie_node *nodes;
273 	size_t node_count, size;
274 	int min_length, full;
275 };
276 
resize_trie(git_oid_shorten * self,size_t new_size)277 static int resize_trie(git_oid_shorten *self, size_t new_size)
278 {
279 	self->nodes = git__reallocarray(self->nodes, new_size, sizeof(trie_node));
280 	GIT_ERROR_CHECK_ALLOC(self->nodes);
281 
282 	if (new_size > self->size) {
283 		memset(&self->nodes[self->size], 0x0, (new_size - self->size) * sizeof(trie_node));
284 	}
285 
286 	self->size = new_size;
287 	return 0;
288 }
289 
push_leaf(git_oid_shorten * os,node_index idx,int push_at,const char * oid)290 static trie_node *push_leaf(git_oid_shorten *os, node_index idx, int push_at, const char *oid)
291 {
292 	trie_node *node, *leaf;
293 	node_index idx_leaf;
294 
295 	if (os->node_count >= os->size) {
296 		if (resize_trie(os, os->size * 2) < 0)
297 			return NULL;
298 	}
299 
300 	idx_leaf = (node_index)os->node_count++;
301 
302 	if (os->node_count == SHRT_MAX) {
303 		os->full = 1;
304         return NULL;
305     }
306 
307 	node = &os->nodes[idx];
308 	node->children[push_at] = -idx_leaf;
309 
310 	leaf = &os->nodes[idx_leaf];
311 	leaf->tail = oid;
312 
313 	return node;
314 }
315 
git_oid_shorten_new(size_t min_length)316 git_oid_shorten *git_oid_shorten_new(size_t min_length)
317 {
318 	git_oid_shorten *os;
319 
320 	GIT_ASSERT_ARG_WITH_RETVAL((size_t)((int)min_length) == min_length, NULL);
321 
322 	os = git__calloc(1, sizeof(git_oid_shorten));
323 	if (os == NULL)
324 		return NULL;
325 
326 	if (resize_trie(os, 16) < 0) {
327 		git__free(os);
328 		return NULL;
329 	}
330 
331 	os->node_count = 1;
332 	os->min_length = (int)min_length;
333 
334 	return os;
335 }
336 
git_oid_shorten_free(git_oid_shorten * os)337 void git_oid_shorten_free(git_oid_shorten *os)
338 {
339 	if (os == NULL)
340 		return;
341 
342 	git__free(os->nodes);
343 	git__free(os);
344 }
345 
346 
347 /*
348  * What wizardry is this?
349  *
350  * This is just a memory-optimized trie: basically a very fancy
351  * 16-ary tree, which is used to store the prefixes of the OID
352  * strings.
353  *
354  * Read more: http://en.wikipedia.org/wiki/Trie
355  *
356  * Magic that happens in this method:
357  *
358  *	- Each node in the trie is an union, so it can work both as
359  *	a normal node, or as a leaf.
360  *
361  *	- Each normal node points to 16 children (one for each possible
362  *	character in the oid). This is *not* stored in an array of
363  *	pointers, because in a 64-bit arch this would be sucking
364  *	16*sizeof(void*) = 128 bytes of memory per node, which is
365  *	insane. What we do is store Node Indexes, and use these indexes
366  *	to look up each node in the om->index array. These indexes are
367  *	signed shorts, so this limits the amount of unique OIDs that
368  *	fit in the structure to about 20000 (assuming a more or less uniform
369  *	distribution).
370  *
371  *	- All the nodes in om->index array are stored contiguously in
372  *	memory, and each of them is 32 bytes, so we fit 2x nodes per
373  *	cache line. Convenient for speed.
374  *
375  *	- To differentiate the leafs from the normal nodes, we store all
376  *	the indexes towards a leaf as a negative index (indexes to normal
377  *	nodes are positives). When we find that one of the children for
378  *	a node has a negative value, that means it's going to be a leaf.
379  *	This reduces the amount of indexes we have by two, but also reduces
380  *	the size of each node by 1-4 bytes (the amount we would need to
381  *	add a `is_leaf` field): this is good because it allows the nodes
382  *	to fit cleanly in cache lines.
383  *
384  *	- Once we reach an empty children, instead of continuing to insert
385  *	new nodes for each remaining character of the OID, we store a pointer
386  *	to the tail in the leaf; if the leaf is reached again, we turn it
387  *	into a normal node and use the tail to create a new leaf.
388  *
389  *	This is a pretty good balance between performance and memory usage.
390  */
git_oid_shorten_add(git_oid_shorten * os,const char * text_oid)391 int git_oid_shorten_add(git_oid_shorten *os, const char *text_oid)
392 {
393 	int i;
394 	bool is_leaf;
395 	node_index idx;
396 
397 	if (os->full) {
398 		git_error_set(GIT_ERROR_INVALID, "unable to shorten OID - OID set full");
399 		return -1;
400 	}
401 
402 	if (text_oid == NULL)
403 		return os->min_length;
404 
405 	idx = 0;
406 	is_leaf = false;
407 
408 	for (i = 0; i < GIT_OID_HEXSZ; ++i) {
409 		int c = git__fromhex(text_oid[i]);
410 		trie_node *node;
411 
412 		if (c == -1) {
413 			git_error_set(GIT_ERROR_INVALID, "unable to shorten OID - invalid hex value");
414 			return -1;
415 		}
416 
417 		node = &os->nodes[idx];
418 
419 		if (is_leaf) {
420 			const char *tail;
421 
422 			tail = node->tail;
423 			node->tail = NULL;
424 
425 			node = push_leaf(os, idx, git__fromhex(tail[0]), &tail[1]);
426 			if (node == NULL) {
427 				if (os->full)
428 					git_error_set(GIT_ERROR_INVALID, "unable to shorten OID - OID set full");
429 				return -1;
430 			}
431 		}
432 
433 		if (node->children[c] == 0) {
434 			if (push_leaf(os, idx, c, &text_oid[i + 1]) == NULL) {
435 				if (os->full)
436 					git_error_set(GIT_ERROR_INVALID, "unable to shorten OID - OID set full");
437 				return -1;
438 			}
439 			break;
440 		}
441 
442 		idx = node->children[c];
443 		is_leaf = false;
444 
445 		if (idx < 0) {
446 			node->children[c] = idx = -idx;
447 			is_leaf = true;
448 		}
449 	}
450 
451 	if (++i > os->min_length)
452 		os->min_length = i;
453 
454 	return os->min_length;
455 }
456 
457