@@ -325,11 +325,12 @@ static int isMmapSafe(int Fd) {
325325COMPILER_RT_VISIBILITY void lprofGetFileContentBuffer (FILE * F , uint64_t Length ,
326326 ManagedMemory * Buf ) {
327327 Buf -> Status = MM_INVALID ;
328-
329- if (!F || isMmapSafe (fileno (F ))) {
330- Buf -> Addr = mmap (NULL , Length , PROT_READ , MAP_SHARED | MAP_FILE ,
331- F ? fileno (F ) : -1 , 0 );
332- if (Buf -> Addr != MAP_FAILED )
328+ if (isMmapSafe (fileno (F ))) {
329+ Buf -> Addr =
330+ mmap (NULL , Length , PROT_READ , MAP_SHARED | MAP_FILE , fileno (F ), 0 );
331+ if (Buf -> Addr == MAP_FAILED )
332+ PROF_ERR ("%s: mmap failed: %s\n" , __func__ , strerror (errno ))
333+ else
333334 Buf -> Status = MM_MMAP ;
334335 return ;
335336 }
@@ -338,20 +339,22 @@ COMPILER_RT_VISIBILITY void lprofGetFileContentBuffer(FILE *F, uint64_t Length,
338339 PROF_NOTE ("Could not use mmap; using fread instead.%s\n" , "" );
339340
340341 void * Buffer = malloc (Length );
341-
342342 if (!Buffer ) {
343343 PROF_ERR ("%s: malloc failed: %s\n" , __func__ , strerror (errno ));
344344 return ;
345345 }
346- if (fseek (F , 0L , SEEK_SET ) != 0 ) {
347- PROF_ERR ("%s: fseek(0, SEEK_SET) failed: %s\n" , __func__ , strerror (errno ));
346+ if (ftell (F ) != 0 ) {
347+ PROF_ERR ("%s: expecting ftell to return zero\n" , __func__ );
348+ free (Buffer );
348349 return ;
349350 }
350351
351352 // Read the entire file into memory.
352353 size_t BytesRead = fread (Buffer , 1 , Length , F );
353- if (BytesRead != (size_t )Length || ferror (F )) {
354- PROF_ERR ("%s: fread failed: %s\n" , __func__ , strerror (errno ));
354+ if (BytesRead != (size_t )Length ) {
355+ PROF_ERR ("%s: fread failed%s\n" , __func__ ,
356+ feof (F ) ? ", end of file reached" : "" );
357+ free (Buffer );
355358 return ;
356359 }
357360
@@ -372,6 +375,8 @@ void lprofReleaseBuffer(ManagedMemory *Buf, size_t Length) {
372375 PROF_ERR ("%s: Buffer has invalid state: %d" , __func__ , Buf -> Status );
373376 break ;
374377 }
378+ Buf -> Addr = NULL ;
379+ Buf -> Status = MM_INVALID ;
375380}
376381
377382COMPILER_RT_VISIBILITY const char * lprofGetPathPrefix (int * PrefixStrip ,
0 commit comments