From 558726a9f13d7c3423a683dd2f4323589b66c310 Mon Sep 17 00:00:00 2001 From: Fatbag Date: Wed, 23 Jan 2013 21:13:25 -0600 Subject: [PATCH] Corrected the memory exhaustion trap behavior used when calling realloc Two more steps are currently required to complete hitutils: write hitld, with support for multiple objects and even .a archives, and implement scan_branch_destinations in hitdump. Then we can seamless modify The Sims 1's HIT routines. --- Tools/hitutils/hitasm.c | 5 +++-- Tools/hitutils/hitdump.c | 11 ++++++----- Tools/rtti-reader/rtti-reader.cpp | 7 +++++-- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Tools/hitutils/hitasm.c b/Tools/hitutils/hitasm.c index b79b5c5..6111597 100644 --- a/Tools/hitutils/hitasm.c +++ b/Tools/hitutils/hitasm.c @@ -58,9 +58,10 @@ typedef struct { } ByteWriterContext; static void bw_expand(ByteWriterContext *bwc){ - bwc->Data = realloc(bwc->Data, (bwc->Size <<= 1)); - if(!bwc->Data) + void * ptr; + if(bwc->Size > SIZE_MAX/2 || !(ptr = realloc(bwc->Data, bwc->Size<<=1))) Shutdown_M("%sCould not allocate memory for %s section.\n", "hitasm: Error: ", bwc->Name); + bwc->Data = ptr; } static void bw_write32(ByteWriterContext *bwc, uint32_t value){ diff --git a/Tools/hitutils/hitdump.c b/Tools/hitutils/hitdump.c index 4c5423b..185f5f3 100644 --- a/Tools/hitutils/hitdump.c +++ b/Tools/hitutils/hitdump.c @@ -88,16 +88,17 @@ typedef struct { } address_t; typedef struct { - size_t Size; + size_t SizeAllocated; size_t Count; address_t * Entries; } addresslist_t; static address_t * add_address(addresslist_t * List){ - if(List->Count == List->Size){ - List->Entries = realloc(List->Entries, (List->Size <<= 1) * sizeof(address_t)); - if(!List->Entries) + if(List->Count*sizeof(address_t) == List->SizeAllocated){ + void * ptr; + if(List->SizeAllocated > SIZE_MAX/2 || !(ptr = realloc(List->Entries, (List->SizeAllocated <<= 1)))) Shutdown_M("%sCould not allocate memory for address list.\n", "hitdump: Error: "); + List->Entries = ptr; } return memset(List->Entries + List->Count++, 0, sizeof(address_t)); } @@ -453,7 +454,7 @@ int main(int argc, char *argv[]){ ** Build up the address list */ - AddressList.Size = 32; + AddressList.SizeAllocated = 32 * sizeof(address_t); AddressList.Count = 0; AddressList.Entries = malloc(32 * sizeof(address_t)); diff --git a/Tools/rtti-reader/rtti-reader.cpp b/Tools/rtti-reader/rtti-reader.cpp index b314425..33cb0c6 100644 --- a/Tools/rtti-reader/rtti-reader.cpp +++ b/Tools/rtti-reader/rtti-reader.cpp @@ -82,9 +82,12 @@ struct RTTIVector { Shutdown_M("Failed to allocate memory"); } T& add(){ - if((Count+1)*sizeof(T) > SizeAllocated) - if(SizeAllocated > SIZE_MAX/2 || !(Buffer = (T*) realloc(Buffer, SizeAllocated<<=1))) + if((Count+1)*sizeof(T) > SizeAllocated){ + void * ptr; + if(SizeAllocated > SIZE_MAX/2 || !(ptr = (T*) realloc(Buffer, SizeAllocated<<=1))) Shutdown_M("Failed to allocate memory"); + Buffer = (T *) ptr; + } return Buffer[Count++]; }