tree: ensure the entry filename fits in 16 bits Return an error in case the length is too big. Also take this opportunity to have a single allocating function for the size and overflow logic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
diff --git a/src/tree.c b/src/tree.c
index d269a53..0a32868 100644
--- a/src/tree.c
+++ b/src/tree.c
@@ -82,47 +82,57 @@ int git_tree_entry_icmp(const git_tree_entry *e1, const git_tree_entry *e2)
}
/**
- * Allocate a tree entry, borrowing the filename from the tree which
- * owns it. This is useful when reading trees, so we don't allocate a
- * ton of small strings but can use the pool.
+ * Allocate either from the pool or from the system allocator
*/
-static git_tree_entry *alloc_entry_pooled(git_pool *pool, const char *filename, size_t filename_len)
+static git_tree_entry *alloc_entry_base(git_pool *pool, const char *filename, size_t filename_len)
{
git_tree_entry *entry = NULL;
size_t tree_len;
+ if (filename_len > UINT16_MAX) {
+ giterr_set(GITERR_INVALID, "tree entry is over UINT16_MAX in length");
+ return NULL;
+ }
+
if (GIT_ADD_SIZET_OVERFLOW(&tree_len, sizeof(git_tree_entry), filename_len) ||
- GIT_ADD_SIZET_OVERFLOW(&tree_len, tree_len, 1) ||
- !(entry = git_pool_malloc(pool, tree_len)))
+ GIT_ADD_SIZET_OVERFLOW(&tree_len, tree_len, 1))
+ return NULL;
+
+ entry = pool ? git_pool_malloc(pool, tree_len) :
+ git__malloc(tree_len);
+ if (!entry)
return NULL;
memset(entry, 0x0, sizeof(git_tree_entry));
memcpy(entry->filename, filename, filename_len);
entry->filename[filename_len] = 0;
entry->filename_len = filename_len;
- entry->pooled = true;
return entry;
}
-static git_tree_entry *alloc_entry(const char *filename)
+/**
+ * Allocate a tree entry, using the poolin the tree which owns
+ * it. This is useful when reading trees, so we don't allocate a ton
+ * of small strings but can use the pool.
+ */
+static git_tree_entry *alloc_entry_pooled(git_pool *pool, const char *filename, size_t filename_len)
{
git_tree_entry *entry = NULL;
- size_t filename_len = strlen(filename), tree_len;
- if (GIT_ADD_SIZET_OVERFLOW(&tree_len, sizeof(git_tree_entry), filename_len) ||
- GIT_ADD_SIZET_OVERFLOW(&tree_len, tree_len, 1) ||
- !(entry = git__malloc(tree_len)))
+ if (!(entry = alloc_entry_base(pool, filename, filename_len)))
return NULL;
- memset(entry, 0x0, sizeof(git_tree_entry));
- memcpy(entry->filename, filename, filename_len);
- entry->filename[filename_len] = 0;
- entry->filename_len = filename_len;
+ entry->pooled = true;
return entry;
}
+static git_tree_entry *alloc_entry(const char *filename)
+{
+ return alloc_entry_base(NULL, filename, strlen(filename));
+}
+
struct tree_key_search {
const char *filename;
uint16_t filename_len;