Skip to content

Commit dca5194

Browse files
committed
[FTFD] Fix malloc/realloc/free wrappers
On x64 malloc needs to return a 16 byte aligned buffer, the previous code used an 8 byte header, making the allocations unaligned. This is now fixed with an improved header structure. Also simplify realloc a bit and make it handle Object == NULL.
1 parent 91fadeb commit dca5194

File tree

1 file changed

+30
-19
lines changed

1 file changed

+30
-19
lines changed

win32ss/drivers/font/ftfd/rosglue.c

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -36,43 +36,54 @@ DbgPrint(IN PCCH Format, IN ...)
3636
* buffer (need to copy the old contents to the new buffer). So, allocate
3737
* extra space for a size_t, store the allocated size in there and return
3838
* the address just past it as the allocated buffer.
39+
* On win64 we need to align the allocation to 16 bytes, otherwise 8 bytes.
3940
*/
41+
typedef struct _MALLOC_HEADER
42+
{
43+
SIZE_T Size;
44+
SIZE_T Alignment;
45+
} MALLOC_HEADER, * PMALLOC_HEADER;
4046

4147
void *
4248
malloc(size_t Size)
4349
{
44-
void *Object;
50+
PMALLOC_HEADER Header;
4551

46-
Object = EngAllocMem(0, sizeof(size_t) + Size, TAG_FREETYPE);
47-
if (Object != NULL)
52+
Header = EngAllocMem(0, sizeof(MALLOC_HEADER) + Size, TAG_FREETYPE);
53+
if (Header == NULL)
4854
{
49-
*((size_t *)Object) = Size;
50-
Object = (void *)((size_t *)Object + 1);
55+
return NULL;
5156
}
5257

53-
return Object;
58+
Header->Size = Size;
59+
Header->Alignment = -1;
60+
return (Header + 1);
5461
}
5562

5663
void *
5764
realloc(void *Object, size_t Size)
5865
{
59-
void *NewObject;
66+
PVOID NewObject;
67+
PMALLOC_HEADER OldHeader;
6068
size_t CopySize;
6169

62-
NewObject = EngAllocMem(0, sizeof(size_t) + Size, TAG_FREETYPE);
63-
if (NewObject != NULL)
70+
NewObject = malloc(Size);
71+
if (NewObject == NULL)
6472
{
65-
*((size_t *)NewObject) = Size;
66-
NewObject = (void *)((size_t *)NewObject + 1);
67-
CopySize = *((size_t *)Object - 1);
68-
if (Size < CopySize)
69-
{
70-
CopySize = Size;
71-
}
72-
memcpy(NewObject, Object, CopySize);
73-
EngFreeMem((size_t *)Object - 1);
73+
return NULL;
7474
}
7575

76+
if (Object == NULL)
77+
{
78+
return NewObject;
79+
}
80+
81+
OldHeader = (PMALLOC_HEADER)Object - 1;
82+
CopySize = min(OldHeader->Size, Size);
83+
memcpy(NewObject, Object, CopySize);
84+
85+
free(Object);
86+
7687
return NewObject;
7788
}
7889

@@ -81,7 +92,7 @@ free(void *Object)
8192
{
8293
if (Object != NULL)
8394
{
84-
EngFreeMem((size_t *)Object - 1);
95+
EngFreeMem((PMALLOC_HEADER)Object - 1);
8596
}
8697
}
8798

0 commit comments

Comments
 (0)