[mini] Fix the llvmonlycheck test.
[mono.git] / mcs / class / corlib / System.IO / FileStream.cs
1 //
2 // System.IO.FileStream.cs
3 //
4 // Authors:
5 //      Dietmar Maurer (dietmar@ximian.com)
6 //      Dan Lewis (dihlewis@yahoo.co.uk)
7 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 //  Marek Safar (marek.safar@gmail.com)
9 //
10 // (C) 2001-2003 Ximian, Inc.  http://www.ximian.com
11 // Copyright (C) 2004-2005, 2008, 2010 Novell, Inc (http://www.novell.com)
12 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System.Collections;
35 using System.Globalization;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
38 using System.Runtime.Remoting.Messaging;
39 using System.Security;
40 using System.Security.AccessControl;
41 using System.Security.Permissions;
42 using System.Threading;
43 using System.Threading.Tasks;
44 using Microsoft.Win32.SafeHandles;
45
46 namespace System.IO
47 {
48         [ComVisible (true)]
49         public class FileStream : Stream
50         {
51                 // construct from handle
52                 
53                 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
54                 public FileStream (IntPtr handle, FileAccess access)
55                         : this (handle, access, true, DefaultBufferSize, false, false) {}
56
57                 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
58                 public FileStream (IntPtr handle, FileAccess access, bool ownsHandle)
59                         : this (handle, access, ownsHandle, DefaultBufferSize, false, false) {}
60                 
61                 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead")]
62                 public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
63                         : this (handle, access, ownsHandle, bufferSize, false, false) {}
64
65                 [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead")]
66                 public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
67                         : this (handle, access, ownsHandle, bufferSize, isAsync, false) {}
68
69                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
70                 internal FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isConsoleWrapper)
71                 {
72                         if (handle == MonoIO.InvalidHandle)
73                                 throw new ArgumentException ("handle", Locale.GetText ("Invalid."));
74
75                         Init (new SafeFileHandle (handle, false), access, ownsHandle, bufferSize, isAsync, isConsoleWrapper);
76                 }
77
78                 // construct from filename
79
80                 public FileStream (string path, FileMode mode)
81                         : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.Read, DefaultBufferSize, false, FileOptions.None)
82                 {
83                 }
84
85                 public FileStream (string path, FileMode mode, FileAccess access)
86                         : this (path, mode, access, access == FileAccess.Write ? FileShare.None : FileShare.Read, DefaultBufferSize, false, false)
87                 {
88                 }
89
90                 public FileStream (string path, FileMode mode, FileAccess access, FileShare share)
91                         : this (path, mode, access, share, DefaultBufferSize, false, FileOptions.None)
92                 {
93                 }
94
95                 public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
96                         : this (path, mode, access, share, bufferSize, false, FileOptions.None)
97                 {
98                 }
99
100                 public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
101                         : this (path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None)
102                 {
103                 }
104
105                 public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
106                         : this (path, mode, access, share, bufferSize, false, options)
107                 {
108                 }
109
110                 public FileStream (SafeFileHandle handle, FileAccess access)
111                         :this(handle, access, DefaultBufferSize, false)
112                 {
113                 }
114                 
115                 public FileStream (SafeFileHandle handle, FileAccess access,
116                                    int bufferSize)
117                         :this(handle, access, bufferSize, false)
118                 {
119                 }
120
121                 public FileStream (SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
122                 {
123                         Init (handle, access, false, bufferSize, isAsync, false);
124                 }
125
126                 [MonoLimitation ("This ignores the rights parameter")]
127                 public FileStream (string path, FileMode mode,
128                                    FileSystemRights rights, FileShare share,
129                                    int bufferSize, FileOptions options)
130                         : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
131                 {
132                 }
133                 
134                 [MonoLimitation ("This ignores the rights and fileSecurity parameters")]
135                 public FileStream (string path, FileMode mode,
136                                    FileSystemRights rights, FileShare share,
137                                    int bufferSize, FileOptions options,
138                                    FileSecurity fileSecurity)
139                         : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
140                 {
141                 }
142
143                 internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy, bool useLongPath = false, bool checkHost = false)
144                         : this (path, mode, access, share, bufferSize, false, options)
145                 {
146                 }
147
148                 internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool isAsync, bool anonymous)
149                         : this (path, mode, access, share, bufferSize, anonymous, isAsync ? FileOptions.Asynchronous : FileOptions.None)
150                 {
151                 }
152
153                 internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool anonymous, FileOptions options)
154                 {
155                         if (path == null) {
156                                 throw new ArgumentNullException ("path");
157                         }
158
159                         if (path.Length == 0) {
160                                 throw new ArgumentException ("Path is empty");
161                         }
162
163                         this.anonymous = anonymous;
164                         // ignore the Inheritable flag
165                         share &= ~FileShare.Inheritable;
166
167                         if (bufferSize <= 0)
168                                 throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
169
170                         if (mode < FileMode.CreateNew || mode > FileMode.Append) {
171 #if MOBILE
172                                 if (anonymous)
173                                         throw new ArgumentException ("mode", "Enum value was out of legal range.");
174                                 else
175 #endif
176                                 throw new ArgumentOutOfRangeException ("mode", "Enum value was out of legal range.");
177                         }
178
179                         if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
180                                 throw new ArgumentOutOfRangeException ("access", "Enum value was out of legal range.");
181                         }
182
183                         if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) {
184                                 throw new ArgumentOutOfRangeException ("share", "Enum value was out of legal range.");
185                         }
186
187                         if (path.IndexOfAny (Path.InvalidPathChars) != -1) {
188                                 throw new ArgumentException ("Name has invalid chars");
189                         }
190
191                         path = Path.InsecureGetFullPath (path);
192
193                         if (Directory.Exists (path)) {
194                                 // don't leak the path information for isolated storage
195                                 string msg = Locale.GetText ("Access to the path '{0}' is denied.");
196                                 throw new UnauthorizedAccessException (String.Format (msg, GetSecureFileName (path, false)));
197                         }
198
199                         /* Append streams can't be read (see FileMode
200                          * docs)
201                          */
202                         if (mode==FileMode.Append &&
203                                 (access&FileAccess.Read)==FileAccess.Read) {
204                                 throw new ArgumentException("Append access can be requested only in write-only mode.");
205                         }
206
207                         if ((access & FileAccess.Write) == 0 &&
208                                 (mode != FileMode.Open && mode != FileMode.OpenOrCreate)) {
209                                 string msg = Locale.GetText ("Combining FileMode: {0} with " +
210                                         "FileAccess: {1} is invalid.");
211                                 throw new ArgumentException (string.Format (msg, access, mode));
212                         }
213
214                         SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
215
216                         string dname = Path.GetDirectoryName (path);
217                         if (dname.Length > 0) {
218                                 string fp = Path.GetFullPath (dname);
219                                 if (!Directory.Exists (fp)) {
220                                         // don't leak the path information for isolated storage
221                                         string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
222                                         string fname = (anonymous) ? dname : Path.GetFullPath (path);
223                                         throw new DirectoryNotFoundException (String.Format (msg, fname));
224                                 }
225                         }
226
227                         if (access == FileAccess.Read && mode != FileMode.Create && mode != FileMode.OpenOrCreate &&
228                                         mode != FileMode.CreateNew && !File.Exists (path)) {
229                                 // don't leak the path information for isolated storage
230                                 string msg = Locale.GetText ("Could not find file \"{0}\".");
231                                 string fname = GetSecureFileName (path);
232                                 throw new FileNotFoundException (String.Format (msg, fname), fname);
233                         }
234
235                         // IsolatedStorage needs to keep the Name property to the default "[Unknown]"
236                         if (!anonymous)
237                                 this.name = path;
238
239                         // TODO: demand permissions
240
241                         MonoIOError error;
242
243                         var nativeHandle = MonoIO.Open (path, mode, access, share, options, out error);
244
245                         if (nativeHandle == MonoIO.InvalidHandle) {
246                                 // don't leak the path information for isolated storage
247                                 throw MonoIO.GetException (GetSecureFileName (path), error);
248                         }
249
250                         this.safeHandle = new SafeFileHandle (nativeHandle, false);
251
252                         this.access = access;
253                         this.owner = true;
254
255                         /* Can we open non-files by name? */
256
257                         if (MonoIO.GetFileType (safeHandle, out error) == MonoFileType.Disk) {
258                                 this.canseek = true;
259                                 this.async = (options & FileOptions.Asynchronous) != 0;
260                         } else {
261                                 this.canseek = false;
262                                 this.async = false;
263                         }
264
265
266                         if (access == FileAccess.Read && canseek && (bufferSize == DefaultBufferSize)) {
267                                 /* Avoid allocating a large buffer for small files */
268                                 long len = Length;
269                                 if (bufferSize > len) {
270                                         bufferSize = (int)(len < 1000 ? 1000 : len);
271                                 }
272                         }
273
274                         InitBuffer (bufferSize, false);
275
276                         if (mode==FileMode.Append) {
277                                 this.Seek (0, SeekOrigin.End);
278                                 this.append_startpos=this.Position;
279                         } else {
280                                 this.append_startpos=0;
281                         }
282                 }
283
284                 private void Init (SafeFileHandle safeHandle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isConsoleWrapper)
285                 {
286                         if (!isConsoleWrapper && safeHandle.IsInvalid)
287                                 throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle");
288                         if (access < FileAccess.Read || access > FileAccess.ReadWrite)
289                                 throw new ArgumentOutOfRangeException ("access");
290                         if (!isConsoleWrapper && bufferSize <= 0)
291                                 throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
292
293                         MonoIOError error;
294                         MonoFileType ftype = MonoIO.GetFileType (safeHandle, out error);
295
296                         if (error != MonoIOError.ERROR_SUCCESS) {
297                                 throw MonoIO.GetException (name, error);
298                         }
299
300                         if (ftype == MonoFileType.Unknown) {
301                                 throw new IOException ("Invalid handle.");
302                         } else if (ftype == MonoFileType.Disk) {
303                                 this.canseek = true;
304                         } else {
305                                 this.canseek = false;
306                         }
307
308                         this.safeHandle = safeHandle;
309                         ExposeHandle ();
310                         this.access = access;
311                         this.owner = ownsHandle;
312                         this.async = isAsync;
313                         this.anonymous = false;
314
315                         if (canseek) {
316                                 buf_start = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
317                                 if (error != MonoIOError.ERROR_SUCCESS) {
318                                         throw MonoIO.GetException (name, error);
319                                 }
320                         }
321
322                         /* Can't set append mode */
323                         this.append_startpos=0;
324                 }
325
326                 // properties
327                 
328                 public override bool CanRead {
329                         get {
330                                 return access == FileAccess.Read ||
331                                        access == FileAccess.ReadWrite;
332                         }
333                 }
334
335                 public override bool CanWrite {
336                         get {
337                                 return access == FileAccess.Write ||
338                                         access == FileAccess.ReadWrite;
339                         }
340                 }
341                 
342                 public override bool CanSeek {
343                         get {
344                                 return(canseek);
345                         }
346                 }
347
348                 public virtual bool IsAsync {
349                         get {
350                                 return (async);
351                         }
352                 }
353
354                 public string Name {
355                         get {
356                                 return name;
357                         }
358                 }
359
360                 public override long Length {
361                         get {
362                                 if (safeHandle.IsClosed)
363                                         throw new ObjectDisposedException ("Stream has been closed");
364
365                                 if (!CanSeek)
366                                         throw new NotSupportedException ("The stream does not support seeking");
367
368                                 // Buffered data might change the length of the stream
369                                 FlushBufferIfDirty ();
370
371                                 MonoIOError error;
372
373                                 long length = MonoIO.GetLength (safeHandle, out error);
374
375                                 if (error != MonoIOError.ERROR_SUCCESS) {
376                                         // don't leak the path information for isolated storage
377                                         throw MonoIO.GetException (GetSecureFileName (name), error);
378                                 }
379
380                                 return(length);
381                         }
382                 }
383
384                 public override long Position {
385                         get {
386                                 if (safeHandle.IsClosed)
387                                         throw new ObjectDisposedException ("Stream has been closed");
388
389                                 if (CanSeek == false)
390                                         throw new NotSupportedException("The stream does not support seeking");
391
392                                 if (!isExposed)
393                                         return(buf_start + buf_offset);
394
395                                 // If the handle was leaked outside we always ask the real handle
396                                 MonoIOError error;
397
398                                 long ret = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
399
400                                 if (error != MonoIOError.ERROR_SUCCESS) {
401                                         // don't leak the path information for isolated storage
402                                         throw MonoIO.GetException (GetSecureFileName (name), error);
403                                 }
404
405                                 return ret;
406                         }
407                         set {
408                                 if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
409
410                                 Seek (value, SeekOrigin.Begin);
411                         }
412                 }
413
414                 [Obsolete ("Use SafeFileHandle instead")]
415                 public virtual IntPtr Handle {
416                         [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
417                         [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
418                         get {
419                                 var handle = safeHandle.DangerousGetHandle ();
420                                 if (!isExposed)
421                                         ExposeHandle ();
422                                 return handle;
423                         }
424                 }
425
426                 public virtual SafeFileHandle SafeFileHandle {
427                         [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
428                         [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
429                         get {
430                                 if (!isExposed)
431                                         ExposeHandle ();
432                                 return safeHandle;
433                         }
434                 }
435
436                 void ExposeHandle ()
437                 {
438                         isExposed = true;
439                         FlushBuffer ();
440                         InitBuffer (0, true);
441                 }
442
443                 // methods
444
445                 public override int ReadByte ()
446                 {
447                         if (safeHandle.IsClosed)
448                                 throw new ObjectDisposedException ("Stream has been closed");
449
450                         if (!CanRead)
451                                 throw new NotSupportedException ("Stream does not support reading");
452
453                         if (buf_size == 0) {
454                                 int n = ReadData (safeHandle, buf, 0, 1);
455                                 if (n == 0) return -1;
456                                 else return buf[0];
457                         }
458                         else if (buf_offset >= buf_length) {
459                                 RefillBuffer ();
460
461                                 if (buf_length == 0)
462                                         return -1;
463                         }
464                         
465                         return buf [buf_offset ++];
466                 }
467
468                 public override void WriteByte (byte value)
469                 {
470                         if (safeHandle.IsClosed)
471                                 throw new ObjectDisposedException ("Stream has been closed");
472
473                         if (!CanWrite)
474                                 throw new NotSupportedException ("Stream does not support writing");
475
476                         if (buf_offset == buf_size)
477                                 FlushBuffer ();
478
479                         if (buf_size == 0) { // No buffering
480                                 buf [0] = value;
481                                 buf_dirty = true;
482                                 buf_length = 1;
483                                 FlushBuffer ();
484                                 return;
485                         }
486
487                         buf [buf_offset ++] = value;
488                         if (buf_offset > buf_length)
489                                 buf_length = buf_offset;
490
491                         buf_dirty = true;
492                 }
493
494                 public override int Read ([In,Out] byte[] array, int offset, int count)
495                 {
496                         if (safeHandle.IsClosed)
497                                 throw new ObjectDisposedException ("Stream has been closed");
498                         if (array == null)
499                                 throw new ArgumentNullException ("array");
500                         if (!CanRead)
501                                 throw new NotSupportedException ("Stream does not support reading");
502                         int len = array.Length;
503                         if (offset < 0)
504                                 throw new ArgumentOutOfRangeException ("offset", "< 0");
505                         if (count < 0)
506                                 throw new ArgumentOutOfRangeException ("count", "< 0");
507                         if (offset > len)
508                                 throw new ArgumentException ("destination offset is beyond array size");
509                         // reordered to avoid possible integer overflow
510                         if (offset > len - count)
511                                 throw new ArgumentException ("Reading would overrun buffer");
512
513                         if (async) {
514                                 IAsyncResult ares = BeginRead (array, offset, count, null, null);
515                                 return EndRead (ares);
516                         }
517
518                         return ReadInternal (array, offset, count);
519                 }
520
521                 int ReadInternal (byte [] dest, int offset, int count)
522                 {
523                         int n = ReadSegment (dest, offset, count);
524                         if (n == count) {
525                                 return count;
526                         }
527                         
528                         int copied = n;
529                         count -= n;
530
531                         if (count > buf_size) {
532                                 /* Read as much as we can, up
533                                  * to count bytes
534                                  */
535                                 FlushBuffer();
536                                 n = ReadData (safeHandle, dest, offset+n, count);
537
538                                 /* Make the next buffer read
539                                  * start from the right place
540                                  */
541                                 buf_start += n;
542                         } else {
543                                 RefillBuffer ();
544                                 n = ReadSegment (dest, offset+copied, count);
545                         }
546
547                         return copied + n;
548                 }
549
550                 delegate int ReadDelegate (byte [] buffer, int offset, int count);
551
552                 public override IAsyncResult BeginRead (byte [] array, int offset, int numBytes,
553                                                         AsyncCallback userCallback, object stateObject)
554                 {
555                         if (safeHandle.IsClosed)
556                                 throw new ObjectDisposedException ("Stream has been closed");
557
558                         if (!CanRead)
559                                 throw new NotSupportedException ("This stream does not support reading");
560
561                         if (array == null)
562                                 throw new ArgumentNullException ("array");
563
564                         if (numBytes < 0)
565                                 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
566
567                         if (offset < 0)
568                                 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
569
570                         // reordered to avoid possible integer overflow
571                         if (numBytes > array.Length - offset)
572                                 throw new ArgumentException ("Buffer too small. numBytes/offset wrong.");
573
574                         if (!async)
575                                 return base.BeginRead (array, offset, numBytes, userCallback, stateObject);
576
577                         ReadDelegate r = new ReadDelegate (ReadInternal);
578                         return r.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
579                 }
580                 
581                 public override int EndRead (IAsyncResult asyncResult)
582                 {
583                         if (asyncResult == null)
584                                 throw new ArgumentNullException ("asyncResult");
585
586                         if (!async)
587                                 return base.EndRead (asyncResult);
588
589                         AsyncResult ares = asyncResult as AsyncResult;
590                         if (ares == null)
591                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
592
593                         ReadDelegate r = ares.AsyncDelegate as ReadDelegate;
594                         if (r == null)
595                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
596
597                         return r.EndInvoke (asyncResult);
598                 }
599
600                 public override void Write (byte[] array, int offset, int count)
601                 {
602                         if (safeHandle.IsClosed)
603                                 throw new ObjectDisposedException ("Stream has been closed");
604                         if (array == null)
605                                 throw new ArgumentNullException ("array");
606                         if (offset < 0)
607                                 throw new ArgumentOutOfRangeException ("offset", "< 0");
608                         if (count < 0)
609                                 throw new ArgumentOutOfRangeException ("count", "< 0");
610                         // ordered to avoid possible integer overflow
611                         if (offset > array.Length - count)
612                                 throw new ArgumentException ("Reading would overrun buffer");
613                         if (!CanWrite)
614                                 throw new NotSupportedException ("Stream does not support writing");
615
616                         if (async) {
617                                 IAsyncResult ares = BeginWrite (array, offset, count, null, null);
618                                 EndWrite (ares);
619                                 return;
620                         }
621
622                         WriteInternal (array, offset, count);
623                 }
624
625                 void WriteInternal (byte [] src, int offset, int count)
626                 {
627                         if (count > buf_size) {
628                                 // shortcut for long writes
629                                 MonoIOError error;
630
631                                 FlushBuffer ();
632
633                                 if (CanSeek && !isExposed) {
634                                         MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
635                                         if (error != MonoIOError.ERROR_SUCCESS)
636                                                 throw MonoIO.GetException (GetSecureFileName (name), error);
637                                 }
638
639                                 int wcount = count;
640
641                                 while (wcount > 0){
642                                         int n = MonoIO.Write (safeHandle, src, offset, wcount, out error);
643                                         if (error != MonoIOError.ERROR_SUCCESS)
644                                                 throw MonoIO.GetException (GetSecureFileName (name), error);
645
646                                         wcount -= n;
647                                         offset += n;
648                                 }
649                                 buf_start += count;
650                         } else {
651
652                                 int copied = 0;
653                                 while (count > 0) {
654                                         
655                                         int n = WriteSegment (src, offset + copied, count);
656                                         copied += n;
657                                         count -= n;
658
659                                         if (count == 0) {
660                                                 break;
661                                         }
662
663                                         FlushBuffer ();
664                                 }
665                         }
666                 }
667
668                 delegate void WriteDelegate (byte [] buffer, int offset, int count);
669
670                 public override IAsyncResult BeginWrite (byte [] array, int offset, int numBytes,
671                                                         AsyncCallback userCallback, object stateObject)
672                 {
673                         if (safeHandle.IsClosed)
674                                 throw new ObjectDisposedException ("Stream has been closed");
675
676                         if (!CanWrite)
677                                 throw new NotSupportedException ("This stream does not support writing");
678
679                         if (array == null)
680                                 throw new ArgumentNullException ("array");
681
682                         if (numBytes < 0)
683                                 throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
684
685                         if (offset < 0)
686                                 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
687
688                         // reordered to avoid possible integer overflow
689                         if (numBytes > array.Length - offset)
690                                 throw new ArgumentException ("array too small. numBytes/offset wrong.");
691
692                         if (!async)
693                                 return base.BeginWrite (array, offset, numBytes, userCallback, stateObject);
694
695                         FileStreamAsyncResult result = new FileStreamAsyncResult (userCallback, stateObject);
696                         result.BytesRead = -1;
697                         result.Count = numBytes;
698                         result.OriginalCount = numBytes;
699 /*
700                         if (buf_dirty) {
701                                 MemoryStream ms = new MemoryStream ();
702                                 FlushBuffer (ms);
703                                 ms.Write (array, offset, numBytes);
704
705                                 // Set arguments to new compounded buffer 
706                                 offset = 0;
707                                 array = ms.ToArray ();
708                                 numBytes = array.Length;
709                         }
710 */
711                         WriteDelegate w = WriteInternal;
712                         return w.BeginInvoke (array, offset, numBytes, userCallback, stateObject);      
713                 }
714                 
715                 public override void EndWrite (IAsyncResult asyncResult)
716                 {
717                         if (asyncResult == null)
718                                 throw new ArgumentNullException ("asyncResult");
719
720                         if (!async) {
721                                 base.EndWrite (asyncResult);
722                                 return;
723                         }
724
725                         AsyncResult ares = asyncResult as AsyncResult;
726                         if (ares == null)
727                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
728
729                         WriteDelegate w = ares.AsyncDelegate as WriteDelegate;
730                         if (w == null)
731                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
732
733                         w.EndInvoke (asyncResult);
734                         return;
735                 }
736
737                 public override long Seek (long offset, SeekOrigin origin)
738                 {
739                         long pos;
740
741                         if (safeHandle.IsClosed)
742                                 throw new ObjectDisposedException ("Stream has been closed");
743                         
744                         // make absolute
745
746                         if(CanSeek == false) {
747                                 throw new NotSupportedException("The stream does not support seeking");
748                         }
749
750                         switch (origin) {
751                         case SeekOrigin.End:
752                                 pos = Length + offset;
753                                 break;
754
755                         case SeekOrigin.Current:
756                                 pos = Position + offset;
757                                 break;
758
759                         case SeekOrigin.Begin:
760                                 pos = offset;
761                                 break;
762
763                         default:
764                                 throw new ArgumentException ("origin", "Invalid SeekOrigin");
765                         }
766
767                         if (pos < 0) {
768                                 /* LAMESPEC: shouldn't this be
769                                  * ArgumentOutOfRangeException?
770                                  */
771                                 throw new IOException("Attempted to Seek before the beginning of the stream");
772                         }
773
774                         if(pos < this.append_startpos) {
775                                 /* More undocumented crap */
776                                 throw new IOException("Can't seek back over pre-existing data in append mode");
777                         }
778
779                         FlushBuffer ();
780
781                         MonoIOError error;
782
783                         buf_start = MonoIO.Seek (safeHandle, pos, SeekOrigin.Begin, out error);
784
785                         if (error != MonoIOError.ERROR_SUCCESS) {
786                                 // don't leak the path information for isolated storage
787                                 throw MonoIO.GetException (GetSecureFileName (name), error);
788                         }
789                         
790                         return(buf_start);
791                 }
792
793                 public override void SetLength (long value)
794                 {
795                         if (safeHandle.IsClosed)
796                                 throw new ObjectDisposedException ("Stream has been closed");
797
798                         if(CanSeek == false)
799                                 throw new NotSupportedException("The stream does not support seeking");
800
801                         if(CanWrite == false)
802                                 throw new NotSupportedException("The stream does not support writing");
803
804                         if(value < 0)
805                                 throw new ArgumentOutOfRangeException("value is less than 0");
806                         
807                         FlushBuffer ();
808
809                         MonoIOError error;
810
811                         MonoIO.SetLength (safeHandle, value, out error);
812                         if (error != MonoIOError.ERROR_SUCCESS) {
813                                 // don't leak the path information for isolated storage
814                                 throw MonoIO.GetException (GetSecureFileName (name), error);
815                         }
816
817                         if (Position > value)
818                                 Position = value;
819                 }
820
821                 public override void Flush ()
822                 {
823                         if (safeHandle.IsClosed)
824                                 throw new ObjectDisposedException ("Stream has been closed");
825
826                         FlushBuffer ();
827                 }
828
829                 public virtual void Flush (bool flushToDisk)
830                 {
831                         if (safeHandle.IsClosed)
832                                 throw new ObjectDisposedException ("Stream has been closed");
833
834                         FlushBuffer ();
835
836                         // This does the fsync
837                         if (flushToDisk){
838                                 MonoIOError error;
839                                 MonoIO.Flush (safeHandle, out error);
840                         }
841                 }
842
843                 public virtual void Lock (long position, long length)
844                 {
845                         if (safeHandle.IsClosed)
846                                 throw new ObjectDisposedException ("Stream has been closed");
847                         if (position < 0) {
848                                 throw new ArgumentOutOfRangeException ("position must not be negative");
849                         }
850                         if (length < 0) {
851                                 throw new ArgumentOutOfRangeException ("length must not be negative");
852                         }
853
854                         MonoIOError error;
855
856                         MonoIO.Lock (safeHandle, position, length, out error);
857                         if (error != MonoIOError.ERROR_SUCCESS) {
858                                 // don't leak the path information for isolated storage
859                                 throw MonoIO.GetException (GetSecureFileName (name), error);
860                         }
861                 }
862
863                 public virtual void Unlock (long position, long length)
864                 {
865                         if (safeHandle.IsClosed)
866                                 throw new ObjectDisposedException ("Stream has been closed");
867                         if (position < 0) {
868                                 throw new ArgumentOutOfRangeException ("position must not be negative");
869                         }
870                         if (length < 0) {
871                                 throw new ArgumentOutOfRangeException ("length must not be negative");
872                         }
873
874                         MonoIOError error;
875
876                         MonoIO.Unlock (safeHandle, position, length, out error);
877                         if (error != MonoIOError.ERROR_SUCCESS) {
878                                 // don't leak the path information for isolated storage
879                                 throw MonoIO.GetException (GetSecureFileName (name), error);
880                         }
881                 }
882
883                 // protected
884
885                 ~FileStream ()
886                 {
887                         Dispose (false);
888                 }
889
890                 protected override void Dispose (bool disposing)
891                 {
892                         Exception exc = null;
893                         if (safeHandle != null && !safeHandle.IsClosed) {
894                                 try {
895                                         // If the FileStream is in "exposed" status
896                                         // it means that we do not have a buffer(we write the data without buffering)
897                                         // therefor we don't and can't flush the buffer becouse we don't have one.
898                                         FlushBuffer ();
899                                 } catch (Exception e) {
900                                         exc = e;
901                                 }
902
903                                 if (owner) {
904                                         MonoIOError error;
905
906                                         MonoIO.Close (safeHandle.DangerousGetHandle (), out error);
907                                         if (error != MonoIOError.ERROR_SUCCESS) {
908                                                 // don't leak the path information for isolated storage
909                                                 throw MonoIO.GetException (GetSecureFileName (name), error);
910                                         }
911
912                                         safeHandle.DangerousRelease ();
913                                 }
914                         }
915
916                         canseek = false;
917                         access = 0;
918                         
919                         if (disposing && buf != null) {
920                                 if (buf.Length == DefaultBufferSize && buf_recycle == null) {
921                                         lock (buf_recycle_lock) {
922                                                 if (buf_recycle == null) {
923                                                         buf_recycle = buf;
924                                                 }
925                                         }
926                                 }
927                                 
928                                 buf = null;
929                                 GC.SuppressFinalize (this);
930                         }
931                         if (exc != null)
932                                 throw exc;
933                 }
934
935                 public FileSecurity GetAccessControl ()
936                 {
937                         if (safeHandle.IsClosed)
938                                 throw new ObjectDisposedException ("Stream has been closed");
939
940                         return new FileSecurity (SafeFileHandle,
941                                                  AccessControlSections.Owner |
942                                                  AccessControlSections.Group |
943                                                  AccessControlSections.Access);
944                 }
945                 
946                 public void SetAccessControl (FileSecurity fileSecurity)
947                 {
948                         if (safeHandle.IsClosed)
949                                 throw new ObjectDisposedException ("Stream has been closed");
950
951                         if (null == fileSecurity)
952                                 throw new ArgumentNullException ("fileSecurity");
953                                 
954                         fileSecurity.PersistModifications (SafeFileHandle);
955                 }
956
957                 public override Task FlushAsync (CancellationToken cancellationToken)
958                 {
959                         if (safeHandle.IsClosed)
960                                 throw new ObjectDisposedException ("Stream has been closed");
961
962                         return base.FlushAsync (cancellationToken);
963                 }
964
965                 public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
966                 {
967                         return base.ReadAsync (buffer, offset, count, cancellationToken);
968                 }
969
970                 public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
971                 {
972                         return base.WriteAsync (buffer, offset, count, cancellationToken);
973                 }
974
975                 // private.
976
977                 // ReadSegment, WriteSegment, FlushBuffer,
978                 // RefillBuffer and ReadData should only be called
979                 // when the Monitor lock is held, but these methods
980                 // grab it again just to be safe.
981
982                 private int ReadSegment (byte [] dest, int dest_offset, int count)
983                 {
984                         count = Math.Min (count, buf_length - buf_offset);
985                         
986                         if (count > 0) {
987                                 // Use the fastest method, all range checks has been done
988                                 Buffer.InternalBlockCopy (buf, buf_offset, dest, dest_offset, count);
989                                 buf_offset += count;
990                         }
991                         
992                         return count;
993                 }
994
995                 private int WriteSegment (byte [] src, int src_offset,
996                                           int count)
997                 {
998                         if (count > buf_size - buf_offset) {
999                                 count = buf_size - buf_offset;
1000                         }
1001                         
1002                         if (count > 0) {
1003                                 Buffer.BlockCopy (src, src_offset,
1004                                                   buf, buf_offset,
1005                                                   count);
1006                                 buf_offset += count;
1007                                 if (buf_offset > buf_length) {
1008                                         buf_length = buf_offset;
1009                                 }
1010                                 
1011                                 buf_dirty = true;
1012                         }
1013                         
1014                         return(count);
1015                 }
1016
1017                 void FlushBuffer ()
1018                 {
1019                         if (buf_dirty) {
1020 //                              if (st == null) {
1021                                         MonoIOError error;
1022
1023                                         if (CanSeek == true && !isExposed) {
1024                                                 MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
1025
1026                                                 if (error != MonoIOError.ERROR_SUCCESS) {
1027                                                         // don't leak the path information for isolated storage
1028                                                         throw MonoIO.GetException (GetSecureFileName (name), error);
1029                                                 }
1030                                         }
1031
1032                                         int wcount = buf_length;
1033                                         int offset = 0;
1034                                         while (wcount > 0){
1035                                                 int n = MonoIO.Write (safeHandle, buf, offset, buf_length, out error);
1036                                                 if (error != MonoIOError.ERROR_SUCCESS) {
1037                                                         // don't leak the path information for isolated storage
1038                                                         throw MonoIO.GetException (GetSecureFileName (name), error);
1039                                                 }
1040                                                 wcount -= n;
1041                                                 offset += n;
1042                                         }
1043 //                              } else {
1044 //                                      st.Write (buf, 0, buf_length);
1045 //                              }
1046                         }
1047
1048                         buf_start += buf_offset;
1049                         buf_offset = buf_length = 0;
1050                         buf_dirty = false;
1051                 }
1052
1053                 private void FlushBufferIfDirty ()
1054                 {
1055                         if (buf_dirty)
1056                                 FlushBuffer ();
1057                 }
1058
1059                 private void RefillBuffer ()
1060                 {
1061                         FlushBuffer ();
1062
1063                         buf_length = ReadData (safeHandle, buf, 0, buf_size);
1064                 }
1065
1066                 private int ReadData (SafeHandle safeHandle, byte[] buf, int offset,
1067                                       int count)
1068                 {
1069                         MonoIOError error;
1070                         int amount = 0;
1071
1072                         /* when async == true, if we get here we don't suport AIO or it's disabled
1073                          * and we're using the threadpool */
1074                         amount = MonoIO.Read (safeHandle, buf, offset, count, out error);
1075                         if (error == MonoIOError.ERROR_BROKEN_PIPE) {
1076                                 amount = 0; // might not be needed, but well...
1077                         } else if (error != MonoIOError.ERROR_SUCCESS) {
1078                                 // don't leak the path information for isolated storage
1079                                 throw MonoIO.GetException (GetSecureFileName (name), error);
1080                         }
1081                         
1082                         /* Check for read error */
1083                         if(amount == -1) {
1084                                 throw new IOException ();
1085                         }
1086                         
1087                         return(amount);
1088                 }
1089                                 
1090                 void InitBuffer (int size, bool isZeroSize)
1091                 {
1092                         if (isZeroSize) {
1093                                 size = 0;
1094                                 buf = new byte[1];
1095                         } else {
1096                                 if (size <= 0)
1097                                         throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
1098
1099                                 size = Math.Max (size, 8);
1100
1101                                 //
1102                                 // Instead of allocating a new default buffer use the
1103                                 // last one if there is any available
1104                                 //              
1105                                 if (size <= DefaultBufferSize && buf_recycle != null) {
1106                                         lock (buf_recycle_lock) {
1107                                                 if (buf_recycle != null) {
1108                                                         buf = buf_recycle;
1109                                                         buf_recycle = null;
1110                                                 }
1111                                         }
1112                                 }
1113
1114                                 if (buf == null)
1115                                         buf = new byte [size];
1116                                 else
1117                                         Array.Clear (buf, 0, size);
1118                         }
1119                                         
1120                         buf_size = size;
1121 //                      buf_start = 0;
1122 //                      buf_offset = buf_length = 0;
1123 //                      buf_dirty = false;
1124                 }
1125
1126                 private string GetSecureFileName (string filename)
1127                 {
1128                         return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
1129                 }
1130
1131                 private string GetSecureFileName (string filename, bool full)
1132                 {
1133                         return (anonymous) ? Path.GetFileName (filename) : 
1134                                 (full) ? Path.GetFullPath (filename) : filename;
1135                 }
1136
1137                 // fields
1138
1139                 internal const int DefaultBufferSize = 4096;
1140
1141                 // Input buffer ready for recycling                             
1142                 static byte[] buf_recycle;
1143                 static readonly object buf_recycle_lock = new object ();
1144
1145                 private byte [] buf;                    // the buffer
1146                 private string name = "[Unknown]";      // name of file.
1147
1148                 private SafeFileHandle safeHandle;
1149                 private bool isExposed;
1150
1151                 private long append_startpos;
1152
1153                 private FileAccess access;
1154                 private bool owner;
1155                 private bool async;
1156                 private bool canseek;
1157                 private bool anonymous;
1158                 private bool buf_dirty;                 // true if buffer has been written to
1159
1160                 private int buf_size;                   // capacity in bytes
1161                 private int buf_length;                 // number of valid bytes in buffer
1162                 private int buf_offset;                 // position of next byte
1163                 private long buf_start;                 // location of buffer in file
1164         }
1165 }