From 95ae3520c5c9f76a435f63cc2d5e18d7ba0ba171 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Mon, 30 Nov 2015 17:32:18 +0100 Subject: 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. --- src/tree.c | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/src/tree.c b/src/tree.c index d269a5333..0a32868cd 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; -- cgit v1.2.1