RawDiskImage.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /* Copyright (C) 2014-2018 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using Utilities;
  11. namespace DiskAccessLibrary
  12. {
  13. public partial class RawDiskImage : DiskImage
  14. {
  15. public const int DefaultBytesPerSector = 512;
  16. private const FileOptions FILE_FLAG_NO_BUFFERING = (FileOptions)0x20000000;
  17. private const FileOptions FILE_FLAG_OVERLAPPED = (FileOptions)0x40000000;
  18. private bool m_isExclusiveLock;
  19. #if Win32
  20. private bool m_useOverlappedIO;
  21. #endif
  22. private Stream m_stream;
  23. private int m_bytesPerSector;
  24. private long m_size;
  25. /// <exception cref="System.IO.IOException"></exception>
  26. /// <exception cref="System.UnauthorizedAccessException"></exception>
  27. public RawDiskImage(string rawDiskImagePath) : this(rawDiskImagePath, false)
  28. {
  29. }
  30. /// <exception cref="System.IO.IOException"></exception>
  31. /// <exception cref="System.UnauthorizedAccessException"></exception>
  32. public RawDiskImage(string rawDiskImagePath, bool isReadOnly) : base(rawDiskImagePath, isReadOnly)
  33. {
  34. m_bytesPerSector = DetectBytesPerSector(rawDiskImagePath);
  35. m_size = new FileInfo(rawDiskImagePath).Length;
  36. }
  37. /// <exception cref="System.IO.IOException"></exception>
  38. /// <exception cref="System.UnauthorizedAccessException"></exception>
  39. public RawDiskImage(string rawDiskImagePath, int bytesPerSector) : this(rawDiskImagePath, bytesPerSector, false)
  40. {
  41. }
  42. /// <exception cref="System.IO.IOException"></exception>
  43. /// <exception cref="System.UnauthorizedAccessException"></exception>
  44. public RawDiskImage(string rawDiskImagePath, int bytesPerSector, bool isReadOnly) : base(rawDiskImagePath, isReadOnly)
  45. {
  46. m_bytesPerSector = bytesPerSector;
  47. m_size = new FileInfo(rawDiskImagePath).Length;
  48. }
  49. /// <exception cref="System.IO.IOException"></exception>
  50. public override bool ExclusiveLock()
  51. {
  52. if (!m_isExclusiveLock)
  53. {
  54. m_isExclusiveLock = true;
  55. m_stream = OpenFileStream();
  56. return true;
  57. }
  58. else
  59. {
  60. return false;
  61. }
  62. }
  63. #if Win32
  64. public override bool ExclusiveLock(bool useOverlappedIO)
  65. {
  66. if (!m_isExclusiveLock)
  67. {
  68. m_useOverlappedIO = useOverlappedIO;
  69. }
  70. return ExclusiveLock();
  71. }
  72. #endif
  73. public override bool ReleaseLock()
  74. {
  75. if (m_isExclusiveLock)
  76. {
  77. m_isExclusiveLock = false;
  78. m_stream.Close();
  79. return true;
  80. }
  81. else
  82. {
  83. return false;
  84. }
  85. }
  86. private Stream OpenFileStream()
  87. {
  88. FileAccess fileAccess = IsReadOnly ? FileAccess.Read : FileAccess.ReadWrite;
  89. // We should use noncached I/O operations to avoid excessive RAM usage.
  90. // Note: KB99794 provides information about FILE_FLAG_WRITE_THROUGH and FILE_FLAG_NO_BUFFERING.
  91. // We must avoid using buffered writes, using it will negatively affect the performance and reliability.
  92. // Note: once the file system write buffer is filled, Windows may delay any (buffer-dependent) pending write operations, which will create a deadlock.
  93. #if Win32
  94. uint flags = unchecked((uint)(FILE_FLAG_NO_BUFFERING | FileOptions.WriteThrough));
  95. if (m_useOverlappedIO)
  96. {
  97. flags |= (uint)FILE_FLAG_OVERLAPPED;
  98. }
  99. Microsoft.Win32.SafeHandles.SafeFileHandle handle = HandleUtils.GetFileHandle(this.Path, fileAccess, ShareMode.ReadWrite, flags);
  100. if (!handle.IsInvalid)
  101. {
  102. return new FileStreamEx(handle, fileAccess);
  103. }
  104. else
  105. {
  106. // we always release invalid handle
  107. int errorCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
  108. string message = String.Format("Failed to obtain file handle for file '{0}'.", this.Path);
  109. IOExceptionHelper.ThrowIOError(errorCode, message);
  110. return null; // this line will not be reached
  111. }
  112. #else
  113. return new FileStream(this.Path, FileMode.Open, fileAccess, FileShare.ReadWrite, m_bytesPerSector, FILE_FLAG_NO_BUFFERING | FileOptions.WriteThrough);
  114. #endif
  115. }
  116. /// <summary>
  117. /// Sector refers to physical disk sector, we can only read complete sectors
  118. /// </summary>
  119. public override byte[] ReadSectors(long sectorIndex, int sectorCount)
  120. {
  121. CheckBoundaries(sectorIndex, sectorCount);
  122. if (!m_isExclusiveLock)
  123. {
  124. m_stream = OpenFileStream();
  125. }
  126. long offset = sectorIndex * BytesPerSector;
  127. byte[] result = new byte[BytesPerSector * sectorCount];
  128. #if Win32
  129. if (m_useOverlappedIO)
  130. {
  131. ((FileStreamEx)m_stream).ReadOverlapped(result, 0, result.Length, offset);
  132. }
  133. else
  134. {
  135. #endif
  136. m_stream.Seek(offset, SeekOrigin.Begin);
  137. m_stream.Read(result, 0, BytesPerSector * sectorCount);
  138. #if Win32
  139. }
  140. #endif
  141. if (!m_isExclusiveLock)
  142. {
  143. m_stream.Close();
  144. }
  145. return result;
  146. }
  147. public override void WriteSectors(long sectorIndex, byte[] data)
  148. {
  149. if (IsReadOnly)
  150. {
  151. throw new UnauthorizedAccessException("Attempted to perform write on a readonly disk");
  152. }
  153. CheckBoundaries(sectorIndex, data.Length / this.BytesPerSector);
  154. if (!m_isExclusiveLock)
  155. {
  156. m_stream = OpenFileStream();
  157. }
  158. long offset = sectorIndex * BytesPerSector;
  159. #if Win32
  160. if (m_useOverlappedIO)
  161. {
  162. ((FileStreamEx)m_stream).WriteOverlapped(data, 0, data.Length, offset);
  163. }
  164. else
  165. {
  166. #endif
  167. m_stream.Seek(offset, SeekOrigin.Begin);
  168. m_stream.Write(data, 0, data.Length);
  169. #if Win32
  170. }
  171. #endif
  172. if (!m_isExclusiveLock)
  173. {
  174. m_stream.Close();
  175. }
  176. }
  177. /// <exception cref="System.IO.IOException"></exception>
  178. public override void Extend(long numberOfAdditionalBytes)
  179. {
  180. if (numberOfAdditionalBytes % this.BytesPerSector > 0)
  181. {
  182. throw new ArgumentException("numberOfAdditionalBytes must be a multiple of BytesPerSector");
  183. }
  184. #if Win32
  185. // calling AdjustTokenPrivileges and then immediately calling SetFileValidData will sometimes result in ERROR_PRIVILEGE_NOT_HELD.
  186. // We can work around the issue by obtaining the privilege before obtaining the handle.
  187. bool hasManageVolumePrivilege = SecurityUtils.ObtainManageVolumePrivilege();
  188. #endif
  189. if (!m_isExclusiveLock)
  190. {
  191. m_stream = OpenFileStream();
  192. }
  193. else
  194. {
  195. // Workaround for AdjustTokenPrivileges issue
  196. ReleaseLock();
  197. ExclusiveLock();
  198. }
  199. m_stream.SetLength(m_size + numberOfAdditionalBytes);
  200. m_size += numberOfAdditionalBytes;
  201. #if Win32
  202. if (hasManageVolumePrivilege)
  203. {
  204. try
  205. {
  206. ((FileStreamEx)m_stream).SetValidLength(m_size);
  207. }
  208. catch (IOException)
  209. {
  210. }
  211. }
  212. #endif
  213. if (!m_isExclusiveLock)
  214. {
  215. m_stream.Close();
  216. }
  217. }
  218. public override int BytesPerSector
  219. {
  220. get
  221. {
  222. return m_bytesPerSector;
  223. }
  224. }
  225. public override long Size
  226. {
  227. get
  228. {
  229. return m_size;
  230. }
  231. }
  232. /// <param name="size">In bytes</param>
  233. /// <exception cref="System.IO.IOException"></exception>
  234. /// <exception cref="System.UnauthorizedAccessException"></exception>
  235. public static RawDiskImage Create(string path, long size)
  236. {
  237. int bytesPerSector = DetectBytesPerSector(path);
  238. return Create(path, size, bytesPerSector);
  239. }
  240. /// <param name="size">In bytes</param>
  241. /// <exception cref="System.IO.IOException"></exception>
  242. /// <exception cref="System.UnauthorizedAccessException"></exception>
  243. internal static RawDiskImage Create(string path, long size, int bytesPerSector)
  244. {
  245. if (size % bytesPerSector > 0)
  246. {
  247. throw new ArgumentException("size must be a multiple of bytesPerSector");
  248. }
  249. #if Win32
  250. // calling AdjustTokenPrivileges and then immediately calling SetFileValidData will sometimes result in ERROR_PRIVILEGE_NOT_HELD.
  251. // We can work around the issue by obtaining the privilege before obtaining the handle.
  252. bool hasManageVolumePrivilege = SecurityUtils.ObtainManageVolumePrivilege();
  253. #endif
  254. FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
  255. try
  256. {
  257. stream.SetLength(size);
  258. }
  259. catch (IOException)
  260. {
  261. stream.Close();
  262. try
  263. {
  264. // Delete the incomplete file
  265. File.Delete(path);
  266. }
  267. catch (IOException)
  268. {
  269. }
  270. throw;
  271. }
  272. #if Win32
  273. if (hasManageVolumePrivilege)
  274. {
  275. try
  276. {
  277. FileStreamUtils.SetValidLength(stream, size);
  278. }
  279. catch (IOException)
  280. {
  281. }
  282. }
  283. #endif
  284. stream.Close();
  285. return new RawDiskImage(path, bytesPerSector);
  286. }
  287. public static int DetectBytesPerSector(string path)
  288. {
  289. FileInfo info = new FileInfo(path);
  290. string[] components = info.Name.Split('.');
  291. if (components.Length >= 3) // file.512.img
  292. {
  293. string bytesPerSectorString = components[components.Length - 2];
  294. int bytesPerSector = Conversion.ToInt32(bytesPerSectorString, DefaultBytesPerSector);
  295. return bytesPerSector;
  296. }
  297. else
  298. {
  299. return DefaultBytesPerSector;
  300. }
  301. }
  302. }
  303. }