Skip to content

Commit d72a841

Browse files
committed
Add utils_align_ptr_down_size_up()
Add utils_align_ptr_down_size_up() to align a pointer down and a size up (for mmap()/munmap()). Signed-off-by: Lukasz Dorau <[email protected]>
1 parent 28ff4a4 commit d72a841

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

src/utils/utils_common.c

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,37 @@ void utils_align_ptr_up_size_down(void **ptr, size_t *size, size_t alignment) {
1717
uintptr_t p = (uintptr_t)*ptr;
1818
size_t s = *size;
1919

20-
// align pointer to 'alignment' bytes and adjust the size
20+
// align the pointer up to 'alignment' bytes and adjust the size down
2121
size_t rest = p & (alignment - 1);
2222
if (rest) {
23-
p += alignment - rest;
23+
p = ALIGN_UP(p, alignment);
2424
s -= alignment - rest;
2525
}
2626

27-
ASSERT((p & (alignment - 1)) == 0);
28-
ASSERT((s & (alignment - 1)) == 0);
27+
ASSERT(IS_ALIGNED(p, alignment));
28+
ASSERT(IS_ALIGNED(s, alignment));
29+
30+
*ptr = (void *)p;
31+
*size = s;
32+
}
33+
34+
// align a pointer down and a size up (for mmap()/munmap())
35+
void utils_align_ptr_down_size_up(void **ptr, size_t *size, size_t alignment) {
36+
uintptr_t p = (uintptr_t)*ptr;
37+
size_t s = *size;
38+
39+
// align the pointer down to 'alignment' bytes and adjust the size up
40+
size_t rest = p & (alignment - 1);
41+
if (rest) {
42+
p = ALIGN_DOWN(p, alignment);
43+
s += rest;
44+
}
45+
46+
// align the size up to 'alignment' bytes
47+
s = ALIGN_UP(s, alignment);
48+
49+
ASSERT(IS_ALIGNED(p, alignment));
50+
ASSERT(IS_ALIGNED(s, alignment));
2951

3052
*ptr = (void *)p;
3153
*size = s;

src/utils/utils_common.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ size_t utils_get_page_size(void);
8585
// align a pointer up and a size down
8686
void utils_align_ptr_up_size_down(void **ptr, size_t *size, size_t alignment);
8787

88+
// align a pointer down and a size up (for mmap()/munmap())
89+
void utils_align_ptr_down_size_up(void **ptr, size_t *size, size_t alignment);
90+
8891
// get the current process ID
8992
int utils_getpid(void);
9093

0 commit comments

Comments
 (0)