r325661 - Clean up use of C allocation functions

Serge Pavlov via cfe-commits cfe-commits at lists.llvm.org
Tue Feb 20 18:02:39 PST 2018


Author: sepavloff
Date: Tue Feb 20 18:02:39 2018
New Revision: 325661

URL: http://llvm.org/viewvc/llvm-project?rev=325661&view=rev
Log:
Clean up use of C allocation functions

If the value returned by `malloc`, `calloc` or `realloc` is not checked
for null pointer, this change replaces them for `safe_malloc`,
`safe_calloc` or `safe_realloc`, which are defined in the namespace `llvm`.
These function report fatal error on out of memory.

In the plain C files, assertion statements are added to ensure that memory
is successfully allocated.

The aim of this change is to get better diagnostics of OOM on Windows.

Differential Revision: https://reviews.llvm.org/D43017

Modified:
    cfe/trunk/include/clang/Sema/ParsedTemplate.h
    cfe/trunk/lib/AST/NestedNameSpecifier.cpp
    cfe/trunk/lib/Frontend/CacheTokens.cpp
    cfe/trunk/lib/Frontend/Rewrite/HTMLPrint.cpp
    cfe/trunk/lib/Lex/MacroArgs.cpp
    cfe/trunk/tools/c-index-test/c-index-test.c
    cfe/trunk/tools/libclang/BuildSystem.cpp
    cfe/trunk/tools/libclang/CIndex.cpp
    cfe/trunk/tools/libclang/CXString.cpp

Modified: cfe/trunk/include/clang/Sema/ParsedTemplate.h
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/ParsedTemplate.h?rev=325661&r1=325660&r2=325661&view=diff
==============================================================================
--- cfe/trunk/include/clang/Sema/ParsedTemplate.h (original)
+++ cfe/trunk/include/clang/Sema/ParsedTemplate.h Tue Feb 20 18:02:39 2018
@@ -199,8 +199,7 @@ namespace clang {
            SourceLocation LAngleLoc, SourceLocation RAngleLoc,
            ArrayRef<ParsedTemplateArgument> TemplateArgs,
            SmallVectorImpl<TemplateIdAnnotation *> &CleanupList) {
-
-      TemplateIdAnnotation *TemplateId = new (std::malloc(
+      TemplateIdAnnotation *TemplateId = new (llvm::safe_malloc(
           totalSizeToAlloc<ParsedTemplateArgument>(TemplateArgs.size())))
           TemplateIdAnnotation(SS, TemplateKWLoc, TemplateNameLoc, Name,
                                OperatorKind, OpaqueTemplateName, TemplateKind,

Modified: cfe/trunk/lib/AST/NestedNameSpecifier.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/NestedNameSpecifier.cpp?rev=325661&r1=325660&r2=325661&view=diff
==============================================================================
--- cfe/trunk/lib/AST/NestedNameSpecifier.cpp (original)
+++ cfe/trunk/lib/AST/NestedNameSpecifier.cpp Tue Feb 20 18:02:39 2018
@@ -466,7 +466,7 @@ static void Append(char *Start, char *En
     unsigned NewCapacity = std::max(
         (unsigned)(BufferCapacity ? BufferCapacity * 2 : sizeof(void *) * 2),
         (unsigned)(BufferSize + (End - Start)));
-    char *NewBuffer = static_cast<char *>(malloc(NewCapacity));
+    char *NewBuffer = static_cast<char *>(llvm::safe_malloc(NewCapacity));
     if (BufferCapacity) {
       memcpy(NewBuffer, Buffer, BufferSize);
       free(Buffer);

Modified: cfe/trunk/lib/Frontend/CacheTokens.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CacheTokens.cpp?rev=325661&r1=325660&r2=325661&view=diff
==============================================================================
--- cfe/trunk/lib/Frontend/CacheTokens.cpp (original)
+++ cfe/trunk/lib/Frontend/CacheTokens.cpp Tue Feb 20 18:02:39 2018
@@ -662,7 +662,8 @@ std::pair<Offset,Offset> PTHWriter::Emit
   //  (2) a map from (IdentifierInfo*, Offset)* -> persistent IDs
 
   // Note that we use 'calloc', so all the bytes are 0.
-  PTHIdKey *IIDMap = (PTHIdKey*)calloc(idcount, sizeof(PTHIdKey));
+  PTHIdKey *IIDMap = static_cast<PTHIdKey*>(
+      llvm::safe_calloc(idcount, sizeof(PTHIdKey)));
 
   // Create the hashtable.
   llvm::OnDiskChainedHashTableGenerator<PTHIdentifierTableTrait> IIOffMap;

Modified: cfe/trunk/lib/Frontend/Rewrite/HTMLPrint.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/Rewrite/HTMLPrint.cpp?rev=325661&r1=325660&r2=325661&view=diff
==============================================================================
--- cfe/trunk/lib/Frontend/Rewrite/HTMLPrint.cpp (original)
+++ cfe/trunk/lib/Frontend/Rewrite/HTMLPrint.cpp Tue Feb 20 18:02:39 2018
@@ -86,8 +86,7 @@ void HTMLPrinter::HandleTranslationUnit(
 
   // Emit the HTML.
   const RewriteBuffer &RewriteBuf = R.getEditBuffer(FID);
-  char *Buffer = (char*)malloc(RewriteBuf.size());
-  std::copy(RewriteBuf.begin(), RewriteBuf.end(), Buffer);
-  Out->write(Buffer, RewriteBuf.size());
-  free(Buffer);
+  std::unique_ptr<char[]> Buffer(new char[RewriteBuf.size()]);
+  std::copy(RewriteBuf.begin(), RewriteBuf.end(), Buffer.get());
+  Out->write(Buffer.get(), RewriteBuf.size());
 }

Modified: cfe/trunk/lib/Lex/MacroArgs.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/MacroArgs.cpp?rev=325661&r1=325660&r2=325661&view=diff
==============================================================================
--- cfe/trunk/lib/Lex/MacroArgs.cpp (original)
+++ cfe/trunk/lib/Lex/MacroArgs.cpp Tue Feb 20 18:02:39 2018
@@ -49,7 +49,8 @@ MacroArgs *MacroArgs::create(const Macro
   if (!ResultEnt) {
     // Allocate memory for a MacroArgs object with the lexer tokens at the end,
     // and construct the MacroArgs object.
-    Result = new (std::malloc(totalSizeToAlloc<Token>(UnexpArgTokens.size())))
+    Result = new (
+        llvm::safe_malloc(totalSizeToAlloc<Token>(UnexpArgTokens.size())))
         MacroArgs(UnexpArgTokens.size(), VarargsElided, MI->getNumParams());
   } else {
     Result = *ResultEnt;

Modified: cfe/trunk/tools/c-index-test/c-index-test.c
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/c-index-test/c-index-test.c?rev=325661&r1=325660&r2=325661&view=diff
==============================================================================
--- cfe/trunk/tools/c-index-test/c-index-test.c (original)
+++ cfe/trunk/tools/c-index-test/c-index-test.c Tue Feb 20 18:02:39 2018
@@ -232,6 +232,7 @@ static int parse_remapped_files_with_opt
   *unsaved_files
     = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
                                      *num_unsaved_files);
+  assert(*unsaved_files);
   for (i = 0; i != *num_unsaved_files; ++i) {
     struct CXUnsavedFile *unsaved = *unsaved_files + i;
     const char *arg_string = argv[arg_indices[i]] + prefix_len;
@@ -267,6 +268,7 @@ static int parse_remapped_files_with_opt
 
     /* Read the contents of the file we're remapping to. */
     contents = (char *)malloc(unsaved->Length + 1);
+    assert(contents);
     if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
       fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
               (feof(to_file) ? "EOF" : "error"), sep + 1);
@@ -286,6 +288,7 @@ static int parse_remapped_files_with_opt
     /* Copy the file name that we're remapping from. */
     filename_len = sep - arg_string;
     filename = (char *)malloc(filename_len + 1);
+    assert(filename);
     memcpy(filename, arg_string, filename_len);
     filename[filename_len] = 0;
     unsaved->Filename = filename;
@@ -340,6 +343,7 @@ static int parse_remapped_files_with_try
     = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
                                       sizeof(struct CXUnsavedFile) *
                                         *num_unsaved_files);
+  assert(*unsaved_files);
   memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
          unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
             num_unsaved_files_try_idx);
@@ -2169,6 +2173,7 @@ int parse_file_line_column(const char *i
 
   /* Copy the file name. */
   *filename = (char*)malloc(last_colon - input + 1);
+  assert(*filename);
   memcpy(*filename, input, last_colon - input);
   (*filename)[last_colon - input] = 0;
   return 0;
@@ -2578,6 +2583,7 @@ static int inspect_cursor_at(int argc, c
   assert(NumLocations > 0 && "Unable to count locations?");
   Locations = (CursorSourceLocation *)malloc(
                                   NumLocations * sizeof(CursorSourceLocation));
+  assert(Locations);
   for (Loc = 0; Loc < NumLocations; ++Loc) {
     const char *input = argv[Loc + 1] + strlen(locations_flag);
     if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
@@ -2871,6 +2877,7 @@ static int find_file_refs_at(int argc, c
   assert(NumLocations > 0 && "Unable to count locations?");
   Locations = (CursorSourceLocation *)malloc(
                                   NumLocations * sizeof(CursorSourceLocation));
+  assert(Locations);
   for (Loc = 0; Loc < NumLocations; ++Loc) {
     const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
     if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
@@ -2978,6 +2985,7 @@ static int find_file_includes_in(int arg
   /* Parse the locations. */
   assert(NumFilenames > 0 && "Unable to count filenames?");
   Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
+  assert(Filenames);
   for (I = 0; I < NumFilenames; ++I) {
     const char *input = argv[I + 1] + strlen("-file-includes-in=");
     /* Copy the file name. */
@@ -3061,7 +3069,9 @@ typedef struct {
 static ImportedASTFilesData *importedASTs_create() {
   ImportedASTFilesData *p;
   p = malloc(sizeof(ImportedASTFilesData));
+  assert(p);
   p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
+  assert(p->filenames);
   p->num_files = 0;
   return p;
 }
@@ -3194,6 +3204,7 @@ static CXIdxClientContainer makeClientCo
   node =
       (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
                                     digitCount(line) + digitCount(column) + 2);
+  assert(node);
   newStr = node->data;
   sprintf(newStr, "%s:%d:%d", name, line, column);
 
@@ -3795,6 +3806,7 @@ static int index_compile_db(int argc, co
 
     len = strlen(database);
     tmp = (char *) malloc(len+1);
+    assert(tmp);
     memcpy(tmp, database, len+1);
     buildDir = dirname(tmp);
 
@@ -3976,6 +3988,7 @@ int perform_token_annotation(int argc, c
   }
 
   cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
+  assert(cursors);
   clang_annotateTokens(TU, tokens, num_tokens, cursors);
 
   if (checkForErrors(TU) != 0) {
@@ -4050,6 +4063,7 @@ perform_test_compilation_db(const char *
 
   len = strlen(database);
   tmp = (char *) malloc(len+1);
+  assert(tmp);
   memcpy(tmp, database, len+1);
   buildDir = dirname(tmp);
 

Modified: cfe/trunk/tools/libclang/BuildSystem.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/BuildSystem.cpp?rev=325661&r1=325660&r2=325661&view=diff
==============================================================================
--- cfe/trunk/tools/libclang/BuildSystem.cpp (original)
+++ cfe/trunk/tools/libclang/BuildSystem.cpp Tue Feb 20 18:02:39 2018
@@ -17,6 +17,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/CBindingWrapping.h"
 #include "llvm/Support/Chrono.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -78,7 +79,7 @@ clang_VirtualFileOverlay_writeToBuffer(C
   unwrap(VFO)->write(OS);
 
   StringRef Data = OS.str();
-  *out_buffer_ptr = (char*)malloc(Data.size());
+  *out_buffer_ptr = static_cast<char*>(llvm::safe_malloc(Data.size()));
   *out_buffer_size = Data.size();
   memcpy(*out_buffer_ptr, Data.data(), Data.size());
   return CXError_Success;
@@ -140,7 +141,7 @@ clang_ModuleMapDescriptor_writeToBuffer(
   OS << "}\n";
 
   StringRef Data = OS.str();
-  *out_buffer_ptr = (char*)malloc(Data.size());
+  *out_buffer_ptr = static_cast<char*>(llvm::safe_malloc(Data.size()));
   *out_buffer_size = Data.size();
   memcpy(*out_buffer_ptr, Data.data(), Data.size());
   return CXError_Success;

Modified: cfe/trunk/tools/libclang/CIndex.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CIndex.cpp?rev=325661&r1=325660&r2=325661&view=diff
==============================================================================
--- cfe/trunk/tools/libclang/CIndex.cpp (original)
+++ cfe/trunk/tools/libclang/CIndex.cpp Tue Feb 20 18:02:39 2018
@@ -6666,7 +6666,8 @@ void clang_tokenize(CXTranslationUnit TU
   if (CXTokens.empty())
     return;
 
-  *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
+  *Tokens = static_cast<CXToken *>(
+      llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
   memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
   *NumTokens = CXTokens.size();
 }

Modified: cfe/trunk/tools/libclang/CXString.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CXString.cpp?rev=325661&r1=325660&r2=325661&view=diff
==============================================================================
--- cfe/trunk/tools/libclang/CXString.cpp (original)
+++ cfe/trunk/tools/libclang/CXString.cpp Tue Feb 20 18:02:39 2018
@@ -96,7 +96,7 @@ CXString createRef(StringRef String) {
 
 CXString createDup(StringRef String) {
   CXString Result;
-  char *Spelling = static_cast<char *>(malloc(String.size() + 1));
+  char *Spelling = static_cast<char *>(llvm::safe_malloc(String.size() + 1));
   memmove(Spelling, String.data(), String.size());
   Spelling[String.size()] = 0;
   Result.data = Spelling;




More information about the cfe-commits mailing list