FileStream.cs 32 KB

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