[committed,69/88] gccrs: lex: Prevent directories in RAIIFile

Message ID 20230405140411.3016563-70-arthur.cohen@embecosm.com
State Accepted
Headers
Series [committed,01/88] gccrs: fatal_error_flag: Fix typo in error message |

Checks

Context Check Description
snail/gcc-patch-check success Github commit url

Commit Message

Arthur Cohen April 5, 2023, 2:03 p.m. UTC
  From: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>

RAIIFile constructor was accepting directory filename. This lead to
unattended directory opening in some part of the code (load_file_bytes)
wich resulted in ice. Since RAIIFile are used for the lexer, removing
the ability to open directories with RAIIFile fixes those issues and
prevent future mistakes.

gcc/rust/ChangeLog:

	* lex/rust-lex.h: Add file type check.

Signed-off-by: Pierre-Emmanuel Patry <pierre-emmanuel.patry@embecosm.com>
---
 gcc/rust/lex/rust-lex.h | 28 ++++++++++++++++++++++++++--
 1 file changed, 26 insertions(+), 2 deletions(-)
  

Patch

diff --git a/gcc/rust/lex/rust-lex.h b/gcc/rust/lex/rust-lex.h
index 2dd60b365ef..50424713df9 100644
--- a/gcc/rust/lex/rust-lex.h
+++ b/gcc/rust/lex/rust-lex.h
@@ -38,13 +38,37 @@  private:
       fclose (file);
   }
 
+  static bool allowed_filetype (const struct stat &statbuf)
+  {
+    // The file could be either
+    // - a regular file
+    // - a char device (/dev/null...)
+    return S_ISREG (statbuf.st_mode) || S_ISCHR (statbuf.st_mode);
+  }
+
 public:
   RAIIFile (const char *filename) : filename (filename)
   {
     if (strcmp (filename, "-") == 0)
-      file = stdin;
+      {
+	file = stdin;
+      }
     else
-      file = fopen (filename, "r");
+      {
+	struct stat statbuf;
+	if (!(file = fopen (filename, "r")))
+	  {
+	    return;
+	  }
+
+	if (-1 == fstat (fileno (file), &statbuf)
+	    || !allowed_filetype (statbuf))
+	  {
+	    fclose (file);
+	    file = nullptr;
+	    errno = EISDIR;
+	  }
+      }
   }
 
   /**