From 8075447fad46671743bff8c66c09e6083a50c62e Mon Sep 17 00:00:00 2001
From: Tom Almeida <tommoa256@gmail.com>
Date: Thu, 21 Jun 2018 00:16:20 +0800
Subject: [PATCH] Changed FILE to use a vector as a buffer instead of raw
 pointers. This allows us to remove the large majority of unsafe blocks from
 the code

---
 src/stdio/src/default.rs | 50 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 50 insertions(+)

diff --git a/src/stdio/src/default.rs b/src/stdio/src/default.rs
index 4adbe015..45adea80 100644
--- a/src/stdio/src/default.rs
+++ b/src/stdio/src/default.rs
@@ -39,6 +39,18 @@ lazy_static! {
     };
 }
 
+struct GlobalFile(UnsafeCell<FILE>);
+impl GlobalFile {
+    const fn new(file: FILE) -> Self {
+        GlobalFile(UnsafeCell::new(file))
+    }
+    fn get(&self) -> *mut FILE {
+        self.0.get()
+    }
+}
+// statics need to be Sync
+unsafe impl Sync for GlobalFile {}
+
 #[no_mangle]
 pub extern "C" fn __stdin() -> *mut FILE {
     unsafe { &mut default_stdin }
@@ -53,3 +65,41 @@ pub extern "C" fn __stdout() -> *mut FILE {
 pub extern "C" fn __stderr() -> *mut FILE {
     unsafe { &mut default_stderr }
 }
+
+lazy_static! {
+    #[allow(non_upper_case_globals)]
+    static ref default_stdin: GlobalFile = GlobalFile::new(FILE {
+        flags: constants::F_PERM | constants::F_NOWR,
+        read: None,
+        write: None,
+        fd: 0,
+        buf: vec![0u8;(BUFSIZ + UNGET) as usize],
+        buf_char: -1,
+        unget: UNGET,
+        lock: AtomicBool::new(false),
+    });
+
+    #[allow(non_upper_case_globals)]
+    static ref default_stdout: GlobalFile = GlobalFile::new(FILE {
+        flags: constants::F_PERM | constants::F_NORD,
+        read: None,
+        write: None,
+        fd: 1,
+        buf: vec![0u8;(BUFSIZ + UNGET) as usize],
+        buf_char: b'\n' as i8,
+        unget: 0,
+        lock: AtomicBool::new(false),
+    });
+
+    #[allow(non_upper_case_globals)]
+    static ref default_stderr: GlobalFile = GlobalFile::new(FILE {
+        flags: constants::F_PERM | constants::F_NORD,
+        read: None,
+        write: None,
+        fd: 2,
+        buf: vec![0u8;(BUFSIZ + UNGET) as usize],
+        buf_char: -1,
+        unget: 0,
+        lock: AtomicBool::new(false),
+    });
+}
-- 
GitLab