input.cc's file_cache was borrowing copies of the file name.
This could lead to use-after-free when writing out sarif output
from Fortran, which frees its filenames before the sarif output
is fully written out.

Fix by taking a copy in file_cache_slot.

Successfully bootstrapped & regrtested on x86_64-pc-linux-gnu.
Verified fix using valgrind before/after the patch.
Pushed to trunk as r15-7627-gee6619b1246b38.

gcc/ChangeLog:
        PR other/118919
        * input.cc (file_cache_slot::m_file_path): Make non-const.
        (file_cache_slot::evict): Free m_file_path.
        (file_cache_slot::create): Store a copy of file_path if non-null.
        (file_cache_slot::~file_cache_slot): Free m_file_path.

Signed-off-by: David Malcolm <dmalc...@redhat.com>
---
 gcc/input.cc | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/gcc/input.cc b/gcc/input.cc
index f0eacf59c8e2..44017589a3d1 100644
--- a/gcc/input.cc
+++ b/gcc/input.cc
@@ -134,10 +134,8 @@ public:
   unsigned m_use_count;
 
   /* The file_path is the key for identifying a particular file in
-     the cache.
-     For libcpp-using code, the underlying buffer for this field is
-     owned by the corresponding _cpp_file within the cpp_reader.  */
-  const char *m_file_path;
+     the cache.  This copy is owned by the slot.  */
+  char *m_file_path;
 
   FILE *m_fp;
 
@@ -395,6 +393,7 @@ file_cache::add_buffered_content (const char *file_path,
 void
 file_cache_slot::evict ()
 {
+  free (m_file_path);
   m_file_path = NULL;
   if (m_fp)
     fclose (m_fp);
@@ -492,7 +491,7 @@ file_cache_slot::create (const file_cache::input_context 
&in_context,
                         const char *file_path, FILE *fp,
                         unsigned highest_use_count)
 {
-  m_file_path = file_path;
+  m_file_path = file_path ? xstrdup (file_path) : nullptr;
   if (m_fp)
     fclose (m_fp);
   m_error = false;
@@ -623,6 +622,7 @@ file_cache_slot::file_cache_slot ()
 
 file_cache_slot::~file_cache_slot ()
 {
+  free (m_file_path);
   if (m_fp)
     {
       fclose (m_fp);
-- 
2.26.3

Reply via email to