From c20b3383b78473fdfb958ebfe15227bded79ba78 Mon Sep 17 00:00:00 2001 From: Matthias Braun Date: Thu, 20 Jul 2017 01:30:39 +0000 Subject: Support, IR, ADT: Check nullptr after allocation with malloc/realloc or calloc As a follow up of the bad alloc handler patch, this patch introduces nullptr checks on pointers returned from the malloc/realloc/calloc functions. In addition some memory size assignments are moved behind the allocation of the corresponding memory to fulfill exception safe memory management (RAII). patch by Klaus Kretzschmar Differential Revision: https://reviews.llvm.org/D35414 llvm-svn: 308576 --- llvm/lib/Support/StringMap.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) (limited to 'llvm/lib/Support/StringMap.cpp') diff --git a/llvm/lib/Support/StringMap.cpp b/llvm/lib/Support/StringMap.cpp index d2315966e32..4341da2d97b 100644 --- a/llvm/lib/Support/StringMap.cpp +++ b/llvm/lib/Support/StringMap.cpp @@ -52,14 +52,21 @@ StringMapImpl::StringMapImpl(unsigned InitSize, unsigned itemSize) { void StringMapImpl::init(unsigned InitSize) { assert((InitSize & (InitSize-1)) == 0 && "Init Size must be a power of 2 or zero!"); - NumBuckets = InitSize ? InitSize : 16; + + unsigned NewNumBuckets = InitSize ? InitSize : 16; NumItems = 0; NumTombstones = 0; - TheTable = (StringMapEntryBase **)calloc(NumBuckets+1, + TheTable = (StringMapEntryBase **)calloc(NewNumBuckets+1, sizeof(StringMapEntryBase **) + sizeof(unsigned)); + if (TheTable == nullptr) + report_bad_alloc_error("Allocation of StringMap table failed."); + + // Set the member only if TheTable was successfully allocated + NumBuckets = NewNumBuckets; + // Allocate one extra bucket, set it to look filled so the iterators stop at // end. TheTable[NumBuckets] = (StringMapEntryBase*)2; @@ -215,6 +222,10 @@ unsigned StringMapImpl::RehashTable(unsigned BucketNo) { StringMapEntryBase **NewTableArray = (StringMapEntryBase **)calloc(NewSize+1, sizeof(StringMapEntryBase *) + sizeof(unsigned)); + + if (NewTableArray == nullptr) + report_bad_alloc_error("Allocation of StringMap hash table failed."); + unsigned *NewHashArray = (unsigned *)(NewTableArray + NewSize + 1); NewTableArray[NewSize] = (StringMapEntryBase*)2; -- cgit v1.2.3