diff --git a/ddprof-lib/src/main/cpp/codeCache.cpp b/ddprof-lib/src/main/cpp/codeCache.cpp index 5fb17d964..14796d701 100644 --- a/ddprof-lib/src/main/cpp/codeCache.cpp +++ b/ddprof-lib/src/main/cpp/codeCache.cpp @@ -6,13 +6,15 @@ #include "codeCache.h" #include "dwarf_dd.h" #include "os_dd.h" + #include #include #include #include char *NativeFunc::create(const char *name, short lib_index) { - NativeFunc *f = (NativeFunc *)malloc(sizeof(NativeFunc) + 1 + strlen(name)); + size_t size = align_up(sizeof(NativeFunc) + 1 + strlen(name), sizeof(NativeFunc*)); + NativeFunc *f = (NativeFunc *)aligned_alloc(sizeof(NativeFunc*), size); f->_lib_index = lib_index; f->_mark = 0; // cppcheck-suppress memleak diff --git a/ddprof-lib/src/main/cpp/codeCache.h b/ddprof-lib/src/main/cpp/codeCache.h index 233da56c1..3398ad029 100644 --- a/ddprof-lib/src/main/cpp/codeCache.h +++ b/ddprof-lib/src/main/cpp/codeCache.h @@ -6,6 +6,8 @@ #ifndef _CODECACHE_H #define _CODECACHE_H +#include "utils.h" + #include #include #include @@ -62,7 +64,7 @@ class NativeFunc { static short libIndex(const char *name) { NativeFunc* func = from(name); - if (posix_memalign((void**)(&func), sizeof(NativeFunc*), sizeof(NativeFunc)) != 0) { + if (!is_aligned(func, sizeof(func))) { return -1; } return func->_lib_index; diff --git a/ddprof-lib/src/main/cpp/utils.h b/ddprof-lib/src/main/cpp/utils.h new file mode 100644 index 000000000..47d58eb96 --- /dev/null +++ b/ddprof-lib/src/main/cpp/utils.h @@ -0,0 +1,35 @@ +#ifndef _UTILS_H +#define _UTILS_H + +#include +#include +#include + +inline bool is_power_of_2(size_t size) { + return size > 0 && (size & (size - 1)) == 0; +} + +template +inline bool is_aligned(const T* ptr, size_t alignment) noexcept { + assert(is_power_of_2(alignment)); + // Convert the pointer to an integer type + auto iptr = reinterpret_cast(ptr); + + // Check if the integer value is a multiple of the alignment + return (iptr & ~(alignment - 1) == 0); +} + +inline size_t align_down(size_t size, size_t alignment) noexcept { + assert(is_power_of_2(alignment)); + return size & ~(alignment - 1); +} + +inline size_t align_up(size_t size, size_t alignment) noexcept { + assert(is_power_of_2(alignment)); + return align_down(size + alignment - 1, alignment); +} + + + + +#endif // _UTILS_H \ No newline at end of file