private void write2(string disk, byte[] header, byte[] sectors) { string ldrive = "PhysicalDrive" + disk; var diskGeometry = DiskGeometry.FromDevice(@"\\.\" + ldrive.Replace("\\", "")); uint sector = diskGeometry.BytesPerSector; long i = 0; try { FileStream fs = new FileStream(CreateFile(@"\\.\" + ldrive.Replace("\\", ""), FileAccess.ReadWrite, FileShare.ReadWrite, 0, FileMode.Open, 0, IntPtr.Zero), FileAccess.ReadWrite); byte[] temp = new byte[sector]; while (i < 34 && !variables.escapeloop) { Buffer.BlockCopy(sectors, (int)i * 0x200, temp, 0, 0x200); fs.Write(temp, 0, (int)sector); i++; } fs.Seek(diskGeometry.MaximumLinearAddress - 0x200, SeekOrigin.Begin); fs.Write(header, 0, 0x200); fs.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); if (variables.debugme) { Console.WriteLine(ex.ToString()); } } }
/// <summary> /// Creates the VHD footer. /// </summary> /// <param name="blocks">The blocks.</param> /// <param name="timeStamp">The time stamp.</param> /// <param name="guid">The GUID.</param> /// <param name="diskGeometry">The disk geometry.</param> /// <returns></returns> public static byte[] CreateFooter(ulong blocks, uint timeStamp, byte[] guid, DiskGeometry diskGeometry) { var binaryFooter = new Mosa.ClassLib.BinaryFormat(512); binaryFooter.SetString(VHDFooterOffset.Cookie, "conectix", 8); binaryFooter.SetUIntReversed(VHDFooterOffset.Features, 0x00000002); binaryFooter.SetUIntReversed(VHDFooterOffset.FileFormatVersion, 0x00010000); binaryFooter.SetULong(VHDFooterOffset.DataOffset, ~(ulong)0); binaryFooter.SetUIntReversed(VHDFooterOffset.TimeStamp, timeStamp); binaryFooter.SetString(VHDFooterOffset.CreatorApplication, "MOSA", 4); binaryFooter.SetUIntReversed(VHDFooterOffset.CreatorVersion, 0x00050000); binaryFooter.SetUIntReversed(VHDFooterOffset.CreatorHostOS, 0x5769326B); // Windows binaryFooter.SetULongReversed(VHDFooterOffset.OriginalSize, blocks * 512); binaryFooter.SetULongReversed(VHDFooterOffset.CurrentSize, blocks * 512); binaryFooter.SetUShortReversed(VHDFooterOffset.DiskGeometryCylinders, diskGeometry.Cylinders); binaryFooter.SetByte(VHDFooterOffset.DiskGeometryHeads, diskGeometry.Heads); binaryFooter.SetByte(VHDFooterOffset.DiskGeometrySectors, (byte)diskGeometry.SectorsPerTrack); binaryFooter.SetUIntReversed(VHDFooterOffset.DiskType, 0x02); // Fixed disk binaryFooter.SetUIntReversed(VHDFooterOffset.Checksum, 0x00); binaryFooter.SetBytes(VHDFooterOffset.UniqueId, guid, 0, 16); binaryFooter.SetByte(VHDFooterOffset.SavedState, 0x00); // No saved state uint checksum = 0; for (uint index = 0; index < 512; index++) checksum += binaryFooter.Data[index]; binaryFooter.SetUIntReversed(VHDFooterOffset.Checksum, ~checksum); return binaryFooter.Data; }
/// <summary> /// Creates the VHD footer. /// </summary> /// <param name="blocks">The blocks.</param> /// <param name="timeStamp">The time stamp.</param> /// <param name="guid">The GUID.</param> /// <param name="diskGeometry">The disk geometry.</param> /// <returns></returns> static public byte[] CreateFooter(ulong blocks, uint timeStamp, byte[] guid, DiskGeometry diskGeometry) { var binaryFooter = new DataBlock(512); binaryFooter.SetString(VHDFooterOffset.Cookie, "conectix", 8); binaryFooter.SetUIntReversed(VHDFooterOffset.Features, 0x00000002); binaryFooter.SetUIntReversed(VHDFooterOffset.FileFormatVersion, 0x00010000); binaryFooter.SetULong(VHDFooterOffset.DataOffset, ~(ulong)0); binaryFooter.SetUIntReversed(VHDFooterOffset.TimeStamp, timeStamp); binaryFooter.SetString(VHDFooterOffset.CreatorApplication, "MOSA", 4); binaryFooter.SetUIntReversed(VHDFooterOffset.CreatorVersion, 0x00050000); binaryFooter.SetUIntReversed(VHDFooterOffset.CreatorHostOS, 0x5769326B); // Windows binaryFooter.SetULongReversed(VHDFooterOffset.OriginalSize, blocks * 512); binaryFooter.SetULongReversed(VHDFooterOffset.CurrentSize, blocks * 512); binaryFooter.SetUShortReversed(VHDFooterOffset.DiskGeometryCylinders, diskGeometry.Cylinders); binaryFooter.SetByte(VHDFooterOffset.DiskGeometryHeads, diskGeometry.Heads); binaryFooter.SetByte(VHDFooterOffset.DiskGeometrySectors, (byte)diskGeometry.SectorsPerTrack); binaryFooter.SetUIntReversed(VHDFooterOffset.DiskType, 0x02); // Fixed disk binaryFooter.SetUIntReversed(VHDFooterOffset.Checksum, 0x00); binaryFooter.SetBytes(VHDFooterOffset.UniqueId, guid, 0, 16); binaryFooter.SetByte(VHDFooterOffset.SavedState, 0x00); // No saved state uint checksum = 0; for (uint index = 0; index < 512; index++) { checksum += binaryFooter.Data[index]; } binaryFooter.SetUIntReversed(VHDFooterOffset.Checksum, ~checksum); return(binaryFooter.Data); }
public static VhdFooter CreateFixedDiskFooter(long virtualSize) { var helper = new AttributeHelper <VhdFooter>(); var footer = new VhdFooter(); var reservedAttribute = helper.GetAttribute(() => footer.Reserved); footer.Cookie = VhdCookie.CreateFooterCookie(); footer.Features = VhdFeature.Reserved; footer.FileFormatVersion = VhdFileFormatVersion.DefaultFileFormatVersion; footer.HeaderOffset = VhdConstants.VHD_NO_DATA_LONG; footer.TimeStamp = DateTime.UtcNow; footer.CreatorApplication = WindowsAzureCreatorApplicationName; footer.CreatorVersion = VhdCreatorVersion.CSUP2011; footer.CreatorHostOsType = HostOsType.Windows; footer.PhsyicalSize = virtualSize; footer.VirtualSize = virtualSize; footer.DiskGeometry = DiskGeometry.CreateFromVirtualSize(virtualSize); footer.DiskType = DiskType.Fixed; footer.UniqueId = Guid.NewGuid(); footer.SavedState = false; footer.Reserved = new byte[reservedAttribute.Size]; var footerSerializer = new VhdFooterSerializer(footer); var byteArray = footerSerializer.ToByteArray(); using (var memoryStream = new MemoryStream(byteArray)) { var binaryReader = new BinaryReader(memoryStream); var vhdDataReader = new VhdDataReader(binaryReader); var footerFactory = new VhdFooterFactory(vhdDataReader); var vhdFooter = footerFactory.CreateFooter(); return(vhdFooter); } }
/// <summary> /// Creates the header. /// </summary> /// <param name="blocks">The blocks.</param> /// <param name="guid">The GUID.</param> /// <param name="lastSnapGuid">The last snap GUID.</param> /// <param name="diskGeometry">The disk geometry.</param> /// <returns></returns> public static byte[] CreateHeader(uint blocks, byte[] guid, byte[] lastSnapGuid, DiskGeometry diskGeometry) { var binaryHeader = new Mosa.ClassLib.BinaryFormat(512); binaryHeader.SetString(VHIHeaderOffset.HeaderText, HeaderText, (uint)HeaderText.Length); binaryHeader.SetByte(VHIHeaderOffset.HeaderText + 0x25, 0x0A); binaryHeader.SetUInt(VHIHeaderOffset.ImageSignature, 0xBEda107F); binaryHeader.SetUInt(VHIHeaderOffset.Version, 0x00010001); binaryHeader.SetUInt(VHIHeaderOffset.HeaderSize, 0x180); binaryHeader.SetUInt(VHIHeaderOffset.ImageType, 0x02); binaryHeader.SetUInt(VHIHeaderOffset.ImageFlags, 0x00); binaryHeader.SetUInt(VHIHeaderOffset.OffsetBlocks, 0x200); binaryHeader.SetUInt(VHIHeaderOffset.OffsetData, 0x400); binaryHeader.SetUInt(VHIHeaderOffset.DiskGeometryCylinders, 0); // diskGeometry.Cylinders); binaryHeader.SetUInt(VHIHeaderOffset.DiskGeometryHeads, 0); // diskGeometry.Heads); binaryHeader.SetUInt(VHIHeaderOffset.DiskGeometrySectors, 0); // diskGeometry.SectorsPerTrack); binaryHeader.SetUInt(VHIHeaderOffset.SectorSize, 512); binaryHeader.SetULong(VHIHeaderOffset.DiskSize, blocks * 512); binaryHeader.SetUInt(VHIHeaderOffset.BlockSize, 0x100000); binaryHeader.SetUInt(VHIHeaderOffset.BlockExtraData, 0); binaryHeader.SetUInt(VHIHeaderOffset.BlocksInHDD, (blocks * 512) / 0x100000); binaryHeader.SetUInt(VHIHeaderOffset.BlocksAllocated, (blocks * 512) / 0x100000); binaryHeader.SetBytes(VHIHeaderOffset.UUID, guid, 0, 16); binaryHeader.SetBytes(VHIHeaderOffset.UUIDLastSnap, lastSnapGuid, 0, 16); return binaryHeader.Data; }
private void write2(string filename) { if (String.IsNullOrEmpty(filename)) { return; } if (listView1.SelectedItems.Count == 0) { return; } string ldrive = listView1.SelectedItems[0].SubItems[1].Text; if (listView1.SelectedItems[0].SubItems[2].Text != "Removable") { Console.WriteLine("Must be a removable type"); return; } if (MessageBox.Show("You are about to write to " + ldrive + ". Continue?", "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) { return; } var diskGeometry = DiskGeometry.FromDevice(@"\\.\" + ldrive.Replace("\\", "")); uint track = diskGeometry.BytesPerSector * (diskGeometry.Sector + 1); long tracks = diskGeometry.DiskSize / track; long i = 0; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); try { Console.WriteLine("Writing to {0} from {1}", ldrive, filename); FileStream fs = new FileStream(CreateFile(@"\\.\" + ldrive.Replace("\\", ""), FileAccess.ReadWrite, FileShare.ReadWrite, 0, FileMode.Open, 0, IntPtr.Zero), FileAccess.ReadWrite); FileStream fw = new FileStream(filename, FileMode.OpenOrCreate); tracks = (fw.Length / track); byte[] temp = new byte[track]; while (i < tracks && !variables.escapeloop) { UpdateProgres((int)((i * 100) / tracks)); i++; fw.Read(temp, 0, (int)track); fs.Write(temp, 0, (int)track); } fs.Close(); fw.Close(); UpdateProgres(100); stopwatch.Stop(); Console.WriteLine("Done!"); Console.WriteLine("in {0}:{1:D2}:{2} min:sec:ms", stopwatch.Elapsed.Minutes + (stopwatch.Elapsed.Hours * 60), stopwatch.Elapsed.Seconds, stopwatch.Elapsed.Milliseconds); } catch (Exception ex) { Console.WriteLine(ex.Message); if (variables.debugme) { Console.WriteLine(ex.ToString()); } } }
internal static long TranslateGeometryToSize(DiskGeometry gem) { Main.SendDebug(string.Format("Cylinders: {0}", gem.Cylinders)); Main.SendDebug(string.Format("Tracks: {0}", gem.TracksPerCylinder)); Main.SendDebug(string.Format("Sectors: {0}", gem.SectorsPerTrack)); Main.SendDebug(string.Format("Bytes: {0}", gem.BytesPerSector)); Main.SendDebug(string.Format("DiskSize: {0}", gem.DiskSize)); return(gem.DiskSize); }
public static long GetDriveSize(SafeHandle sfh) { DiskGeometry geo = new DiskGeometry(); uint returnedBytes; DeviceIoControl(sfh, 0x70000, IntPtr.Zero, 0, ref geo, (uint)Marshal.SizeOf(typeof(DiskGeometry)), out returnedBytes, IntPtr.Zero); return(geo.DiskSize); }
public DataReceiver(int diskId) { DiskId = diskId; var diskGeometry = DiskGeometry.FromDevice(@"\\.\PHYSICALDRIVE" + DiskId.ToString()); BytesPerSector = (int)diskGeometry.BytesPerSector; SourceLength = diskGeometry.DiskSize; TotalSectors = SourceLength / BytesPerSector; Open(); }
private DiskGeometry ReadDiskGeometry(VhdPropertyAttribute attribute) { long offset = GetFooterOffset() + attribute.Offset; var attributeHelper = new AttributeHelper <DiskGeometry>(); var diskGeometry = new DiskGeometry(); diskGeometry.Cylinder = dataReader.ReadInt16(offset + attributeHelper.GetAttribute(() => diskGeometry.Cylinder).Offset); diskGeometry.Heads = dataReader.ReadByte(offset + attributeHelper.GetAttribute(() => diskGeometry.Heads).Offset); diskGeometry.Sectors = dataReader.ReadByte(offset + attributeHelper.GetAttribute(() => diskGeometry.Sectors).Offset); return(diskGeometry); }
/// <summary> /// Computes the CHS given a disk geometry /// </summary> /// <param name="diskGeometry">The disk geometry.</param> /// <param name="lba">The lba.</param> public void SetCHS(DiskGeometry diskGeometry, ulong lba) { if ((lba / (uint)(diskGeometry.SectorsPerTrack * diskGeometry.Heads) > 1023)) lba = (uint)diskGeometry.Heads * diskGeometry.SectorsPerTrack * 1024 - 1; Sector = (ushort)(lba % diskGeometry.SectorsPerTrack + 1); lba /= diskGeometry.SectorsPerTrack; Head = (byte)(lba % diskGeometry.Heads); lba /= diskGeometry.Heads; Cylinder = (ushort)(lba & 0xFF); Sector |= (ushort)((lba >> 2) & 0xC0); }
/// <summary> /// Writes the master boot block. /// </summary> /// <returns></returns> public bool Write() { if (!diskDevice.CanWrite) { return(false); } var masterboot = new DataBlock(512); masterboot.SetUInt(MBR.DiskSignature, diskSignature); masterboot.SetUShort(MBR.MBRSignature, MBRConstant.MBRSignature); if (code != null) { for (uint index = 0; ((index < MBRConstant.CodeAreaSize) && (index < code.Length)); index++) { masterboot.SetByte(index, code[index]); } } for (uint index = 0; index < MaxMBRPartitions; index++) { if (Partitions[index].TotalBlocks != 0) { uint offset = MBR.FirstPartition + (index * 16); masterboot.SetByte(offset + PartitionRecord.Status, (byte)(Partitions[index].Bootable ? 0x80 : 0x00)); masterboot.SetByte(offset + PartitionRecord.PartitionType, Partitions[index].PartitionType); masterboot.SetUInt(offset + PartitionRecord.LBA, Partitions[index].StartLBA); masterboot.SetUInt(offset + PartitionRecord.Sectors, Partitions[index].TotalBlocks); var diskGeometry = new DiskGeometry(); diskGeometry.GuessGeometry(diskDevice.TotalBlocks); var chsStart = new CHS(); var chsEnd = new CHS(); chsStart.SetCHS(diskGeometry, Partitions[index].StartLBA); chsEnd.SetCHS(diskGeometry, Partitions[index].StartLBA + Partitions[index].TotalBlocks - 1); masterboot.SetByte(offset + PartitionRecord.FirstCRS, chsStart.Head); masterboot.SetByte(offset + PartitionRecord.FirstCRS + 1, (byte)((chsStart.Sector & 0x3F) | ((chsStart.Cylinder >> 8) & 0x03))); masterboot.SetByte(offset + PartitionRecord.FirstCRS + 2, (byte)(chsStart.Cylinder & 0xFF)); masterboot.SetByte(offset + PartitionRecord.LastCRS, chsEnd.Head); masterboot.SetByte(offset + PartitionRecord.LastCRS + 1, (byte)((chsEnd.Sector & 0x3F) | ((chsEnd.Cylinder >> 8) & 0x03))); masterboot.SetByte(offset + PartitionRecord.LastCRS + 2, (byte)(chsEnd.Cylinder & 0xFF)); } } diskDevice.WriteBlock(0, 1, masterboot.Data); return(true); }
/// <summary> /// Computes the CHS given a disk geometry /// </summary> /// <param name="diskGeometry">The disk geometry.</param> /// <param name="lba">The lba.</param> public void SetCHS(DiskGeometry diskGeometry, ulong lba) { if ((lba / (uint)(diskGeometry.SectorsPerTrack * diskGeometry.Heads) > 1023)) { lba = (uint)diskGeometry.Heads * diskGeometry.SectorsPerTrack * 1024 - 1; } Sector = (ushort)(lba % diskGeometry.SectorsPerTrack + 1); lba /= diskGeometry.SectorsPerTrack; Head = (byte)(lba % diskGeometry.Heads); lba /= diskGeometry.Heads; Cylinder = (ushort)(lba & 0xFF); Sector |= (ushort)((lba >> 2) & 0xC0); }
private void QueryDiskGeometry(XmlElement pathNode, IOSVolumeDeviceInfo vinfo, SafeHandle hDevice) { DiskGeometry diskGeo = QueryApi(pathNode, "DiskGeometry", vinfo, () => { return(vinfo.GetDiskGeometry(hDevice)); }, out XmlElement geoNode); if (diskGeo == null) { return; } WriteApiResult(geoNode, "MediaType", (int)diskGeo.MediaType); WriteApiResult(geoNode, "Cylinders", diskGeo.Cylinders); WriteApiResult(geoNode, "TracksPerCylinder", diskGeo.TracksPerCylinder); WriteApiResult(geoNode, "SectorsPerTrack", diskGeo.SectorsPerTrack); WriteApiResult(geoNode, "BytesPerSector", diskGeo.BytesPerSector); }
public static void TestMethod() { var diskGeometry = DiskGeometry.FromDevice(@"\\.\PhysicalDrive3"); var cubicAddress = diskGeometry.MaximumCubicAddress; Console.WriteLine(" media type: {0}", diskGeometry.MediaTypeName); Console.WriteLine(); Console.WriteLine("maximum linear address: {0}", diskGeometry.MaximumLinearAddress); Console.WriteLine(" last cylinder number: {0}", cubicAddress.Cylinder); Console.WriteLine(" last head number: {0}", cubicAddress.Head); Console.WriteLine(" last sector number: {0}", cubicAddress.Sector); Console.WriteLine(); Console.WriteLine(" cylinders: {0}", diskGeometry.Cylinder); Console.WriteLine(" tracks per cylinder: {0}", diskGeometry.Head); Console.WriteLine(" sectors per track: {0}", diskGeometry.Sector); Console.WriteLine(); Console.WriteLine(" bytes per sector: {0}", diskGeometry.BytesPerSector); Console.WriteLine(" bytes per cylinder: {0}", diskGeometry.BytesPerCylinder); Console.WriteLine(" total disk space: {0}", diskGeometry.DiskSize); }
public static List <DiskInfo> GetDiskInfoList() { List <DiskInfo> diskInfoList = new List <DiskInfo>(); try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive"); foreach (ManagementObject queryObj in searcher.Get()) { var id = queryObj["DeviceID"]; var diskGeometry = DiskGeometry.FromDevice(id.ToString()); var model = queryObj["Model"]; var sectors = diskGeometry.MaximumLinearAddress; var size = queryObj["Size"]; var bytesPerS = queryObj["BytesPerSector"]; if (size == null || model == null || sectors == null || id == null || bytesPerS == null) { continue; } long sizeL = long.Parse(size.ToString()) / 1024 / 1024 / 1024 + 1; char last = id.ToString()[id.ToString().Length - 1]; int diskNum = int.Parse(last.ToString()); DiskInfo diskInfo = new DiskInfo(diskNum, int.Parse(bytesPerS.ToString()), model.ToString(), long.Parse(sectors.ToString()), sizeL); diskInfoList.Add(diskInfo); } diskInfoList.Sort((s1, s2) => s1.ID.CompareTo(s2.ID)); } catch (ManagementException) { return(diskInfoList); } return(diskInfoList); }
private bool read(string disk, out byte[] sectors) { sectors = null; string ldrive = "PhysicalDrive" + disk; Console.WriteLine(ldrive); var diskGeometry = DiskGeometry.FromDevice(@"\\.\" + ldrive.Replace("\\", "")); if (diskGeometry == null) { Console.WriteLine("Failed to get DiskGeometry."); return(false); } uint track = diskGeometry.BytesPerSector; sectors = new byte[diskGeometry.BytesPerSector * 34]; long i = 0; try { Console.WriteLine("Reading from {0}", ldrive); SafeFileHandle sfh = CreateFile(@"\\.\" + ldrive.Replace("\\", ""), FileAccess.Read, FileShare.Read, 0, FileMode.Open, 0, IntPtr.Zero); FileStream fs = new FileStream(sfh, FileAccess.Read); byte[] temp = new byte[track]; while (i < 34 && !variables.escapeloop) { fs.Read(temp, 0, (int)track); Buffer.BlockCopy(temp, 0, sectors, (int)(i * track), (int)track); i++; } CloseHandle(sfh); fs.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString() + i); return(false); } return(true); }
private IEnumerable <CompletionPort> ReadDiskGeometryAsync(AsyncMachine <DiskGeometry> machine, VhdPropertyAttribute attribute) { long offset = GetFooterOffset() + attribute.Offset; var attributeHelper = new AttributeHelper <DiskGeometry>(); var diskGeometry = new DiskGeometry(); dataReader.BeginReadInt16(offset + attributeHelper.GetAttribute(() => diskGeometry.Cylinder).Offset, machine.CompletionCallback, null); yield return(CompletionPort.SingleOperation); diskGeometry.Cylinder = dataReader.EndReadInt16(machine.CompletionResult); dataReader.BeginReadByte(offset + attributeHelper.GetAttribute(() => diskGeometry.Heads).Offset, machine.CompletionCallback, null); yield return(CompletionPort.SingleOperation); diskGeometry.Heads = dataReader.EndReadByte(machine.CompletionResult); dataReader.BeginReadByte(offset + attributeHelper.GetAttribute(() => diskGeometry.Sectors).Offset, machine.CompletionCallback, null); yield return(CompletionPort.SingleOperation); diskGeometry.Sectors = dataReader.EndReadByte(machine.CompletionResult); machine.ParameterValue = diskGeometry; }
/// <summary> /// Creates the header. /// </summary> /// <param name="blocks">The blocks.</param> /// <param name="guid">The GUID.</param> /// <param name="lastSnapGuid">The last snap GUID.</param> /// <param name="diskGeometry">The disk geometry.</param> /// <returns></returns> static public byte[] CreateHeader(uint blocks, byte[] guid, byte[] lastSnapGuid, DiskGeometry diskGeometry) { var binaryHeader = new DataBlock(512); binaryHeader.SetString(VHIHeaderOffset.HeaderText, HeaderText, (uint)HeaderText.Length); binaryHeader.SetByte(VHIHeaderOffset.HeaderText + 0x25, 0x0A); binaryHeader.SetUInt(VHIHeaderOffset.ImageSignature, 0xBEda107F); binaryHeader.SetUInt(VHIHeaderOffset.Version, 0x00010001); binaryHeader.SetUInt(VHIHeaderOffset.HeaderSize, 0x180); binaryHeader.SetUInt(VHIHeaderOffset.ImageType, 0x02); binaryHeader.SetUInt(VHIHeaderOffset.ImageFlags, 0x00); binaryHeader.SetUInt(VHIHeaderOffset.OffsetBlocks, 0x200); binaryHeader.SetUInt(VHIHeaderOffset.OffsetData, 0x400); binaryHeader.SetUInt(VHIHeaderOffset.DiskGeometryCylinders, 0); // diskGeometry.Cylinders); binaryHeader.SetUInt(VHIHeaderOffset.DiskGeometryHeads, 0); // diskGeometry.Heads); binaryHeader.SetUInt(VHIHeaderOffset.DiskGeometrySectors, 0); // diskGeometry.SectorsPerTrack); binaryHeader.SetUInt(VHIHeaderOffset.SectorSize, 512); binaryHeader.SetULong(VHIHeaderOffset.DiskSize, blocks * 512); binaryHeader.SetUInt(VHIHeaderOffset.BlockSize, 0x100000); binaryHeader.SetUInt(VHIHeaderOffset.BlockExtraData, 0); binaryHeader.SetUInt(VHIHeaderOffset.BlocksInHDD, (blocks * 512) / 0x100000); binaryHeader.SetUInt(VHIHeaderOffset.BlocksAllocated, (blocks * 512) / 0x100000); binaryHeader.SetBytes(VHIHeaderOffset.UUID, guid, 0, 16); binaryHeader.SetBytes(VHIHeaderOffset.UUIDLastSnap, lastSnapGuid, 0, 16); return(binaryHeader.Data); }
internal void GetGeom() { xGeom = new DiskGeometry(); uint blah; DeviceIoControl(xSFH, 0x70000, IntPtr.Zero, 0, ref xGeom, (uint)Marshal.SizeOf(typeof(DiskGeometry)), out blah, IntPtr.Zero); }
private void enumerate() { Environment.GetLogicalDrives(); listView1.Items.Clear(); List <string> pdrives = GetPhysicalDriveList(); int i = 0; foreach (string info in pdrives) { int driveNumber = Convert.ToInt32(info.Replace(@"PhysicalDrive", "")); List <string> letter = GetLetters(driveNumber); if (variables.debugme) { Console.WriteLine("{0} - {1}", info, letter.Count); } if (letter.Count == 0) { ListViewItem lvi = new ListViewItem(); lvi.Text = info; lvi.SubItems.Add(""); lvi.SubItems.Add(""); lvi.SubItems.Add(""); lvi.SubItems.Add(""); var x = DiskGeometry.FromDevice(@"\\.\PHYSICALDRIVE" + driveNumber); if (x != null) { lvi.SubItems.Add(((x.DiskSize / 1024f) / 1024f).ToString()); } else { lvi.SubItems.Add(""); } listView1.Items.Add(lvi); } else { int j = 0; foreach (string drive in letter) { if (variables.debugme) { Console.WriteLine("{0} - {1}", info, drive); } ListViewItem lvi = new ListViewItem(); lvi.Text = info; DriveInfo driv = new DriveInfo(drive.Replace(@"\\.\", "")); lvi.SubItems.Add(driv.Name); lvi.SubItems.Add(driv.DriveType.ToString()); if (driv.IsReady == true) { lvi.SubItems.Add(driv.VolumeLabel); lvi.SubItems.Add(driv.DriveFormat); lvi.SubItems.Add((driv.TotalSize / (1024f) / 1024f).ToString()); if (variables.debugme) { Console.WriteLine("Drive is ready"); } } else { lvi.SubItems.Add(""); lvi.SubItems.Add(""); var x = DiskGeometry.FromDevice(@"\\.\PHYSICALDRIVE" + driveNumber); if (x != null) { lvi.SubItems.Add(((x.DiskSize / 1024f) / 1024f).ToString()); } else { lvi.SubItems.Add(""); } } if (driv.DriveType == DriveType.Removable || showall) { listView1.Items.Add(lvi); } j++; UpdateProgres(((i + j) * 100) / (pdrives.Count * letter.Count)); } } //lvi.SubItems.Add(string.Join("", getletters(Convert.ToInt32(info[info.Length -1].ToString())))); i++; UpdateProgres((i * 100) / pdrives.Count); } }
/// <summary> /// Initializes a new instance of the <see cref="CHS"/> struct. /// </summary> /// <param name="diskGeometry">The disk geometry.</param> /// <param name="lba">The lba.</param> public CHS(DiskGeometry diskGeometry, ulong lba) { SetCHS(diskGeometry, lba); }
private static extern bool DeviceIoControl(SafeHandle hDevice, uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, ref DiskGeometry lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned, IntPtr lpOverlapped);
private void write(string disk, byte[] header, byte[] sectors) { const uint OPEN_EXISTING = 3; const uint GENERIC_WRITE = (0x40000000); const uint FSCTL_LOCK_VOLUME = 0x00090018; const uint FSCTL_UNLOCK_VOLUME = 0x0009001c; const uint FSCTL_DISMOUNT_VOLUME = 0x00090020; string ldrive = "PhysicalDrive" + disk; if (variables.debugme) { Console.WriteLine(ldrive); } bool success = false; int intOut; string deviceId = @"\\.\" + ldrive; var diskGeometry = DiskGeometry.FromDevice(@"\\.\" + ldrive.Replace("\\", "")); List <string> logicaldrives = GetLetters(Convert.ToInt32(ldrive.Replace(@"PhysicalDrive", "").Replace("\\", "").Replace(".", "").ToString())); SafeFileHandle diskHandle = CreateFile(deviceId, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if (diskHandle.IsInvalid) { int lastError = Marshal.GetLastWin32Error(); Console.WriteLine(@"!! Error ({0}): {1}", lastError, new Win32Exception(lastError).Message); Console.WriteLine(deviceId + " open error."); return; } if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": opened."); } List <SafeFileHandle> lhandles = new List <SafeFileHandle>(); List <string> lnames = new List <string>(); int i = 0; if (variables.debugme) { Console.WriteLine(logicaldrives.Count); } foreach (string logdrive in logicaldrives) { if (variables.debugme) { Console.WriteLine("Opening logical drives"); } string ldevid = @"\\.\" + logdrive.Replace("\\", "").Replace(".", ""); if (variables.debugme) { Console.WriteLine(ldevid); } SafeFileHandle ldiskHandle = CreateFile(ldevid, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if (ldiskHandle.IsInvalid) { Console.WriteLine(ldevid + " open error."); break; } if (variables.debugme) { Console.WriteLine(ldevid + " " + Marshal.GetHRForLastWin32Error().ToString() + ": opened."); } lhandles.Add(ldiskHandle); lnames.Add(ldevid); success = DeviceIoControl(ldiskHandle, FSCTL_LOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (!success) { Console.WriteLine(ldevid + " lock error."); CloseHandle(ldiskHandle); break; } if (variables.debugme) { Console.WriteLine(ldevid + " " + Marshal.GetHRForLastWin32Error().ToString() + ": locked."); } success = DeviceIoControl(ldiskHandle, FSCTL_DISMOUNT_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (!success) { Console.WriteLine(ldevid + " " + Marshal.GetHRForLastWin32Error().ToString() + ": dismount error."); DeviceIoControl(ldiskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); CloseHandle(ldiskHandle); return; } } success = DeviceIoControl(diskHandle, FSCTL_LOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (!success) { Console.WriteLine(deviceId + " lock error."); CloseHandle(diskHandle); return; } if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": locked."); } success = DeviceIoControl(diskHandle, FSCTL_DISMOUNT_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (!success) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": dismount error."); DeviceIoControl(diskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); CloseHandle(diskHandle); return; } if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unmounted."); } //uint numTotalSectors = 0x795FFF;//DiskSize / 512; //uint numTotalSectors = 0x702000; uint sector = diskGeometry.BytesPerSector; long totaltracks = 33; byte[] junkBytes = new byte[(int)sector]; if (variables.debugme) { Console.WriteLine(totaltracks); } FileStream fw = new FileStream(diskHandle, FileAccess.ReadWrite); for (uint sectorNum = 0; sectorNum < totaltracks; sectorNum++) { Buffer.BlockCopy(sectors, (int)sectorNum * 0x200, junkBytes, 0, 0x200); fw.Write(junkBytes, 0, (int)sector); } fw.Seek(diskGeometry.MaximumLinearAddress - 0x200, SeekOrigin.Begin); fw.Write(header, 0, 0x200); i = 0; foreach (SafeFileHandle sfh in lhandles) { success = DeviceIoControl(sfh, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (success) { if (variables.debugme) { Console.WriteLine(lnames[i] + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlocked."); } } else { Console.WriteLine(lnames[i] + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlock error: " + Marshal.GetHRForLastWin32Error().ToString()); } i++; } success = DeviceIoControl(diskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (success) { if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlocked."); } } else { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlock error: " + Marshal.GetHRForLastWin32Error().ToString()); } i = 0; foreach (SafeFileHandle sfh in lhandles) { success = CloseHandle(sfh); if (success) { if (variables.debugme) { Console.WriteLine(lnames[i] + " " + Marshal.GetHRForLastWin32Error().ToString() + ": handle closed."); } } else { Console.WriteLine(lnames[i] + " " + Marshal.GetHRForLastWin32Error().ToString() + ": close handle error: " + Marshal.GetHRForLastWin32Error().ToString()); } i++; } success = CloseHandle(diskHandle); if (success) { if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": handle closed."); } } else { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": close handle error: " + Marshal.GetHRForLastWin32Error().ToString()); } try { fw.Close(); } catch (Exception) { } Environment.GetLogicalDrives(); }
internal static long TranslateGeometryToSize(DiskGeometry gem) { Main.SendDebug(string.Format("Cylinders: {0}", gem.Cylinders)); Main.SendDebug(string.Format("Tracks: {0}", gem.TracksPerCylinder)); Main.SendDebug(string.Format("Sectors: {0}", gem.SectorsPerTrack)); Main.SendDebug(string.Format("Bytes: {0}", gem.BytesPerSector)); Main.SendDebug(string.Format("DiskSize: {0}", gem.DiskSize)); return gem.DiskSize; }
private int read(string filename) { if (String.IsNullOrEmpty(filename)) { return(0); } if (listView1.SelectedItems.Count == 0) { return(0); } if (File.Exists(filename)) { if (DialogResult.Cancel == MessageBox.Show("File already exists, it will be DELETED! Press ok to continue", "File Already Exists", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)) { Console.WriteLine("Cancelled"); return(0); } ; try { File.Delete(filename); } catch (Exception ex) { if (variables.debugme) { Console.WriteLine(ex.ToString()); } return(0); } } string ldrive = listView1.SelectedItems[0].SubItems[1].Text; Console.WriteLine(ldrive); var diskGeometry = DiskGeometry.FromDevice(@"\\.\" + ldrive.Replace("\\", "")); if (diskGeometry == null) { Console.WriteLine("Failed to get DiskGeometry."); return(0); } uint track = diskGeometry.BytesPerSector * (diskGeometry.Sector + 1); long tracks = 0x600; if (chkFullDump.Checked) { tracks = diskGeometry.DiskSize / track; } long i = 0; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); try { Console.WriteLine("Reading from {0} to {1}", ldrive, filename); FileStream fs = new FileStream(CreateFile(@"\\.\" + ldrive.Replace("\\", ""), FileAccess.Read, FileShare.Read, 0, FileMode.Open, 0, IntPtr.Zero), FileAccess.Read); FileStream fw = new FileStream(filename, FileMode.OpenOrCreate); byte[] temp = new byte[track]; while (i < tracks && !variables.escapeloop) { UpdateProgres((int)((i * 100) / tracks)); UpdateBloc(((i * track) / 1024 / 1024).ToString("F0") + "MB"); i++; fs.Read(temp, 0, (int)track); fw.Write(temp, 0, (int)track); } fs.Close(); fw.Close(); UpdateBloc(""); UpdateProgres(100); stopwatch.Stop(); Console.WriteLine("Done!"); Console.WriteLine("in {0}:{1:D2} min:sec", stopwatch.Elapsed.Minutes + (stopwatch.Elapsed.Hours * 60), stopwatch.Elapsed.Seconds); } catch (Exception ex) { Console.WriteLine(ex.ToString() + i); } return(1); }
private static void WriteDiskGeometry(VhdDataWriter dataWriter, DiskGeometry diskGeometry) { dataWriter.WriteInt16(diskGeometry.Cylinder); dataWriter.WriteByte(diskGeometry.Heads); dataWriter.WriteByte(diskGeometry.Sectors); }
/// <summary> /// Creates the specified options. /// </summary> /// <param name="options">The options.</param> static public void Create(BootImageOptions options) { if (File.Exists(options.DiskImageFileName)) { File.Delete(options.DiskImageFileName); } uint blockCount = options.BlockCount; if (blockCount == 0) { blockCount = 8400 + 1; foreach (var file in options.IncludeFiles) { blockCount += ((uint)file.Content.Length / SectorSize) + 1; } } var diskGeometry = new DiskGeometry(); diskGeometry.GuessGeometry(blockCount); // Create disk image file var diskDeviceDriver = new BlockFileStreamDriver(options.DiskImageFileName); var diskDevice = new Device() { DeviceDriver = diskDeviceDriver }; // Setup device -- required as part of framework in operating system diskDeviceDriver.Setup(diskDevice); diskDeviceDriver.Initialize(); diskDeviceDriver.Start(); if (options.ImageFormat == ImageFormat.VDI) { // Create header var header = VDI.CreateHeader( blockCount, options.MediaGuid.ToByteArray(), options.MediaLastSnapGuid.ToByteArray(), diskGeometry ); diskDeviceDriver.WriteBlock(0, 1, header); var map = VDI.CreateImageMap(blockCount); diskDeviceDriver.WriteBlock(1, (uint)(map.Length / SectorSize), map); diskDeviceDriver.BlockOffset = 1 + (uint)(map.Length / 512); } // Expand disk image diskDeviceDriver.WriteBlock(blockCount - 1, 1, new byte[SectorSize]); // Create partition device driver var partitionDevice = new PartitionDeviceDriver(); // Setup partition configuration var configuraiton = new DiskPartitionConfiguration() { Index = 0, ReadOnly = false, }; if (options.MBROption) { // Create master boot block record var mbr = new MasterBootBlock(diskDeviceDriver) { // Setup partition entry DiskSignature = 0x12345678 }; mbr.Partitions[0].Bootable = true; mbr.Partitions[0].StartLBA = diskGeometry.SectorsPerTrack; mbr.Partitions[0].TotalBlocks = blockCount - mbr.Partitions[0].StartLBA; switch (options.FileSystem) { case FileSystem.FAT12: mbr.Partitions[0].PartitionType = PartitionType.FAT12; break; case FileSystem.FAT16: mbr.Partitions[0].PartitionType = PartitionType.FAT16; break; case FileSystem.FAT32: mbr.Partitions[0].PartitionType = PartitionType.FAT32; break; default: break; } mbr.Code = options.MBRCode; mbr.Write(); configuraiton.StartLBA = mbr.Partitions[0].StartLBA; configuraiton.TotalBlocks = mbr.Partitions[0].TotalBlocks; } else { configuraiton.StartLBA = 0; configuraiton.TotalBlocks = diskDeviceDriver.TotalBlocks; } // Setup device -- required as part of framework in operating system var device = new Device() { Configuration = configuraiton, DeviceDriver = partitionDevice, Parent = diskDevice, }; // Setup and initialize partitionDevice.Setup(device); partitionDevice.Initialize(); partitionDevice.Start(); // Set FAT settings var fatSettings = new FatSettings(); switch (options.FileSystem) { case FileSystem.FAT12: fatSettings.FATType = FatType.FAT12; break; case FileSystem.FAT16: fatSettings.FATType = FatType.FAT16; break; case FileSystem.FAT32: fatSettings.FATType = FatType.FAT32; break; default: break; } fatSettings.FloppyMedia = false; fatSettings.VolumeLabel = options.VolumeLabel; fatSettings.SerialID = new byte[4] { 0x01, 0x02, 0x03, 0x04 }; fatSettings.SectorsPerTrack = diskGeometry.SectorsPerTrack; fatSettings.NumberOfHeads = diskGeometry.Heads; fatSettings.HiddenSectors = diskGeometry.SectorsPerTrack; fatSettings.OSBootCode = options.FatBootCode; // Create FAT file system var fat = new FatFileSystem(partitionDevice); if (!fat.Format(fatSettings)) { throw new Exception("ERROR: Invalid FAT settings"); } fat.SetVolumeName(options.VolumeLabel); foreach (var includeFile in options.IncludeFiles) { var fileAttributes = new FatFileAttributes(); if (includeFile.Archive) { fileAttributes |= FatFileAttributes.Archive; } if (includeFile.ReadOnly) { fileAttributes |= FatFileAttributes.ReadOnly; } if (includeFile.Hidden) { fileAttributes |= FatFileAttributes.Hidden; } if (includeFile.System) { fileAttributes |= FatFileAttributes.System; } string newname = (Path.GetFileNameWithoutExtension(includeFile.Filename).PadRight(8).Substring(0, 8) + Path.GetExtension(includeFile.Filename).PadRight(4).Substring(1, 3)).ToUpper(); var location = fat.CreateFile(newname, fileAttributes); if (!location.IsValid) { throw new Exception("Unable to write file"); } var fatFileStream = new FatFileStream(fat, location); fatFileStream.Write(includeFile.Content, 0, includeFile.Content.Length); fatFileStream.Flush(); } if (options.PatchSyslinuxOption) { if (options.BootLoader == BootLoader.Syslinux_6_03) { Syslinux.PatchSyslinux_6_03(partitionDevice, fat); } else if (options.BootLoader == BootLoader.Syslinux_3_72) { Syslinux.PatchSyslinux_3_72(partitionDevice, fat); } } if (options.ImageFormat == ImageFormat.VHD) { // Create footer var footer = VHD.CreateFooter( blockCount, (uint)(DateTime.Now - (new DateTime(2000, 1, 1, 0, 0, 0))).Seconds, options.MediaGuid.ToByteArray(), diskGeometry ); diskDeviceDriver.WriteBlock(blockCount, 1, footer); } diskDeviceDriver.Dispose(); }
/// <summary> /// Validates the header and throws an exception if it's invalid /// </summary> public void Validate() { var E = Encoding.Default; if (Cookie == null || E.GetBytes(Cookie).Length != 8) { throw new ValidationException(nameof(Cookie), "Must be an 8 byte (ANSI) string"); } if (!Enum.IsDefined(typeof(VhdFeatures), Features)) { throw new ValidationException(nameof(Features), "Must be one or a combination of the defined enum values"); } if (!Features.HasFlag(VhdFeatures.Reserved)) { throw new ValidationException(nameof(Features), $"Must have '{nameof(VhdFeatures.Reserved)}' flag set"); } if ((int)Features >= ((int)VhdFeatures.Reserved << 1)) { throw new ValidationException(nameof(Features), "Must have undefined bits set to zero"); } if (FileFormatVersion == null) { throw new ValidationException(nameof(FileFormatVersion), "Must be defined"); } if (!Tools.InRange(ushort.MinValue, FileFormatVersion.Major, ushort.MaxValue)) { throw new ValidationException(nameof(FileFormatVersion) + "." + nameof(Version.Major), $"Must be in the range of {ushort.MinValue}-{ushort.MaxValue}"); } if (!Tools.InRange(ushort.MinValue, FileFormatVersion.Major, ushort.MaxValue)) { throw new ValidationException(nameof(FileFormatVersion) + "." + nameof(Version.Minor), $"Must be in the range of {ushort.MinValue}-{ushort.MaxValue}"); } if (DiskType == VhdType.FixedDisk && DataOffset != OFFSET_NONE) { throw new ValidationException(nameof(DataOffset), $"Must be set to ({nameof(OFFSET_NONE)}){OFFSET_NONE} for a fixed vhd type"); } if (VHD.ToDiskTimestamp(TimeStamp) < int.MinValue || VHD.ToDiskTimestamp(TimeStamp) > int.MaxValue) { throw new ValidationException(nameof(TimeStamp), $"Must be at most {int.MinValue}-{int.MaxValue} seconds away from 2000-01-01 00:00:00 UTC"); } if (CreatorApplication == null || E.GetBytes(CreatorApplication).Length != 4) { throw new ValidationException(nameof(CreatorApplication), "Must be a 4 byte (ANSI) string"); } if (CreatorVersion == null) { throw new ValidationException(nameof(CreatorVersion), "Must be defined"); } if (!Tools.InRange(ushort.MinValue, CreatorVersion.Major, ushort.MaxValue)) { throw new ValidationException(nameof(CreatorVersion) + nameof(Version.Major), $"Must be in the range of {ushort.MinValue}-{ushort.MaxValue}"); } if (!Tools.InRange(ushort.MinValue, CreatorVersion.Minor, ushort.MaxValue)) { throw new ValidationException(nameof(CreatorVersion) + nameof(Version.Minor), $"Must be in the range of {ushort.MinValue}-{ushort.MaxValue}"); } if (CreatorHostOS == null || E.GetBytes(CreatorHostOS).Length != 4) { throw new ValidationException(nameof(CreatorHostOS), "Is not a 4 byte (ANSI) string"); } if (OriginalSize == 0) { throw new ValidationException(nameof(OriginalSize), "Can't be zero"); } if (CurrentSize == 0) { throw new ValidationException(nameof(CurrentSize), $"Can't be zero"); } if (CurrentSize % 512 != 0) { throw new ValidationException(nameof(CurrentSize), "Must be a multiple of 512"); } if (DiskGeometry == null) { throw new ValidationException(nameof(DiskGeometry), "Is not defined"); } if (DiskGeometry.Cylinders < 1 || DiskGeometry.Cylinders > CHS.MAX_CYLINDERS) { throw new ValidationException(nameof(DiskGeometry) + nameof(CHS.Cylinders), $"Must be in the range of 1-{CHS.MAX_CYLINDERS}"); } if (DiskGeometry.Heads < 1 || DiskGeometry.Heads > CHS.MAX_HEADS) { throw new ValidationException(nameof(DiskGeometry) + nameof(CHS.Heads), $"Must be in the range of 1-{CHS.MAX_HEADS}"); } if (DiskGeometry.SectorsPerTrack < 1 || DiskGeometry.SectorsPerTrack > CHS.MAX_SECTORS_PER_TRACK) { throw new ValidationException(nameof(DiskGeometry) + nameof(CHS.SectorsPerTrack), $"Must be in the range of 1-{CHS.MAX_SECTORS_PER_TRACK}"); } if (!DiskGeometry.Equals(new CHS(CurrentSize))) { throw new ValidationException(nameof(DiskGeometry), $"Does not matches {nameof(CurrentSize)}"); } if (!Enum.IsDefined(typeof(VhdType), DiskType)) { throw new ValidationException(nameof(DiskType), "Not one of the defined enum values"); } if (Checksum != ComputeChecksum()) { throw new ValidationException(nameof(Checksum), $"Wrong checksum. Expected: {ComputeChecksum()}"); } if (DiskId == Guid.Empty) { throw new ValidationException(nameof(DiskId), "Is invalid (All zeros)"); } if (Reserved == null || Reserved.Length != RESERVED_FIELD_SIZE) { throw new ValidationException(nameof(Reserved), $"Must be {RESERVED_FIELD_SIZE} bytes long"); } if (Reserved.Any(m => m != 0)) { throw new ValidationException(nameof(Reserved), "Must be made up of nullbytes only"); } }
private void erase_v1() { const uint OPEN_EXISTING = 3; const uint GENERIC_WRITE = (0x40000000); const uint FSCTL_LOCK_VOLUME = 0x00090018; const uint FSCTL_UNLOCK_VOLUME = 0x0009001c; const uint FSCTL_DISMOUNT_VOLUME = 0x00090020; if (listView1.SelectedItems.Count == 0) { return; } string ldrive = listView1.SelectedItems[0].SubItems[0].Text; if (variables.debugme) { Console.WriteLine(ldrive); } bool success = false; int intOut; string deviceId = @"\\.\" + ldrive; var diskGeometry = DiskGeometry.FromDevice(@"\\.\" + ldrive.Replace("\\", "")); List <string> logicaldrives = GetLetters(Convert.ToInt32(ldrive.Replace(@"PhysicalDrive", "").Replace("\\", "").Replace(".", "").ToString())); SafeFileHandle diskHandle = CreateFile(deviceId, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if (diskHandle.IsInvalid) { Console.WriteLine(deviceId + " open error."); return; } if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": opened."); } List <SafeFileHandle> lhandles = new List <SafeFileHandle>(); List <string> lnames = new List <string>(); int i = 0; if (variables.debugme) { Console.WriteLine(logicaldrives.Count); } foreach (string logdrive in logicaldrives) { if (variables.debugme) { Console.WriteLine("Opening logical drives"); } string ldevid = @"\\.\" + logdrive.Replace("\\", "").Replace(".", ""); if (variables.debugme) { Console.WriteLine(ldevid); } SafeFileHandle ldiskHandle = CreateFile(ldevid, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if (ldiskHandle.IsInvalid) { Console.WriteLine(ldevid + " open error."); break; } if (variables.debugme) { Console.WriteLine(ldevid + " " + Marshal.GetHRForLastWin32Error().ToString() + ": opened."); } lhandles.Add(ldiskHandle); lnames.Add(ldevid); success = DeviceIoControl(ldiskHandle, FSCTL_LOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (!success) { Console.WriteLine(ldevid + " lock error."); CloseHandle(ldiskHandle); break; } if (variables.debugme) { Console.WriteLine(ldevid + " " + Marshal.GetHRForLastWin32Error().ToString() + ": locked."); } success = DeviceIoControl(ldiskHandle, FSCTL_DISMOUNT_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (!success) { Console.WriteLine(ldevid + " " + Marshal.GetHRForLastWin32Error().ToString() + ": dismount error."); DeviceIoControl(ldiskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); CloseHandle(ldiskHandle); return; } } success = DeviceIoControl(diskHandle, FSCTL_LOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (!success) { Console.WriteLine(deviceId + " lock error."); CloseHandle(diskHandle); return; } if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": locked."); } success = DeviceIoControl(diskHandle, FSCTL_DISMOUNT_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (!success) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": dismount error."); DeviceIoControl(diskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); CloseHandle(diskHandle); return; } if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unmounted."); } //uint numTotalSectors = 0x795FFF;//DiskSize / 512; //uint numTotalSectors = 0x702000; uint track = diskGeometry.BytesPerSector * (diskGeometry.Sector + 1); long totaltracks = diskGeometry.DiskSize / track; byte[] junkBytes = new byte[(int)track]; if (variables.debugme) { Console.WriteLine(totaltracks); } FileStream fw = new FileStream(diskHandle, FileAccess.ReadWrite); uint offset = 0; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (uint sectorNum = 0; sectorNum < totaltracks; sectorNum++) { if (variables.escapeloop) { break; } int numBytesWritten = (int)diskGeometry.BytesPerSector; //int moveToHigh; try { offset++; int value = (int)((offset * 100) / totaltracks); //if (offset % 1000 == 0) Console.WriteLine(offset + " " + value); UpdateProgres(value); } catch (Exception ex) { Console.WriteLine("{0} - {1} - {2}", offset, sectorNum, ex.ToString()); break; } //uint rvalsfp = SetFilePointer(diskHandle, sectorNum * numBytesPerSector, out moveToHigh, EMoveMethod.Begin); //Console.WriteLine("File pointer set " + Marshal.GetHRForLastWin32Error().ToString() + ": " + (sectorNum * numBytesPerSector).ToString()); fw.Write(junkBytes, 0, (int)track); //int rval = WriteFile(diskHandle, junkBytes, junkBytes.Length, out numBytesWritten, IntPtr.Zero); if (numBytesWritten != junkBytes.Length) { //Console.WriteLine("Write error on track " + sectorNum.ToString() + " from " + (sectorNum * numBytesPerSector).ToString() + "-" + moveToHigh.ToString() + " " + Marshal.GetHRForLastWin32Error().ToString() + ": Only " + numBytesWritten.ToString() + "/" + junkBytes.Length.ToString() + " bytes written."); //break; } else { //Console.WriteLine("Write success " + Marshal.GetHRForLastWin32Error().ToString() + ": " + numBytesWritten.ToString() + "/" + junkBytes.Length.ToString() + " bytes written."); } } stopwatch.Stop(); Console.WriteLine("Done!"); Console.WriteLine("in {0}:{1:D2} min:sec", stopwatch.Elapsed.Minutes + (stopwatch.Elapsed.Hours * 60), stopwatch.Elapsed.Seconds); i = 0; foreach (SafeFileHandle sfh in lhandles) { success = DeviceIoControl(sfh, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (success) { if (variables.debugme) { Console.WriteLine(lnames[i] + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlocked."); } } else { Console.WriteLine(lnames[i] + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlock error: " + Marshal.GetHRForLastWin32Error().ToString()); } i++; } success = DeviceIoControl(diskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero); if (success) { if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlocked."); } } else { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlock error: " + Marshal.GetHRForLastWin32Error().ToString()); } i = 0; foreach (SafeFileHandle sfh in lhandles) { success = CloseHandle(sfh); if (success) { if (variables.debugme) { Console.WriteLine(lnames[i] + " " + Marshal.GetHRForLastWin32Error().ToString() + ": handle closed."); } } else { Console.WriteLine(lnames[i] + " " + Marshal.GetHRForLastWin32Error().ToString() + ": close handle error: " + Marshal.GetHRForLastWin32Error().ToString()); } i++; } success = CloseHandle(diskHandle); if (success) { if (variables.debugme) { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": handle closed."); } } else { Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": close handle error: " + Marshal.GetHRForLastWin32Error().ToString()); } try { fw.Close(); } catch (Exception) { } Environment.GetLogicalDrives(); }