From: Chandler Carruth Date: Tue, 4 Aug 2015 03:52:56 +0000 (+0000) Subject: [UB] Fix the two ways that we would try to memcpy from a null buffer in X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=9bf4b5f6264515fde32523af77dbea5557b1ec7a;p=clang [UB] Fix the two ways that we would try to memcpy from a null buffer in the nested name specifier code. First, skip the entire thing when the input is empty. Next, handle the case where we started off with a null buffer and a zero capacity to skip copying and freeing. This was found with UBSan. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@243946 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/AST/NestedNameSpecifier.cpp b/lib/AST/NestedNameSpecifier.cpp index 50a00502ca..97425d001d 100644 --- a/lib/AST/NestedNameSpecifier.cpp +++ b/lib/AST/NestedNameSpecifier.cpp @@ -435,17 +435,19 @@ TypeLoc NestedNameSpecifierLoc::getTypeLoc() const { namespace { void Append(char *Start, char *End, char *&Buffer, unsigned &BufferSize, unsigned &BufferCapacity) { + if (Start == End) + return; + if (BufferSize + (End - Start) > BufferCapacity) { // Reallocate the buffer. - unsigned NewCapacity - = std::max((unsigned)(BufferCapacity? BufferCapacity * 2 - : sizeof(void*) * 2), - (unsigned)(BufferSize + (End - Start))); + unsigned NewCapacity = std::max( + (unsigned)(BufferCapacity ? BufferCapacity * 2 : sizeof(void *) * 2), + (unsigned)(BufferSize + (End - Start))); char *NewBuffer = static_cast(malloc(NewCapacity)); - memcpy(NewBuffer, Buffer, BufferSize); - - if (BufferCapacity) + if (BufferCapacity) { + memcpy(NewBuffer, Buffer, BufferSize); free(Buffer); + } Buffer = NewBuffer; BufferCapacity = NewCapacity; }