Merge pull request #615 from nealef/master
[mono.git] / mcs / class / corlib / System.IO / FileStream.cs
index 481f41d40e3345676291cd3bb007bd1190357c63..98416dfa82f875a06a564fa7251b9d484c3c80df 100644 (file)
@@ -9,6 +9,7 @@
 //
 // (C) 2001-2003 Ximian, Inc.  http://www.ximian.com
 // Copyright (C) 2004-2005, 2008, 2010 Novell, Inc (http://www.novell.com)
+// Copyright 2011 Xamarin Inc (http://www.xamarin.com).
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -38,14 +39,18 @@ using System.Runtime.Remoting.Messaging;
 using System.Security;
 using System.Security.Permissions;
 using System.Threading;
-
 using Microsoft.Win32.SafeHandles;
+
 #if NET_2_1
 using System.IO.IsolatedStorage;
 #else
 using System.Security.AccessControl;
 #endif
 
+#if NET_4_5
+using System.Threading.Tasks;
+#endif
+
 namespace System.IO
 {
        [ComVisible (true)]
@@ -95,21 +100,11 @@ namespace System.IO
                        }
 
                        this.handle = handle;
+                       ExposeHandle ();
                        this.access = access;
                        this.owner = ownsHandle;
                        this.async = isAsync;
-#if MOONLIGHT
-                       // default the browser to 'all' anonymous files and let other usage (like smcs) with 'normal'
-                       // (i.e. non-anonymous except for isolated storage) files and paths
-                       this.anonymous = SecurityManager.SecurityEnabled;
-#else
                        this.anonymous = false;
-#endif
-                       if (isZeroSize)
-                               bufferSize = 1;
-
-                       InitBuffer (bufferSize);
-
                        if (canseek) {
                                buf_start = MonoIO.Seek (handle, 0, SeekOrigin.Current, out error);
                                if (error != MonoIOError.ERROR_SUCCESS) {
@@ -144,16 +139,16 @@ namespace System.IO
                }
 
                public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
-                       : this (path, mode, access, share, bufferSize, useAsync, FileOptions.None)
+                       : this (path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None)
                {
                }
 
-#if !NET_2_1
                public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
                        : this (path, mode, access, share, bufferSize, false, options)
                {
                }
 
+#if !NET_2_1
                public FileStream (SafeFileHandle handle, FileAccess access)
                        :this(handle, access, DefaultBufferSize, false)
                {
@@ -206,6 +201,7 @@ namespace System.IO
                                throw new ArgumentException ("Path is empty");
                        }
 
+                       this.anonymous = anonymous;
                        // ignore the Inheritable flag
                        share &= ~FileShare.Inheritable;
 
@@ -222,20 +218,10 @@ namespace System.IO
                        }
 
                        if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
-#if NET_2_1
-                               if (anonymous)
-                                       throw new IsolatedStorageException ("Enum value for FileAccess was out of legal range.");
-                               else
-#endif
                                throw new ArgumentOutOfRangeException ("access", "Enum value was out of legal range.");
                        }
 
                        if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) {
-#if NET_2_1
-                               if (anonymous)
-                                       throw new IsolatedStorageException ("Enum value for FileShare was out of legal range.");
-                               else
-#endif
                                throw new ArgumentOutOfRangeException ("share", "Enum value was out of legal range.");
                        }
 
@@ -277,12 +263,7 @@ namespace System.IO
                                        // don't leak the path information for isolated storage
                                        string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
                                        string fname = (anonymous) ? dname : Path.GetFullPath (path);
-#if NET_2_1
-                                       // don't use GetSecureFileName for the directory name
-                                       throw new IsolatedStorageException (String.Format (msg, fname));
-#else
                                        throw new DirectoryNotFoundException (String.Format (msg, fname));
-#endif
                                }
                        }
 
@@ -291,11 +272,7 @@ namespace System.IO
                                // don't leak the path information for isolated storage
                                string msg = Locale.GetText ("Could not find file \"{0}\".");
                                string fname = GetSecureFileName (path);
-#if NET_2_1
-                               throw new IsolatedStorageException (String.Format (msg, fname));
-#else
                                throw new FileNotFoundException (String.Format (msg, fname), fname);
-#endif
                        }
 
                        // IsolatedStorage needs to keep the Name property to the default "[Unknown]"
@@ -314,7 +291,6 @@ namespace System.IO
 
                        this.access = access;
                        this.owner = true;
-                       this.anonymous = anonymous;
 
                        /* Can we open non-files by name? */
                        
@@ -335,7 +311,7 @@ namespace System.IO
                                }
                        }
 
-                       InitBuffer (bufferSize);
+                       InitBuffer (bufferSize, false);
 
                        if (mode==FileMode.Append) {
                                this.Seek (0, SeekOrigin.End);
@@ -375,11 +351,7 @@ namespace System.IO
 
                public string Name {
                        get {
-#if MOONLIGHT
-                               return SecurityManager.CheckElevatedPermissions () ? name : "[Unknown]";
-#else
                                return name;
-#endif
                        }
                }
 
@@ -412,19 +384,26 @@ namespace System.IO
                                if (handle == MonoIO.InvalidHandle)
                                        throw new ObjectDisposedException ("Stream has been closed");
 
-                               if(CanSeek == false)
+                               if (CanSeek == false)
                                        throw new NotSupportedException("The stream does not support seeking");
-                               
+
+                               if (safeHandle != null) {
+                                       // If the handle was leaked outside we always ask the real handle
+                                       MonoIOError error;
+
+                                       long ret = MonoIO.Seek (handle, 0,SeekOrigin.Current,out error);
+
+                                       if (error != MonoIOError.ERROR_SUCCESS) {
+                                               // don't leak the path information for isolated storage
+                                               throw MonoIO.GetException (GetSecureFileName (name), error);
+                                       }
+
+                                       return ret;
+                               }
+       
                                return(buf_start + buf_offset);
                        }
                        set {
-                               if (handle == MonoIO.InvalidHandle)
-                                       throw new ObjectDisposedException ("Stream has been closed");
-
-                               if(CanSeek == false) {
-                                       throw new NotSupportedException("The stream does not support seeking");
-                               }
-
                                if(value < 0) {
                                        throw new ArgumentOutOfRangeException("Attempt to set the position to a negative value");
                                }
@@ -438,6 +417,9 @@ namespace System.IO
                        [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
                        [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
                        get {
+                               if (safeHandle == null) {
+                                       ExposeHandle ();
+                               }
                                return handle;
                        }
                }
@@ -446,20 +428,22 @@ namespace System.IO
                        [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
                        [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
                        get {
-                               SafeFileHandle ret;
-
-                               if (safeHandle != null)
-                                       ret = safeHandle;
-                               else
-                                       ret = new SafeFileHandle (handle, owner);
-
-                               FlushBuffer ();
-                               return ret;
+                               if (safeHandle == null) {
+                                       ExposeHandle ();
+                               }
+                               return safeHandle;
                        }
                }
 
                // methods
 
+         void ExposeHandle ()
+               {
+                       safeHandle = new SafeFileHandle (handle, false);
+                       FlushBuffer ();
+                       InitBuffer (0, true);
+               }
+
                public override int ReadByte ()
                {
                        if (handle == MonoIO.InvalidHandle)
@@ -538,27 +522,20 @@ namespace System.IO
 
                int ReadInternal (byte [] dest, int offset, int count)
                {
-                       int copied = 0;
-
                        int n = ReadSegment (dest, offset, count);
-                       copied += n;
-                       count -= n;
-                       
-                       if (count == 0) {
-                               /* If there was already enough
-                                * buffered, no need to read
-                                * more from the file.
-                                */
-                               return (copied);
+                       if (n == count) {
+                               return count;
                        }
-
+                       
+                       int copied = n;
+                       count -= n;
                        if (count > buf_size) {
                                /* Read as much as we can, up
                                 * to count bytes
                                 */
                                FlushBuffer();
                                n = ReadData (handle, dest,
-                                             offset+copied,
+                                             offset+n,
                                              count);
                        
                                /* Make the next buffer read
@@ -572,9 +549,7 @@ namespace System.IO
                                                 count);
                        }
 
-                       copied += n;
-
-                       return copied;
+                       return copied + n;
                }
 
                delegate int ReadDelegate (byte [] buffer, int offset, int count);
@@ -916,6 +891,9 @@ namespace System.IO
                        Exception exc = null;
                        if (handle != MonoIO.InvalidHandle) {
                                try {
+                                       // If the FileStream is in "exposed" status
+                                       // it means that we do not have a buffer(we write the data without buffering)
+                                       // therefor we don't and can't flush the buffer becouse we don't have one.
                                        FlushBuffer ();
                                } catch (Exception e) {
                                        exc = e;
@@ -956,12 +934,35 @@ namespace System.IO
 #if !NET_2_1
                public FileSecurity GetAccessControl ()
                {
-                       throw new NotImplementedException ();
+                       return new FileSecurity (SafeFileHandle,
+                                                AccessControlSections.Owner |
+                                                AccessControlSections.Group |
+                                                AccessControlSections.Access);
                }
                
                public void SetAccessControl (FileSecurity fileSecurity)
                {
-                       throw new NotImplementedException ();
+                       if (null == fileSecurity)
+                               throw new ArgumentNullException ("fileSecurity");
+                               
+                       fileSecurity.PersistModifications (SafeFileHandle);
+               }
+#endif
+
+#if NET_4_5
+               public override Task FlushAsync (CancellationToken cancellationToken)
+               {
+                       return base.FlushAsync (cancellationToken);
+               }
+
+               public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+               {
+                       return base.ReadAsync (buffer, offset, count, cancellationToken);
+               }
+
+               public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+               {
+                       return base.WriteAsync (buffer, offset, count, cancellationToken);
                }
 #endif
 
@@ -974,18 +975,15 @@ namespace System.IO
 
                private int ReadSegment (byte [] dest, int dest_offset, int count)
                {
-                       if (count > buf_length - buf_offset) {
-                               count = buf_length - buf_offset;
-                       }
+                       count = Math.Min (count, buf_length - buf_offset);
                        
                        if (count > 0) {
-                               Buffer.BlockCopy (buf, buf_offset,
-                                                 dest, dest_offset,
-                                                 count);
+                               // Use the fastest method, all range checks has been done
+                               Buffer.BlockCopyInternal (buf, buf_offset, dest, dest_offset, count);
                                buf_offset += count;
                        }
                        
-                       return(count);
+                       return count;
                }
 
                private int WriteSegment (byte [] src, int src_offset,
@@ -1015,7 +1013,7 @@ namespace System.IO
                        if (buf_dirty) {
                                MonoIOError error;
 
-                               if (CanSeek == true) {
+                               if (CanSeek == true && safeHandle == null) {
                                        MonoIO.Seek (handle, buf_start,
                                                     SeekOrigin.Begin,
                                                     out error);
@@ -1089,30 +1087,35 @@ namespace System.IO
                        return(amount);
                }
                                
-               void InitBuffer (int size)
+               void InitBuffer (int size, bool isZeroSize)
                {
-                       if (size <= 0)
-                               throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
-                       
-                       size = Math.Max (size, 8);
-                       
-                       //
-                       // Instead of allocating a new default buffer use the
-                       // last one if there is any available
-                       //              
-                       if (size <= DefaultBufferSize && buf_recycle != null) {
-                               lock (buf_recycle_lock) {
-                                       if (buf_recycle != null) {
-                                               buf = buf_recycle;
-                                               buf_recycle = null;
+                       if (isZeroSize) {
+                               size = 0;
+                               buf = new byte[1];
+                       } else {
+                               if (size <= 0)
+                                       throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
+
+                               size = Math.Max (size, 8);
+
+                               //
+                               // Instead of allocating a new default buffer use the
+                               // last one if there is any available
+                               //              
+                               if (size <= DefaultBufferSize && buf_recycle != null) {
+                                       lock (buf_recycle_lock) {
+                                               if (buf_recycle != null) {
+                                                       buf = buf_recycle;
+                                                       buf_recycle = null;
+                                               }
                                        }
                                }
+
+                               if (buf == null)
+                                       buf = new byte [size];
+                               else
+                                       Array.Clear (buf, 0, size);
                        }
-                       
-                       if (buf == null)
-                               buf = new byte [size];
-                       else
-                               Array.Clear (buf, 0, size);
                                        
                        buf_size = size;
 //                     buf_start = 0;
@@ -1133,29 +1136,31 @@ namespace System.IO
 
                // fields
 
-               internal const int DefaultBufferSize = 8192;
+               internal const int DefaultBufferSize = 4096;
 
                // Input buffer ready for recycling                             
                static byte[] buf_recycle;
                static readonly object buf_recycle_lock = new object ();
 
+               private byte [] buf;                    // the buffer
+               private string name = "[Unknown]";      // name of file.
+
+               SafeFileHandle safeHandle;              // set only when using one of the
+                                                       // constructors taking SafeFileHandle
+
+               private long append_startpos;
+               IntPtr handle;                          // handle to underlying file
+
                private FileAccess access;
                private bool owner;
                private bool async;
                private bool canseek;
-               private long append_startpos;
                private bool anonymous;
+               private bool buf_dirty;                 // true if buffer has been written to
 
-               private byte [] buf;                    // the buffer
                private int buf_size;                   // capacity in bytes
                private int buf_length;                 // number of valid bytes in buffer
                private int buf_offset;                 // position of next byte
-               private bool buf_dirty;                 // true if buffer has been written to
                private long buf_start;                 // location of buffer in file
-               private string name = "[Unknown]";      // name of file.
-
-               IntPtr handle;                          // handle to underlying file
-               SafeFileHandle safeHandle;              // set only when using one of the
-                                                       // constructors taking SafeFileHandle
        }
 }