* @brief This function allocates a memory block, which address is aligned to the * specified alignment size. * * @param size is the allocated memory block size. * * @param align is the alignment size. * * @return The memory block address was returned successfully, otherwise it was * returned empty RT_NULL. */
| 1010 | * returned empty RT_NULL. |
| 1011 | */ |
| 1012 | rt_weak void *rt_malloc_align(rt_size_t size, rt_size_t align) |
| 1013 | { |
| 1014 | void *ptr = RT_NULL; |
| 1015 | void *align_ptr = RT_NULL; |
| 1016 | int uintptr_size = 0; |
| 1017 | rt_size_t align_size = 0; |
| 1018 | |
| 1019 | /* sizeof pointer */ |
| 1020 | uintptr_size = sizeof(void*); |
| 1021 | uintptr_size -= 1; |
| 1022 | |
| 1023 | /* align the alignment size to uintptr size byte */ |
| 1024 | align = ((align + uintptr_size) & ~uintptr_size); |
| 1025 | |
| 1026 | /* get total aligned size */ |
| 1027 | align_size = ((size + uintptr_size) & ~uintptr_size) + align; |
| 1028 | /* allocate memory block from heap */ |
| 1029 | ptr = rt_malloc(align_size); |
| 1030 | if (ptr != RT_NULL) |
| 1031 | { |
| 1032 | /* the allocated memory block is aligned */ |
| 1033 | if (((rt_uintptr_t)ptr & (align - 1)) == 0) |
| 1034 | { |
| 1035 | align_ptr = (void *)((rt_uintptr_t)ptr + align); |
| 1036 | } |
| 1037 | else |
| 1038 | { |
| 1039 | align_ptr = (void *)(((rt_uintptr_t)ptr + (align - 1)) & ~(align - 1)); |
| 1040 | } |
| 1041 | |
| 1042 | /* set the pointer before alignment pointer to the real pointer */ |
| 1043 | *((rt_uintptr_t *)((rt_uintptr_t)align_ptr - sizeof(void *))) = (rt_uintptr_t)ptr; |
| 1044 | |
| 1045 | ptr = align_ptr; |
| 1046 | } |
| 1047 | |
| 1048 | return ptr; |
| 1049 | } |
| 1050 | RTM_EXPORT(rt_malloc_align); |
| 1051 | |
| 1052 | /** |