Skip to content

Commit a59bee8

Browse files
zhengyu123jbachorik
authored andcommitted
Misused posix_memalign results in memory leak and returning wrong lib index (#296)
(cherry picked from commit dcfc396)
1 parent 1c432ee commit a59bee8

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed

ddprof-lib/src/main/cpp/codeCache.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@
66
#include "codeCache.h"
77
#include "dwarf_dd.h"
88
#include "os_dd.h"
9+
910
#include <stdint.h>
1011
#include <stdlib.h>
1112
#include <string.h>
1213
#include <sys/mman.h>
1314

1415
char *NativeFunc::create(const char *name, short lib_index) {
15-
NativeFunc *f = (NativeFunc *)malloc(sizeof(NativeFunc) + 1 + strlen(name));
16+
size_t size = align_up(sizeof(NativeFunc) + 1 + strlen(name), sizeof(NativeFunc*));
17+
NativeFunc *f = (NativeFunc *)aligned_alloc(sizeof(NativeFunc*), size);
1618
f->_lib_index = lib_index;
1719
f->_mark = 0;
1820
// cppcheck-suppress memleak

ddprof-lib/src/main/cpp/codeCache.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
#ifndef _CODECACHE_H
77
#define _CODECACHE_H
88

9+
#include "utils.h"
10+
911
#include <jvmti.h>
1012
#include <stdlib.h>
1113
#include <string.h>
@@ -62,7 +64,7 @@ class NativeFunc {
6264

6365
static short libIndex(const char *name) {
6466
NativeFunc* func = from(name);
65-
if (posix_memalign((void**)(&func), sizeof(NativeFunc*), sizeof(NativeFunc)) != 0) {
67+
if (!is_aligned(func, sizeof(func))) {
6668
return -1;
6769
}
6870
return func->_lib_index;

ddprof-lib/src/main/cpp/utils.h

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#ifndef _UTILS_H
2+
#define _UTILS_H
3+
4+
#include <cassert>
5+
#include <cstdint>
6+
#include <cstddef>
7+
8+
inline bool is_power_of_2(size_t size) {
9+
return size > 0 && (size & (size - 1)) == 0;
10+
}
11+
12+
template <typename T>
13+
inline bool is_aligned(const T* ptr, size_t alignment) noexcept {
14+
assert(is_power_of_2(alignment));
15+
// Convert the pointer to an integer type
16+
auto iptr = reinterpret_cast<uintptr_t>(ptr);
17+
18+
// Check if the integer value is a multiple of the alignment
19+
return (iptr & ~(alignment - 1) == 0);
20+
}
21+
22+
inline size_t align_down(size_t size, size_t alignment) noexcept {
23+
assert(is_power_of_2(alignment));
24+
return size & ~(alignment - 1);
25+
}
26+
27+
inline size_t align_up(size_t size, size_t alignment) noexcept {
28+
assert(is_power_of_2(alignment));
29+
return align_down(size + alignment - 1, alignment);
30+
}
31+
32+
33+
34+
35+
#endif // _UTILS_H

0 commit comments

Comments
 (0)