Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7ff7ca6

Browse files
vmgcarlosmn
authored andcommitted
pool: Never return unaligned buffers
1 parent 75a0ccf commit 7ff7ca6

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

src/pool.c

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ struct git_pool_page {
88
git_pool_page *next;
99
uint32_t size;
1010
uint32_t avail;
11-
char data[GIT_FLEX_ARRAY];
11+
GIT_ALIGN(char data[GIT_FLEX_ARRAY], 8);
1212
};
1313

1414
static void *pool_alloc_page(git_pool *pool, uint32_t size);
@@ -30,11 +30,8 @@ uint32_t git_pool__system_page_size(void)
3030

3131
void git_pool_init(git_pool *pool, uint32_t item_size)
3232
{
33-
const uint32_t align_size = sizeof(void *) - 1;
3433
assert(pool);
35-
36-
if (item_size > 1)
37-
item_size = (item_size + align_size) & ~align_size;
34+
assert(item_size >= 1);
3835

3936
memset(pool, 0, sizeof(git_pool));
4037
pool->item_size = item_size;
@@ -98,15 +95,26 @@ static void *pool_alloc(git_pool *pool, uint32_t size)
9895
return ptr;
9996
}
10097

98+
static uint32_t alloc_size(git_pool *pool, uint32_t count)
99+
{
100+
const uint32_t align = sizeof(void *) - 1;
101+
102+
if (pool->item_size > 1) {
103+
const uint32_t item_size = (pool->item_size + align) & ~align;
104+
return item_size * count;
105+
}
106+
107+
return (count + align) & ~align;
108+
}
109+
101110
void *git_pool_malloc(git_pool *pool, uint32_t items)
102111
{
103-
const uint32_t size = items * pool->item_size;
104-
return pool_alloc(pool, size);
112+
return pool_alloc(pool, alloc_size(pool, items));
105113
}
106114

107115
void *git_pool_mallocz(git_pool *pool, uint32_t items)
108116
{
109-
const uint32_t size = items * pool->item_size;
117+
const uint32_t size = alloc_size(pool, items);
110118
void *ptr = pool_alloc(pool, size);
111119
if (ptr)
112120
memset(ptr, 0x0, size);

tests/core/pool.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ void test_core_pool__1(void)
3232
cl_assert(git_pool_malloc(&p, i) != NULL);
3333

3434
/* with fixed page size, allocation must end up with these values */
35-
cl_assert_equal_i(590, git_pool__open_pages(&p));
35+
cl_assert_equal_i(591, git_pool__open_pages(&p));
3636
git_pool_clear(&p);
3737

3838
git_pool_init(&p, 1);
@@ -42,7 +42,7 @@ void test_core_pool__1(void)
4242
cl_assert(git_pool_malloc(&p, i) != NULL);
4343

4444
/* with fixed page size, allocation must end up with these values */
45-
cl_assert_equal_i(573, git_pool__open_pages(&p));
45+
cl_assert_equal_i(sizeof(void *) == 8 ? 575 : 573, git_pool__open_pages(&p));
4646
git_pool_clear(&p);
4747
}
4848

0 commit comments

Comments
 (0)