// Dietmar Maurer (dietmar@ximian.com)
// Dan Lewis (dihlewis@yahoo.co.uk)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
+// Marek Safar (marek.safar@gmail.com)
//
// (C) 2001-2003 Ximian, Inc. http://www.ximian.com
-// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.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
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
+using System.Security;
using System.Security.Permissions;
using System.Threading;
-
-#if NET_2_0
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
{
-#if NET_2_0
[ComVisible (true)]
-#endif
public class FileStream : Stream
{
// construct from handle
-#if NET_2_0_SAFEFILEHANDLE_ENABLED
[Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
-#endif
public FileStream (IntPtr handle, FileAccess access)
: this (handle, access, true, DefaultBufferSize, false) {}
-#if NET_2_0_SAFEFILEHANDLE_ENABLED
[Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
-#endif
public FileStream (IntPtr handle, FileAccess access, bool ownsHandle)
: this (handle, access, ownsHandle, DefaultBufferSize, false) {}
-#if NET_2_0_SAFEFILEHANDLE_ENABLED
[Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead")]
-#endif
public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
: this (handle, access, ownsHandle, bufferSize, false) {}
-#if NET_2_0_SAFEFILEHANDLE_ENABLED
[Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead")]
-#endif
public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
: this (handle, access, ownsHandle, bufferSize, isAsync, false) {}
[SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
- internal FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool noBuffering)
+ internal FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isZeroSize)
{
this.handle = MonoIO.InvalidHandle;
if (handle == this.handle)
}
this.handle = handle;
+ ExposeHandle ();
this.access = access;
this.owner = ownsHandle;
this.async = isAsync;
this.anonymous = false;
-
- InitBuffer (bufferSize, noBuffering);
-
if (canseek) {
buf_start = MonoIO.Seek (handle, 0, SeekOrigin.Current, out error);
if (error != MonoIOError.ERROR_SUCCESS) {
}
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_0
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)
{
int bufferSize, bool isAsync)
:this (handle.DangerousGetHandle (), access, false, bufferSize, isAsync)
{
+ this.safeHandle = handle;
}
+ [MonoLimitation ("This ignores the rights parameter")]
public FileStream (string path, FileMode mode,
FileSystemRights rights, FileShare share,
int bufferSize, FileOptions options)
+ : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
{
- throw new NotImplementedException ();
}
+ [MonoLimitation ("This ignores the rights and fileSecurity parameters")]
public FileStream (string path, FileMode mode,
FileSystemRights rights, FileShare share,
int bufferSize, FileOptions options,
FileSecurity fileSecurity)
+ : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
{
- throw new NotImplementedException ();
}
#endif
throw new ArgumentException ("Path is empty");
}
-#if NET_2_0
+ this.anonymous = anonymous;
// ignore the Inheritable flag
share &= ~FileShare.Inheritable;
-#endif
-
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
- if (mode < FileMode.CreateNew || mode > FileMode.Append)
+ if (mode < FileMode.CreateNew || mode > FileMode.Append) {
+#if NET_2_1
+ if (anonymous)
+ throw new ArgumentException ("mode", "Enum value was out of legal range.");
+ else
+#endif
throw new ArgumentOutOfRangeException ("mode", "Enum value was out of legal range.");
+ }
- if (access < FileAccess.Read || access > FileAccess.ReadWrite)
+ if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
throw new ArgumentOutOfRangeException ("access", "Enum value was out of legal range.");
+ }
-#if NET_2_0
- if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete))
-#else
- if (share < FileShare.None || share > FileShare.ReadWrite)
-#endif
+ if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) {
throw new ArgumentOutOfRangeException ("share", "Enum value was out of legal range.");
+ }
if (path.IndexOfAny (Path.InvalidPathChars) != -1) {
throw new ArgumentException ("Name has invalid chars");
if (Directory.Exists (path)) {
// don't leak the path information for isolated storage
string msg = Locale.GetText ("Access to the path '{0}' is denied.");
- string fname = (anonymous) ? Path.GetFileName (path) : Path.GetFullPath (path);
- throw new UnauthorizedAccessException (String.Format (msg, fname));
+ throw new UnauthorizedAccessException (String.Format (msg, GetSecureFileName (path, false)));
}
/* Append streams can't be read (see FileMode
throw new ArgumentException (string.Format (msg, access, mode));
}
- string dname = Path.GetDirectoryName (path);
+ SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
+ string dname;
+ if (Path.DirectorySeparatorChar != '/' && path.IndexOf ('/') >= 0)
+ dname = Path.GetDirectoryName (Path.GetFullPath (path));
+ else
+ dname = Path.GetDirectoryName (path);
if (dname.Length > 0) {
string fp = Path.GetFullPath (dname);
if (!Directory.Exists (fp)) {
mode != FileMode.CreateNew && !File.Exists (path)) {
// don't leak the path information for isolated storage
string msg = Locale.GetText ("Could not find file \"{0}\".");
- string fname = (anonymous) ? Path.GetFileName (path) : Path.GetFullPath (path);
+ string fname = GetSecureFileName (path);
throw new FileNotFoundException (String.Format (msg, fname), fname);
}
this.handle = MonoIO.Open (path, mode, access, share, options, out error);
if (handle == MonoIO.InvalidHandle) {
// don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (path) : Path.GetFullPath (path);
- throw MonoIO.GetException (fname, error);
+ throw MonoIO.GetException (GetSecureFileName (path), error);
}
this.access = access;
this.owner = true;
- this.anonymous = anonymous;
/* Can we open non-files by name? */
public string Name {
get {
- return name;
+ return name;
}
}
length = MonoIO.GetLength (handle, out error);
if (error != MonoIOError.ERROR_SUCCESS) {
// don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
+ throw MonoIO.GetException (GetSecureFileName (name), error);
}
return(length);
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");
}
}
}
-#if NET_2_0
[Obsolete ("Use SafeFileHandle instead")]
-#endif
public virtual IntPtr Handle {
[SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
[SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
get {
+ if (safeHandle == null) {
+ ExposeHandle ();
+ }
return handle;
}
}
-#if NET_2_0
public virtual SafeFileHandle SafeFileHandle {
[SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
[SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
- get { throw new NotImplementedException (); }
+ get {
+ if (safeHandle == null) {
+ ExposeHandle ();
+ }
+ return safeHandle;
+ }
}
-#endif
// methods
+ void ExposeHandle ()
+ {
+ safeHandle = new SafeFileHandle (handle, false);
+ FlushBuffer ();
+ InitBuffer (0, true);
+ }
+
public override int ReadByte ()
{
if (handle == MonoIO.InvalidHandle)
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
count);
}
- copied += n;
-
- return copied;
+ return copied + n;
}
delegate int ReadDelegate (byte [] buffer, int offset, int count);
MonoIOError error;
FlushBuffer ();
-
- MonoIO.Write (handle, src, offset, count, out error);
- if (error != MonoIOError.ERROR_SUCCESS) {
- // don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
- }
+ int wcount = count;
+ while (wcount > 0){
+ int n = MonoIO.Write (handle, src, offset, wcount, out error);
+ if (error != MonoIOError.ERROR_SUCCESS)
+ throw MonoIO.GetException (GetSecureFileName (name), error);
+
+ wcount -= n;
+ offset += n;
+ }
buf_start += count;
} else {
if (buf_dirty) {
MemoryStream ms = new MemoryStream ();
- FlushBufferToStream (ms);
+ FlushBuffer (ms);
ms.Write (array, offset, numBytes);
offset = 0;
numBytes = (int) ms.Length;
if (error != MonoIOError.ERROR_SUCCESS) {
// don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
+ throw MonoIO.GetException (GetSecureFileName (name), error);
}
return(buf_start);
MonoIO.SetLength (handle, value, out error);
if (error != MonoIOError.ERROR_SUCCESS) {
// don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
+ throw MonoIO.GetException (GetSecureFileName (name), error);
}
if (Position > value)
throw new ObjectDisposedException ("Stream has been closed");
FlushBuffer ();
-
- // The flushing is not actually required, in
- //the mono runtime we were mapping flush to
- //`fsync' which is not the same.
- //
- //MonoIO.Flush (handle);
}
-#if !NET_2_0
- public override void Close ()
+#if NET_4_0
+ public virtual void Flush (bool flushToDisk)
{
- Dispose (true);
+ FlushBuffer ();
+
+ // This does the fsync
+ if (flushToDisk){
+ MonoIOError error;
+ MonoIO.Flush (handle, out error);
+ }
}
#endif
MonoIO.Lock (handle, position, length, out error);
if (error != MonoIOError.ERROR_SUCCESS) {
// don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
+ throw MonoIO.GetException (GetSecureFileName (name), error);
}
}
MonoIO.Unlock (handle, position, length, out error);
if (error != MonoIOError.ERROR_SUCCESS) {
// don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
+ throw MonoIO.GetException (GetSecureFileName (name), error);
}
}
Dispose (false);
}
-#if NET_2_0
protected override void Dispose (bool disposing)
-#else
- protected virtual void Dispose (bool disposing)
-#endif
{
+ Exception exc = null;
if (handle != MonoIO.InvalidHandle) {
- FlushBuffer ();
+ 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;
+ }
if (owner) {
MonoIOError error;
MonoIO.Close (handle, out error);
if (error != MonoIOError.ERROR_SUCCESS) {
// don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
+ throw MonoIO.GetException (GetSecureFileName (name), error);
}
handle = MonoIO.InvalidHandle;
canseek = false;
access = 0;
- if (disposing) {
+
+ if (disposing && buf != null) {
+ if (buf.Length == DefaultBufferSize && buf_recycle == null) {
+ lock (buf_recycle_lock) {
+ if (buf_recycle == null) {
+ buf_recycle = buf;
+ }
+ }
+ }
+
buf = null;
- }
- if (disposing)
GC.SuppressFinalize (this);
+ }
+ if (exc != null)
+ throw exc;
}
-#if NET_2_0
+#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
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,
return(count);
}
- void FlushBufferToStream (Stream st)
+ void FlushBuffer (Stream st)
{
if (buf_dirty) {
- if (CanSeek == true) {
- MonoIOError error;
+ MonoIOError error;
+
+ if (CanSeek == true && safeHandle == null) {
MonoIO.Seek (handle, buf_start,
SeekOrigin.Begin,
out error);
if (error != MonoIOError.ERROR_SUCCESS) {
// don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
+ throw MonoIO.GetException (GetSecureFileName (name), error);
+ }
+ }
+ if (st == null) {
+ int wcount = buf_length;
+ int offset = 0;
+ while (wcount > 0){
+ int n = MonoIO.Write (handle, buf, 0, buf_length, out error);
+ if (error != MonoIOError.ERROR_SUCCESS) {
+ // don't leak the path information for isolated storage
+ throw MonoIO.GetException (GetSecureFileName (name), error);
+ }
+ wcount -= n;
+ offset += n;
}
+ } else {
+ st.Write (buf, 0, buf_length);
}
- st.Write (buf, 0, buf_length);
}
buf_start += buf_offset;
private void FlushBuffer ()
{
- if (buf_dirty) {
- MonoIOError error;
-
- if (CanSeek == true) {
- MonoIO.Seek (handle, buf_start,
- SeekOrigin.Begin,
- out error);
- if (error != MonoIOError.ERROR_SUCCESS) {
- // don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
- }
- }
- MonoIO.Write (handle, buf, 0,
- buf_length, out error);
-
- if (error != MonoIOError.ERROR_SUCCESS) {
- // don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
- }
- }
-
- buf_start += buf_offset;
- buf_offset = buf_length = 0;
- buf_dirty = false;
+ FlushBuffer (null);
}
private void FlushBufferIfDirty ()
{
if (buf_dirty)
- FlushBuffer ();
+ FlushBuffer (null);
}
private void RefillBuffer ()
{
- FlushBuffer();
+ FlushBuffer (null);
buf_length = ReadData (handle, buf, 0,
buf_size);
amount = 0; // might not be needed, but well...
} else if (error != MonoIOError.ERROR_SUCCESS) {
// don't leak the path information for isolated storage
- string fname = (anonymous) ? Path.GetFileName (name) : name;
- throw MonoIO.GetException (fname, error);
+ throw MonoIO.GetException (GetSecureFileName (name), error);
}
/* Check for read error */
return(amount);
}
- private void InitBuffer (int size, bool noBuffering)
+ void InitBuffer (int size, bool isZeroSize)
{
- if (noBuffering) {
+ if (isZeroSize) {
size = 0;
- // We need a buffer for the ReadByte method. This buffer won't
- // be used for anything else since buf_size==0.
- buf = new byte [1];
- }
- else {
+ buf = new byte[1];
+ } else {
if (size <= 0)
throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
- if (size < 8)
- size = 8;
- buf = new byte [size];
+
+ 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);
}
buf_size = size;
- buf_start = 0;
- buf_offset = buf_length = 0;
- buf_dirty = false;
+// buf_start = 0;
+// buf_offset = buf_length = 0;
+// buf_dirty = false;
+ }
+
+ private string GetSecureFileName (string filename)
+ {
+ return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
+ }
+
+ private string GetSecureFileName (string filename, bool full)
+ {
+ return (anonymous) ? Path.GetFileName (filename) :
+ (full) ? Path.GetFullPath (filename) : filename;
}
// 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
}
}