FileStream.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. //
  2. // System.IO.FileStream.cs
  3. //
  4. // Authors:
  5. // Dietmar Maurer ([email protected])
  6. // Dan Lewis ([email protected])
  7. // Gonzalo Paniagua Javier ([email protected])
  8. // Marek Safar ([email protected])
  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. using System.Collections;
  34. using System.Globalization;
  35. using System.Runtime.CompilerServices;
  36. using System.Runtime.InteropServices;
  37. using System.Runtime.Remoting.Messaging;
  38. using System.Security;
  39. using System.Security.AccessControl;
  40. using System.Security.Permissions;
  41. using System.Threading;
  42. using System.Threading.Tasks;
  43. using Microsoft.Win32.SafeHandles;
  44. namespace System.IO
  45. {
  46. [ComVisible (true)]
  47. public class FileStream : Stream
  48. {
  49. // construct from handle
  50. [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
  51. public FileStream (IntPtr handle, FileAccess access)
  52. : this (handle, access, true, DefaultBufferSize, false, false) {}
  53. [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
  54. public FileStream (IntPtr handle, FileAccess access, bool ownsHandle)
  55. : this (handle, access, ownsHandle, DefaultBufferSize, false, false) {}
  56. [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead")]
  57. public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
  58. : this (handle, access, ownsHandle, bufferSize, false, false) {}
  59. [Obsolete ("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead")]
  60. public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
  61. : this (handle, access, ownsHandle, bufferSize, isAsync, false) {}
  62. [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
  63. internal FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isConsoleWrapper)
  64. {
  65. if (handle == MonoIO.InvalidHandle)
  66. throw new ArgumentException ("handle", Locale.GetText ("Invalid."));
  67. Init (new SafeFileHandle (handle, false), access, ownsHandle, bufferSize, isAsync, isConsoleWrapper);
  68. }
  69. // construct from filename
  70. public FileStream (string path, FileMode mode)
  71. : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.Read, DefaultBufferSize, false, FileOptions.None)
  72. {
  73. }
  74. public FileStream (string path, FileMode mode, FileAccess access)
  75. : this (path, mode, access, access == FileAccess.Write ? FileShare.None : FileShare.Read, DefaultBufferSize, false, false)
  76. {
  77. }
  78. public FileStream (string path, FileMode mode, FileAccess access, FileShare share)
  79. : this (path, mode, access, share, DefaultBufferSize, false, FileOptions.None)
  80. {
  81. }
  82. public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
  83. : this (path, mode, access, share, bufferSize, false, FileOptions.None)
  84. {
  85. }
  86. public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
  87. : this (path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None)
  88. {
  89. }
  90. public FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
  91. : this (path, mode, access, share, bufferSize, false, options)
  92. {
  93. }
  94. public FileStream (SafeFileHandle handle, FileAccess access)
  95. :this(handle, access, DefaultBufferSize, false)
  96. {
  97. }
  98. public FileStream (SafeFileHandle handle, FileAccess access,
  99. int bufferSize)
  100. :this(handle, access, bufferSize, false)
  101. {
  102. }
  103. public FileStream (SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync)
  104. {
  105. Init (handle, access, false, bufferSize, isAsync, false);
  106. }
  107. [MonoLimitation ("This ignores the rights parameter")]
  108. public FileStream (string path, FileMode mode,
  109. FileSystemRights rights, FileShare share,
  110. int bufferSize, FileOptions options)
  111. : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
  112. {
  113. }
  114. [MonoLimitation ("This ignores the rights and fileSecurity parameters")]
  115. public FileStream (string path, FileMode mode,
  116. FileSystemRights rights, FileShare share,
  117. int bufferSize, FileOptions options,
  118. FileSecurity fileSecurity)
  119. : this (path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), share, bufferSize, false, options)
  120. {
  121. }
  122. internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy, bool useLongPath = false, bool checkHost = false)
  123. : this (path, mode, access, share, bufferSize, false, options)
  124. {
  125. }
  126. internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool isAsync, bool anonymous)
  127. : this (path, mode, access, share, bufferSize, anonymous, isAsync ? FileOptions.Asynchronous : FileOptions.None)
  128. {
  129. }
  130. internal FileStream (string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool anonymous, FileOptions options)
  131. {
  132. if (path == null) {
  133. throw new ArgumentNullException ("path");
  134. }
  135. if (path.Length == 0) {
  136. throw new ArgumentException ("Path is empty");
  137. }
  138. this.anonymous = anonymous;
  139. // ignore the Inheritable flag
  140. share &= ~FileShare.Inheritable;
  141. if (bufferSize <= 0)
  142. throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
  143. if (mode < FileMode.CreateNew || mode > FileMode.Append) {
  144. #if MOBILE
  145. if (anonymous)
  146. throw new ArgumentException ("mode", "Enum value was out of legal range.");
  147. else
  148. #endif
  149. throw new ArgumentOutOfRangeException ("mode", "Enum value was out of legal range.");
  150. }
  151. if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
  152. throw new ArgumentOutOfRangeException ("access", "Enum value was out of legal range.");
  153. }
  154. if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) {
  155. throw new ArgumentOutOfRangeException ("share", "Enum value was out of legal range.");
  156. }
  157. if (path.IndexOfAny (Path.InvalidPathChars) != -1) {
  158. throw new ArgumentException ("Name has invalid chars");
  159. }
  160. path = Path.InsecureGetFullPath (path);
  161. if (Directory.Exists (path)) {
  162. // don't leak the path information for isolated storage
  163. string msg = Locale.GetText ("Access to the path '{0}' is denied.");
  164. throw new UnauthorizedAccessException (String.Format (msg, GetSecureFileName (path, false)));
  165. }
  166. /* Append streams can't be read (see FileMode
  167. * docs)
  168. */
  169. if (mode==FileMode.Append &&
  170. (access&FileAccess.Read)==FileAccess.Read) {
  171. throw new ArgumentException("Append access can be requested only in write-only mode.");
  172. }
  173. if ((access & FileAccess.Write) == 0 &&
  174. (mode != FileMode.Open && mode != FileMode.OpenOrCreate)) {
  175. string msg = Locale.GetText ("Combining FileMode: {0} with " +
  176. "FileAccess: {1} is invalid.");
  177. throw new ArgumentException (string.Format (msg, access, mode));
  178. }
  179. SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
  180. string dname = Path.GetDirectoryName (path);
  181. if (dname.Length > 0) {
  182. string fp = Path.GetFullPath (dname);
  183. if (!Directory.Exists (fp)) {
  184. // don't leak the path information for isolated storage
  185. string msg = Locale.GetText ("Could not find a part of the path \"{0}\".");
  186. string fname = (anonymous) ? dname : Path.GetFullPath (path);
  187. throw new DirectoryNotFoundException (String.Format (msg, fname));
  188. }
  189. }
  190. if (access == FileAccess.Read && mode != FileMode.Create && mode != FileMode.OpenOrCreate &&
  191. mode != FileMode.CreateNew && !File.Exists (path)) {
  192. // don't leak the path information for isolated storage
  193. string msg = Locale.GetText ("Could not find file \"{0}\".");
  194. string fname = GetSecureFileName (path);
  195. throw new FileNotFoundException (String.Format (msg, fname), fname);
  196. }
  197. // IsolatedStorage needs to keep the Name property to the default "[Unknown]"
  198. if (!anonymous)
  199. this.name = path;
  200. // TODO: demand permissions
  201. MonoIOError error;
  202. var nativeHandle = MonoIO.Open (path, mode, access, share, options, out error);
  203. if (nativeHandle == MonoIO.InvalidHandle) {
  204. // don't leak the path information for isolated storage
  205. throw MonoIO.GetException (GetSecureFileName (path), error);
  206. }
  207. this.safeHandle = new SafeFileHandle (nativeHandle, false);
  208. this.access = access;
  209. this.owner = true;
  210. /* Can we open non-files by name? */
  211. if (MonoIO.GetFileType (safeHandle, out error) == MonoFileType.Disk) {
  212. this.canseek = true;
  213. this.async = (options & FileOptions.Asynchronous) != 0;
  214. } else {
  215. this.canseek = false;
  216. this.async = false;
  217. }
  218. if (access == FileAccess.Read && canseek && (bufferSize == DefaultBufferSize)) {
  219. /* Avoid allocating a large buffer for small files */
  220. long len = Length;
  221. if (bufferSize > len) {
  222. bufferSize = (int)(len < 1000 ? 1000 : len);
  223. }
  224. }
  225. InitBuffer (bufferSize, false);
  226. if (mode==FileMode.Append) {
  227. this.Seek (0, SeekOrigin.End);
  228. this.append_startpos=this.Position;
  229. } else {
  230. this.append_startpos=0;
  231. }
  232. }
  233. private void Init (SafeFileHandle safeHandle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync, bool isConsoleWrapper)
  234. {
  235. if (!isConsoleWrapper && safeHandle.IsInvalid)
  236. throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle");
  237. if (access < FileAccess.Read || access > FileAccess.ReadWrite)
  238. throw new ArgumentOutOfRangeException ("access");
  239. if (!isConsoleWrapper && bufferSize <= 0)
  240. throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
  241. MonoIOError error;
  242. MonoFileType ftype = MonoIO.GetFileType (safeHandle, out error);
  243. if (error != MonoIOError.ERROR_SUCCESS) {
  244. throw MonoIO.GetException (name, error);
  245. }
  246. if (ftype == MonoFileType.Unknown) {
  247. throw new IOException ("Invalid handle.");
  248. } else if (ftype == MonoFileType.Disk) {
  249. this.canseek = true;
  250. } else {
  251. this.canseek = false;
  252. }
  253. this.safeHandle = safeHandle;
  254. ExposeHandle ();
  255. this.access = access;
  256. this.owner = ownsHandle;
  257. this.async = isAsync;
  258. this.anonymous = false;
  259. if (canseek) {
  260. buf_start = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
  261. if (error != MonoIOError.ERROR_SUCCESS) {
  262. throw MonoIO.GetException (name, error);
  263. }
  264. }
  265. /* Can't set append mode */
  266. this.append_startpos=0;
  267. }
  268. // properties
  269. public override bool CanRead {
  270. get {
  271. return access == FileAccess.Read ||
  272. access == FileAccess.ReadWrite;
  273. }
  274. }
  275. public override bool CanWrite {
  276. get {
  277. return access == FileAccess.Write ||
  278. access == FileAccess.ReadWrite;
  279. }
  280. }
  281. public override bool CanSeek {
  282. get {
  283. return(canseek);
  284. }
  285. }
  286. public virtual bool IsAsync {
  287. get {
  288. return (async);
  289. }
  290. }
  291. public string Name {
  292. get {
  293. return name;
  294. }
  295. }
  296. public override long Length {
  297. get {
  298. if (safeHandle.IsClosed)
  299. throw new ObjectDisposedException ("Stream has been closed");
  300. if (!CanSeek)
  301. throw new NotSupportedException ("The stream does not support seeking");
  302. // Buffered data might change the length of the stream
  303. FlushBufferIfDirty ();
  304. MonoIOError error;
  305. long length = MonoIO.GetLength (safeHandle, out error);
  306. if (error != MonoIOError.ERROR_SUCCESS) {
  307. // don't leak the path information for isolated storage
  308. throw MonoIO.GetException (GetSecureFileName (name), error);
  309. }
  310. return(length);
  311. }
  312. }
  313. public override long Position {
  314. get {
  315. if (safeHandle.IsClosed)
  316. throw new ObjectDisposedException ("Stream has been closed");
  317. if (CanSeek == false)
  318. throw new NotSupportedException("The stream does not support seeking");
  319. if (!isExposed)
  320. return(buf_start + buf_offset);
  321. // If the handle was leaked outside we always ask the real handle
  322. MonoIOError error;
  323. long ret = MonoIO.Seek (safeHandle, 0, SeekOrigin.Current, out error);
  324. if (error != MonoIOError.ERROR_SUCCESS) {
  325. // don't leak the path information for isolated storage
  326. throw MonoIO.GetException (GetSecureFileName (name), error);
  327. }
  328. return ret;
  329. }
  330. set {
  331. if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
  332. Seek (value, SeekOrigin.Begin);
  333. }
  334. }
  335. [Obsolete ("Use SafeFileHandle instead")]
  336. public virtual IntPtr Handle {
  337. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  338. [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
  339. get {
  340. var handle = safeHandle.DangerousGetHandle ();
  341. if (!isExposed)
  342. ExposeHandle ();
  343. return handle;
  344. }
  345. }
  346. public virtual SafeFileHandle SafeFileHandle {
  347. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  348. [SecurityPermission (SecurityAction.InheritanceDemand, UnmanagedCode = true)]
  349. get {
  350. if (!isExposed)
  351. ExposeHandle ();
  352. return safeHandle;
  353. }
  354. }
  355. void ExposeHandle ()
  356. {
  357. isExposed = true;
  358. FlushBuffer ();
  359. InitBuffer (0, true);
  360. }
  361. // methods
  362. public override int ReadByte ()
  363. {
  364. if (safeHandle.IsClosed)
  365. throw new ObjectDisposedException ("Stream has been closed");
  366. if (!CanRead)
  367. throw new NotSupportedException ("Stream does not support reading");
  368. if (buf_size == 0) {
  369. int n = ReadData (safeHandle, buf, 0, 1);
  370. if (n == 0) return -1;
  371. else return buf[0];
  372. }
  373. else if (buf_offset >= buf_length) {
  374. RefillBuffer ();
  375. if (buf_length == 0)
  376. return -1;
  377. }
  378. return buf [buf_offset ++];
  379. }
  380. public override void WriteByte (byte value)
  381. {
  382. if (safeHandle.IsClosed)
  383. throw new ObjectDisposedException ("Stream has been closed");
  384. if (!CanWrite)
  385. throw new NotSupportedException ("Stream does not support writing");
  386. if (buf_offset == buf_size)
  387. FlushBuffer ();
  388. if (buf_size == 0) { // No buffering
  389. buf [0] = value;
  390. buf_dirty = true;
  391. buf_length = 1;
  392. FlushBuffer ();
  393. return;
  394. }
  395. buf [buf_offset ++] = value;
  396. if (buf_offset > buf_length)
  397. buf_length = buf_offset;
  398. buf_dirty = true;
  399. }
  400. public override int Read ([In,Out] byte[] array, int offset, int count)
  401. {
  402. if (safeHandle.IsClosed)
  403. throw new ObjectDisposedException ("Stream has been closed");
  404. if (array == null)
  405. throw new ArgumentNullException ("array");
  406. if (!CanRead)
  407. throw new NotSupportedException ("Stream does not support reading");
  408. int len = array.Length;
  409. if (offset < 0)
  410. throw new ArgumentOutOfRangeException ("offset", "< 0");
  411. if (count < 0)
  412. throw new ArgumentOutOfRangeException ("count", "< 0");
  413. if (offset > len)
  414. throw new ArgumentException ("destination offset is beyond array size");
  415. // reordered to avoid possible integer overflow
  416. if (offset > len - count)
  417. throw new ArgumentException ("Reading would overrun buffer");
  418. if (async) {
  419. IAsyncResult ares = BeginRead (array, offset, count, null, null);
  420. return EndRead (ares);
  421. }
  422. return ReadInternal (array, offset, count);
  423. }
  424. int ReadInternal (byte [] dest, int offset, int count)
  425. {
  426. int n = ReadSegment (dest, offset, count);
  427. if (n == count) {
  428. return count;
  429. }
  430. int copied = n;
  431. count -= n;
  432. if (count > buf_size) {
  433. /* Read as much as we can, up
  434. * to count bytes
  435. */
  436. FlushBuffer();
  437. n = ReadData (safeHandle, dest, offset+n, count);
  438. /* Make the next buffer read
  439. * start from the right place
  440. */
  441. buf_start += n;
  442. } else {
  443. RefillBuffer ();
  444. n = ReadSegment (dest, offset+copied, count);
  445. }
  446. return copied + n;
  447. }
  448. delegate int ReadDelegate (byte [] buffer, int offset, int count);
  449. public override IAsyncResult BeginRead (byte [] array, int offset, int numBytes,
  450. AsyncCallback userCallback, object stateObject)
  451. {
  452. if (safeHandle.IsClosed)
  453. throw new ObjectDisposedException ("Stream has been closed");
  454. if (!CanRead)
  455. throw new NotSupportedException ("This stream does not support reading");
  456. if (array == null)
  457. throw new ArgumentNullException ("array");
  458. if (numBytes < 0)
  459. throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
  460. if (offset < 0)
  461. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  462. // reordered to avoid possible integer overflow
  463. if (numBytes > array.Length - offset)
  464. throw new ArgumentException ("Buffer too small. numBytes/offset wrong.");
  465. if (!async)
  466. return base.BeginRead (array, offset, numBytes, userCallback, stateObject);
  467. ReadDelegate r = new ReadDelegate (ReadInternal);
  468. return r.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
  469. }
  470. public override int EndRead (IAsyncResult asyncResult)
  471. {
  472. if (asyncResult == null)
  473. throw new ArgumentNullException ("asyncResult");
  474. if (!async)
  475. return base.EndRead (asyncResult);
  476. AsyncResult ares = asyncResult as AsyncResult;
  477. if (ares == null)
  478. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  479. ReadDelegate r = ares.AsyncDelegate as ReadDelegate;
  480. if (r == null)
  481. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  482. return r.EndInvoke (asyncResult);
  483. }
  484. public override void Write (byte[] array, int offset, int count)
  485. {
  486. if (safeHandle.IsClosed)
  487. throw new ObjectDisposedException ("Stream has been closed");
  488. if (array == null)
  489. throw new ArgumentNullException ("array");
  490. if (offset < 0)
  491. throw new ArgumentOutOfRangeException ("offset", "< 0");
  492. if (count < 0)
  493. throw new ArgumentOutOfRangeException ("count", "< 0");
  494. // ordered to avoid possible integer overflow
  495. if (offset > array.Length - count)
  496. throw new ArgumentException ("Reading would overrun buffer");
  497. if (!CanWrite)
  498. throw new NotSupportedException ("Stream does not support writing");
  499. if (async) {
  500. IAsyncResult ares = BeginWrite (array, offset, count, null, null);
  501. EndWrite (ares);
  502. return;
  503. }
  504. WriteInternal (array, offset, count);
  505. }
  506. void WriteInternal (byte [] src, int offset, int count)
  507. {
  508. if (count > buf_size) {
  509. // shortcut for long writes
  510. MonoIOError error;
  511. FlushBuffer ();
  512. if (CanSeek && !isExposed) {
  513. MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
  514. if (error != MonoIOError.ERROR_SUCCESS)
  515. throw MonoIO.GetException (GetSecureFileName (name), error);
  516. }
  517. int wcount = count;
  518. while (wcount > 0){
  519. int n = MonoIO.Write (safeHandle, src, offset, wcount, out error);
  520. if (error != MonoIOError.ERROR_SUCCESS)
  521. throw MonoIO.GetException (GetSecureFileName (name), error);
  522. wcount -= n;
  523. offset += n;
  524. }
  525. buf_start += count;
  526. } else {
  527. int copied = 0;
  528. while (count > 0) {
  529. int n = WriteSegment (src, offset + copied, count);
  530. copied += n;
  531. count -= n;
  532. if (count == 0) {
  533. break;
  534. }
  535. FlushBuffer ();
  536. }
  537. }
  538. }
  539. delegate void WriteDelegate (byte [] buffer, int offset, int count);
  540. public override IAsyncResult BeginWrite (byte [] array, int offset, int numBytes,
  541. AsyncCallback userCallback, object stateObject)
  542. {
  543. if (safeHandle.IsClosed)
  544. throw new ObjectDisposedException ("Stream has been closed");
  545. if (!CanWrite)
  546. throw new NotSupportedException ("This stream does not support writing");
  547. if (array == null)
  548. throw new ArgumentNullException ("array");
  549. if (numBytes < 0)
  550. throw new ArgumentOutOfRangeException ("numBytes", "Must be >= 0");
  551. if (offset < 0)
  552. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  553. // reordered to avoid possible integer overflow
  554. if (numBytes > array.Length - offset)
  555. throw new ArgumentException ("array too small. numBytes/offset wrong.");
  556. if (!async)
  557. return base.BeginWrite (array, offset, numBytes, userCallback, stateObject);
  558. FileStreamAsyncResult result = new FileStreamAsyncResult (userCallback, stateObject);
  559. result.BytesRead = -1;
  560. result.Count = numBytes;
  561. result.OriginalCount = numBytes;
  562. /*
  563. if (buf_dirty) {
  564. MemoryStream ms = new MemoryStream ();
  565. FlushBuffer (ms);
  566. ms.Write (array, offset, numBytes);
  567. // Set arguments to new compounded buffer
  568. offset = 0;
  569. array = ms.ToArray ();
  570. numBytes = array.Length;
  571. }
  572. */
  573. WriteDelegate w = WriteInternal;
  574. return w.BeginInvoke (array, offset, numBytes, userCallback, stateObject);
  575. }
  576. public override void EndWrite (IAsyncResult asyncResult)
  577. {
  578. if (asyncResult == null)
  579. throw new ArgumentNullException ("asyncResult");
  580. if (!async) {
  581. base.EndWrite (asyncResult);
  582. return;
  583. }
  584. AsyncResult ares = asyncResult as AsyncResult;
  585. if (ares == null)
  586. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  587. WriteDelegate w = ares.AsyncDelegate as WriteDelegate;
  588. if (w == null)
  589. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  590. w.EndInvoke (asyncResult);
  591. return;
  592. }
  593. public override long Seek (long offset, SeekOrigin origin)
  594. {
  595. long pos;
  596. if (safeHandle.IsClosed)
  597. throw new ObjectDisposedException ("Stream has been closed");
  598. // make absolute
  599. if(CanSeek == false) {
  600. throw new NotSupportedException("The stream does not support seeking");
  601. }
  602. switch (origin) {
  603. case SeekOrigin.End:
  604. pos = Length + offset;
  605. break;
  606. case SeekOrigin.Current:
  607. pos = Position + offset;
  608. break;
  609. case SeekOrigin.Begin:
  610. pos = offset;
  611. break;
  612. default:
  613. throw new ArgumentException ("origin", "Invalid SeekOrigin");
  614. }
  615. if (pos < 0) {
  616. /* LAMESPEC: shouldn't this be
  617. * ArgumentOutOfRangeException?
  618. */
  619. throw new IOException("Attempted to Seek before the beginning of the stream");
  620. }
  621. if(pos < this.append_startpos) {
  622. /* More undocumented crap */
  623. throw new IOException("Can't seek back over pre-existing data in append mode");
  624. }
  625. FlushBuffer ();
  626. MonoIOError error;
  627. buf_start = MonoIO.Seek (safeHandle, pos, SeekOrigin.Begin, out error);
  628. if (error != MonoIOError.ERROR_SUCCESS) {
  629. // don't leak the path information for isolated storage
  630. throw MonoIO.GetException (GetSecureFileName (name), error);
  631. }
  632. return(buf_start);
  633. }
  634. public override void SetLength (long value)
  635. {
  636. if (safeHandle.IsClosed)
  637. throw new ObjectDisposedException ("Stream has been closed");
  638. if(CanSeek == false)
  639. throw new NotSupportedException("The stream does not support seeking");
  640. if(CanWrite == false)
  641. throw new NotSupportedException("The stream does not support writing");
  642. if(value < 0)
  643. throw new ArgumentOutOfRangeException("value is less than 0");
  644. FlushBuffer ();
  645. MonoIOError error;
  646. MonoIO.SetLength (safeHandle, value, out error);
  647. if (error != MonoIOError.ERROR_SUCCESS) {
  648. // don't leak the path information for isolated storage
  649. throw MonoIO.GetException (GetSecureFileName (name), error);
  650. }
  651. if (Position > value)
  652. Position = value;
  653. }
  654. public override void Flush ()
  655. {
  656. if (safeHandle.IsClosed)
  657. throw new ObjectDisposedException ("Stream has been closed");
  658. FlushBuffer ();
  659. }
  660. public virtual void Flush (bool flushToDisk)
  661. {
  662. if (safeHandle.IsClosed)
  663. throw new ObjectDisposedException ("Stream has been closed");
  664. FlushBuffer ();
  665. // This does the fsync
  666. if (flushToDisk){
  667. MonoIOError error;
  668. MonoIO.Flush (safeHandle, out error);
  669. }
  670. }
  671. public virtual void Lock (long position, long length)
  672. {
  673. if (safeHandle.IsClosed)
  674. throw new ObjectDisposedException ("Stream has been closed");
  675. if (position < 0) {
  676. throw new ArgumentOutOfRangeException ("position must not be negative");
  677. }
  678. if (length < 0) {
  679. throw new ArgumentOutOfRangeException ("length must not be negative");
  680. }
  681. MonoIOError error;
  682. MonoIO.Lock (safeHandle, position, length, out error);
  683. if (error != MonoIOError.ERROR_SUCCESS) {
  684. // don't leak the path information for isolated storage
  685. throw MonoIO.GetException (GetSecureFileName (name), error);
  686. }
  687. }
  688. public virtual void Unlock (long position, long length)
  689. {
  690. if (safeHandle.IsClosed)
  691. throw new ObjectDisposedException ("Stream has been closed");
  692. if (position < 0) {
  693. throw new ArgumentOutOfRangeException ("position must not be negative");
  694. }
  695. if (length < 0) {
  696. throw new ArgumentOutOfRangeException ("length must not be negative");
  697. }
  698. MonoIOError error;
  699. MonoIO.Unlock (safeHandle, position, length, out error);
  700. if (error != MonoIOError.ERROR_SUCCESS) {
  701. // don't leak the path information for isolated storage
  702. throw MonoIO.GetException (GetSecureFileName (name), error);
  703. }
  704. }
  705. // protected
  706. ~FileStream ()
  707. {
  708. Dispose (false);
  709. }
  710. protected override void Dispose (bool disposing)
  711. {
  712. Exception exc = null;
  713. if (safeHandle != null && !safeHandle.IsClosed) {
  714. try {
  715. // If the FileStream is in "exposed" status
  716. // it means that we do not have a buffer(we write the data without buffering)
  717. // therefor we don't and can't flush the buffer becouse we don't have one.
  718. FlushBuffer ();
  719. } catch (Exception e) {
  720. exc = e;
  721. }
  722. if (owner) {
  723. MonoIOError error;
  724. MonoIO.Close (safeHandle.DangerousGetHandle (), out error);
  725. if (error != MonoIOError.ERROR_SUCCESS) {
  726. // don't leak the path information for isolated storage
  727. throw MonoIO.GetException (GetSecureFileName (name), error);
  728. }
  729. safeHandle.DangerousRelease ();
  730. }
  731. }
  732. canseek = false;
  733. access = 0;
  734. if (disposing && buf != null) {
  735. if (buf.Length == DefaultBufferSize && buf_recycle == null) {
  736. lock (buf_recycle_lock) {
  737. if (buf_recycle == null) {
  738. buf_recycle = buf;
  739. }
  740. }
  741. }
  742. buf = null;
  743. GC.SuppressFinalize (this);
  744. }
  745. if (exc != null)
  746. throw exc;
  747. }
  748. public FileSecurity GetAccessControl ()
  749. {
  750. if (safeHandle.IsClosed)
  751. throw new ObjectDisposedException ("Stream has been closed");
  752. return new FileSecurity (SafeFileHandle,
  753. AccessControlSections.Owner |
  754. AccessControlSections.Group |
  755. AccessControlSections.Access);
  756. }
  757. public void SetAccessControl (FileSecurity fileSecurity)
  758. {
  759. if (safeHandle.IsClosed)
  760. throw new ObjectDisposedException ("Stream has been closed");
  761. if (null == fileSecurity)
  762. throw new ArgumentNullException ("fileSecurity");
  763. fileSecurity.PersistModifications (SafeFileHandle);
  764. }
  765. public override Task FlushAsync (CancellationToken cancellationToken)
  766. {
  767. if (safeHandle.IsClosed)
  768. throw new ObjectDisposedException ("Stream has been closed");
  769. return base.FlushAsync (cancellationToken);
  770. }
  771. public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  772. {
  773. return base.ReadAsync (buffer, offset, count, cancellationToken);
  774. }
  775. public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  776. {
  777. return base.WriteAsync (buffer, offset, count, cancellationToken);
  778. }
  779. // private.
  780. // ReadSegment, WriteSegment, FlushBuffer,
  781. // RefillBuffer and ReadData should only be called
  782. // when the Monitor lock is held, but these methods
  783. // grab it again just to be safe.
  784. private int ReadSegment (byte [] dest, int dest_offset, int count)
  785. {
  786. count = Math.Min (count, buf_length - buf_offset);
  787. if (count > 0) {
  788. // Use the fastest method, all range checks has been done
  789. Buffer.InternalBlockCopy (buf, buf_offset, dest, dest_offset, count);
  790. buf_offset += count;
  791. }
  792. return count;
  793. }
  794. private int WriteSegment (byte [] src, int src_offset,
  795. int count)
  796. {
  797. if (count > buf_size - buf_offset) {
  798. count = buf_size - buf_offset;
  799. }
  800. if (count > 0) {
  801. Buffer.BlockCopy (src, src_offset,
  802. buf, buf_offset,
  803. count);
  804. buf_offset += count;
  805. if (buf_offset > buf_length) {
  806. buf_length = buf_offset;
  807. }
  808. buf_dirty = true;
  809. }
  810. return(count);
  811. }
  812. void FlushBuffer ()
  813. {
  814. if (buf_dirty) {
  815. // if (st == null) {
  816. MonoIOError error;
  817. if (CanSeek == true && !isExposed) {
  818. MonoIO.Seek (safeHandle, buf_start, SeekOrigin.Begin, out error);
  819. if (error != MonoIOError.ERROR_SUCCESS) {
  820. // don't leak the path information for isolated storage
  821. throw MonoIO.GetException (GetSecureFileName (name), error);
  822. }
  823. }
  824. int wcount = buf_length;
  825. int offset = 0;
  826. while (wcount > 0){
  827. int n = MonoIO.Write (safeHandle, buf, offset, buf_length, out error);
  828. if (error != MonoIOError.ERROR_SUCCESS) {
  829. // don't leak the path information for isolated storage
  830. throw MonoIO.GetException (GetSecureFileName (name), error);
  831. }
  832. wcount -= n;
  833. offset += n;
  834. }
  835. // } else {
  836. // st.Write (buf, 0, buf_length);
  837. // }
  838. }
  839. buf_start += buf_offset;
  840. buf_offset = buf_length = 0;
  841. buf_dirty = false;
  842. }
  843. private void FlushBufferIfDirty ()
  844. {
  845. if (buf_dirty)
  846. FlushBuffer ();
  847. }
  848. private void RefillBuffer ()
  849. {
  850. FlushBuffer ();
  851. buf_length = ReadData (safeHandle, buf, 0, buf_size);
  852. }
  853. private int ReadData (SafeHandle safeHandle, byte[] buf, int offset,
  854. int count)
  855. {
  856. MonoIOError error;
  857. int amount = 0;
  858. /* when async == true, if we get here we don't suport AIO or it's disabled
  859. * and we're using the threadpool */
  860. amount = MonoIO.Read (safeHandle, buf, offset, count, out error);
  861. if (error == MonoIOError.ERROR_BROKEN_PIPE) {
  862. amount = 0; // might not be needed, but well...
  863. } else if (error != MonoIOError.ERROR_SUCCESS) {
  864. // don't leak the path information for isolated storage
  865. throw MonoIO.GetException (GetSecureFileName (name), error);
  866. }
  867. /* Check for read error */
  868. if(amount == -1) {
  869. throw new IOException ();
  870. }
  871. return(amount);
  872. }
  873. void InitBuffer (int size, bool isZeroSize)
  874. {
  875. if (isZeroSize) {
  876. size = 0;
  877. buf = new byte[1];
  878. } else {
  879. if (size <= 0)
  880. throw new ArgumentOutOfRangeException ("bufferSize", "Positive number required.");
  881. size = Math.Max (size, 8);
  882. //
  883. // Instead of allocating a new default buffer use the
  884. // last one if there is any available
  885. //
  886. if (size <= DefaultBufferSize && buf_recycle != null) {
  887. lock (buf_recycle_lock) {
  888. if (buf_recycle != null) {
  889. buf = buf_recycle;
  890. buf_recycle = null;
  891. }
  892. }
  893. }
  894. if (buf == null)
  895. buf = new byte [size];
  896. else
  897. Array.Clear (buf, 0, size);
  898. }
  899. buf_size = size;
  900. // buf_start = 0;
  901. // buf_offset = buf_length = 0;
  902. // buf_dirty = false;
  903. }
  904. private string GetSecureFileName (string filename)
  905. {
  906. return (anonymous) ? Path.GetFileName (filename) : Path.GetFullPath (filename);
  907. }
  908. private string GetSecureFileName (string filename, bool full)
  909. {
  910. return (anonymous) ? Path.GetFileName (filename) :
  911. (full) ? Path.GetFullPath (filename) : filename;
  912. }
  913. // fields
  914. internal const int DefaultBufferSize = 4096;
  915. // Input buffer ready for recycling
  916. static byte[] buf_recycle;
  917. static readonly object buf_recycle_lock = new object ();
  918. private byte [] buf; // the buffer
  919. private string name = "[Unknown]"; // name of file.
  920. private SafeFileHandle safeHandle;
  921. private bool isExposed;
  922. private long append_startpos;
  923. private FileAccess access;
  924. private bool owner;
  925. private bool async;
  926. private bool canseek;
  927. private bool anonymous;
  928. private bool buf_dirty; // true if buffer has been written to
  929. private int buf_size; // capacity in bytes
  930. private int buf_length; // number of valid bytes in buffer
  931. private int buf_offset; // position of next byte
  932. private long buf_start; // location of buffer in file
  933. }
  934. }