public override bool VerifyCurrentFileAgainstDigest(string algorithmName, byte[] digest) { return(StreamUtilities.VerifyAgainstDigest(tarStream, CurrentFileSize(), algorithmName, digest)); }
/// <summary> /// Examines the given data stream and attempts to determine if it is in .bin format. /// </summary> /// <param name="filePath">The path to the ROM file.</param> /// <param name="configFilePath">The path to the config file.</param> /// <returns>A valid BinFormatRom if the file appears to be a valid .bin (or similar) file, otherwise <c>null</c>.</returns> /// <remarks>Apparently, there may be odd-sized files floating around out there, in which case this will fail.</remarks> internal static new BinFormatRom Create(string filePath, string configFilePath) { BinFormatRom bin = null; var format = CheckFormat(filePath); if (format == RomFormat.Bin) { using (System.IO.Stream configFile = (configFilePath == null) ? null : StreamUtilities.OpenFileStream(configFilePath)) { // any valid .bin file will be even sized -- except for some available through the Digital Press. For some reason, these all seem to be a multiple of // 8KB + 1 byte in size. So allow those through, too. var configFileCheck = ((configFile != null) && (configFile.Length > 0)) || configFile == null; if (configFileCheck) { bin = new BinFormatRom() { Format = RomFormat.Bin, IsValid = true, RomPath = filePath, ConfigPath = configFilePath }; } } } return(bin); }
public ReaderDirEntry(IsoContext context, DirectoryRecord dirRecord) { _context = context; _record = dirRecord; _fileName = _record.FileIdentifier; bool rockRidge = !string.IsNullOrEmpty(_context.RockRidgeIdentifier); if (context.SuspDetected && _record.SystemUseData != null) { SuspRecords = new SuspRecords(_context, _record.SystemUseData, 0); } if (rockRidge && SuspRecords != null) { // The full name is taken from this record, even if it's a child-link record List <SystemUseEntry> nameEntries = SuspRecords.GetEntries(_context.RockRidgeIdentifier, "NM"); StringBuilder rrName = new StringBuilder(); if (nameEntries != null && nameEntries.Count > 0) { foreach (PosixNameSystemUseEntry nameEntry in nameEntries) { rrName.Append(nameEntry.NameData); } _fileName = rrName.ToString(); } // If this is a Rock Ridge child link, replace the dir record with that from the 'self' record // in the child directory. ChildLinkSystemUseEntry clEntry = SuspRecords.GetEntry <ChildLinkSystemUseEntry>(_context.RockRidgeIdentifier, "CL"); if (clEntry != null) { _context.DataStream.Position = clEntry.ChildDirLocation * _context.VolumeDescriptor.LogicalBlockSize; byte[] firstSector = StreamUtilities.ReadFully(_context.DataStream, _context.VolumeDescriptor.LogicalBlockSize); DirectoryRecord.ReadFrom(firstSector, 0, _context.VolumeDescriptor.CharacterEncoding, out _record); if (_record.SystemUseData != null) { SuspRecords = new SuspRecords(_context, _record.SystemUseData, 0); } } } LastAccessTimeUtc = _record.RecordingDateAndTime; LastWriteTimeUtc = _record.RecordingDateAndTime; CreationTimeUtc = _record.RecordingDateAndTime; if (rockRidge && SuspRecords != null) { FileTimeSystemUseEntry tfEntry = SuspRecords.GetEntry <FileTimeSystemUseEntry>(_context.RockRidgeIdentifier, "TF"); if (tfEntry != null) { if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Access) != 0) { LastAccessTimeUtc = tfEntry.AccessTime; } if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Modify) != 0) { LastWriteTimeUtc = tfEntry.ModifyTime; } if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Creation) != 0) { CreationTimeUtc = tfEntry.CreationTime; } } } }
private void PreVerifyMft(File file) { int recordLength = _context.BiosParameterBlock.MftRecordSize; int bytesPerSector = _context.BiosParameterBlock.BytesPerSector; // Check out the MFT's clusters foreach (Range <long, long> range in file.GetAttribute(AttributeType.Data, null).GetClusters()) { if (!VerifyClusterRange(range)) { ReportError("Corrupt cluster range in MFT data attribute {0}", range.ToString()); Abort(); } } foreach (Range <long, long> range in file.GetAttribute(AttributeType.Bitmap, null).GetClusters()) { if (!VerifyClusterRange(range)) { ReportError("Corrupt cluster range in MFT bitmap attribute {0}", range.ToString()); Abort(); } } using (Stream mftStream = file.OpenStream(AttributeType.Data, null, FileAccess.Read)) using (Stream bitmapStream = file.OpenStream(AttributeType.Bitmap, null, FileAccess.Read)) { Bitmap bitmap = new Bitmap(bitmapStream, long.MaxValue); long index = 0; while (mftStream.Position < mftStream.Length) { byte[] recordData = StreamUtilities.ReadFully(mftStream, recordLength); string magic = EndianUtilities.BytesToString(recordData, 0, 4); if (magic != "FILE") { if (bitmap.IsPresent(index)) { ReportError("Invalid MFT record magic at index {0} - was ({2},{3},{4},{5}) \"{1}\"", index, magic.Trim('\0'), (int)magic[0], (int)magic[1], (int)magic[2], (int)magic[3]); } } else { if (!VerifyMftRecord(recordData, bitmap.IsPresent(index), bytesPerSector)) { ReportError("Invalid MFT record at index {0}", index); StringBuilder bldr = new StringBuilder(); for (int i = 0; i < recordData.Length; ++i) { bldr.Append(string.Format(CultureInfo.InvariantCulture, " {0:X2}", recordData[i])); } ReportInfo("MFT record binary data for index {0}:{1}", index, bldr.ToString()); } } index++; } } }
/// <summary> /// Read *from* this stream and write to the targetStream in a buffered manner as per the Read() /// </summary> /// <param name="targetStream">Stream to put data into</param> public void BufferedRead(Stream targetStream) { StreamUtilities.BufferedStreamCopy(this, targetStream); }
public void StreamUtilitiesWithTestStorage_CallFileExistsWithNonexistentPath_ReturnsFalse() { var storage = new TestStorageAccess(); Assert.False(StreamUtilities.FileExists(@"SomeInvalidPathThatDoesNotExist", storage)); }
public void StreamUtilitiesWithTestStorage_CallLastWriteTimeUtcWithNonexistentPath_ReturnsDefaultDateTime() { var storage = new TestStorageAccess(); Assert.Equal(FileNotFoundTime, StreamUtilities.LastFileWriteTimeUtc(@"SomeSillyPathWithNoLastWriteTime", storage)); }
public void BufferedStreamCopyWithNullOutputStream() { using (MemoryStream ms = new MemoryStream()) Assert.Throws(typeof(ArgumentNullException), () => StreamUtilities.BufferedStreamCopy(ms, null)); }
public VfsExtFileSystem(Stream stream, FileSystemParameters parameters) : base(new ExtFileSystemOptions(parameters)) { stream.Position = 1024; byte[] superblockData = StreamUtilities.ReadExact(stream, 1024); SuperBlock superblock = new SuperBlock(); superblock.ReadFrom(superblockData, 0); if (superblock.Magic != SuperBlock.Ext2Magic) { throw new IOException("Invalid superblock magic - probably not an Ext file system"); } if (superblock.RevisionLevel == SuperBlock.OldRevision) { throw new IOException("Old ext revision - not supported"); } if ((superblock.IncompatibleFeatures & ~SupportedIncompatibleFeatures) != 0) { throw new IOException("Incompatible ext features present: " + (superblock.IncompatibleFeatures & ~SupportedIncompatibleFeatures)); } Context = new Context { RawStream = stream, SuperBlock = superblock, Options = (ExtFileSystemOptions)Options }; uint numGroups = MathUtilities.Ceil(superblock.BlocksCount, superblock.BlocksPerGroup); long blockDescStart = (superblock.FirstDataBlock + 1) * (long)superblock.BlockSize; stream.Position = blockDescStart; var bgDescSize = superblock.Has64Bit ? superblock.DescriptorSize : BlockGroup.DescriptorSize; byte[] blockDescData = StreamUtilities.ReadExact(stream, (int)numGroups * bgDescSize); _blockGroups = new BlockGroup[numGroups]; for (int i = 0; i < numGroups; ++i) { BlockGroup bg = superblock.Has64Bit ? new BlockGroup64(bgDescSize) : new BlockGroup(); bg.ReadFrom(blockDescData, i * bgDescSize); _blockGroups[i] = bg; } var journalSuperBlock = new JournalSuperBlock(); if (superblock.JournalInode != 0) { var journalInode = GetInode(superblock.JournalInode); var journalDataStream = journalInode.GetContentBuffer(Context); var journalData = StreamUtilities.ReadExact(journalDataStream, 0, 1024 + 12); journalSuperBlock.ReadFrom(journalData, 0); Context.JournalSuperblock = journalSuperBlock; } RootDirectory = new Directory(Context, 2, GetInode(2)); }
internal Slot(Stream stream) { byte[] buffer = StreamUtilities.ReadExact(stream, 32); Load(buffer, 0); }
private void LoadRun(CompressedRun run) { int toCopy = (int)(run.SectorCount * Sizes.Sector); switch (run.Type) { case RunType.ZlibCompressed: this.stream.Position = run.CompOffset + 2; // 2 byte zlib header using (DeflateStream ds = new DeflateStream(this.stream, CompressionMode.Decompress, true)) { StreamUtilities.ReadExact(ds, this.decompBuffer, 0, toCopy); } break; case RunType.AdcCompressed: this.stream.Position = run.CompOffset; byte[] compressed = StreamUtilities.ReadExact(this.stream, (int)run.CompLength); if (ADCDecompress(compressed, 0, compressed.Length, this.decompBuffer, 0) != toCopy) { throw new InvalidDataException("Run too short when decompressed"); } break; case RunType.BZlibCompressed: using ( BZip2DecoderStream ds = new BZip2DecoderStream( new SubStream( this.stream, run.CompOffset, run.CompLength), Ownership.None)) { StreamUtilities.ReadExact(ds, this.decompBuffer, 0, toCopy); } break; case RunType.LzfseCompressed: this.stream.Position = run.CompOffset; byte[] lzfseCompressed = StreamUtilities.ReadExact(this.stream, (int)run.CompLength); if (LzfseCompressor.Decompress(lzfseCompressed, this.decompBuffer) != toCopy) { throw new InvalidDataException("Run too short when decompressed"); } break; case RunType.LzmaCompressed: using (var ds = new XZInputStream( new SubStream( this.stream, run.CompOffset, run.CompLength))) { StreamUtilities.ReadExact(ds, this.decompBuffer, 0, toCopy); } break; case RunType.Zeros: case RunType.Raw: case RunType.None: break; default: throw new NotImplementedException("Unrecognized run type " + run.Type); } this.activeRun = run; }
public override int Read(byte[] buffer, int offset, int count) { CheckDisposed(); if (_atEof || _position > _length) { _atEof = true; throw new IOException("Attempt to read beyond end of file"); } if (_position == _length) { _atEof = true; return(0); } if (_position % _metadata.LogicalSectorSize != 0 || count % _metadata.LogicalSectorSize != 0) { throw new IOException("Unaligned read"); } int totalToRead = (int)Math.Min(_length - _position, count); int totalRead = 0; while (totalRead < totalToRead) { int chunkIndex; int blockIndex; int sectorIndex; Chunk chunk = GetChunk(_position + totalRead, out chunkIndex, out blockIndex, out sectorIndex); int blockOffset = (int)(sectorIndex * _metadata.LogicalSectorSize); int blockBytesRemaining = (int)(_fileParameters.BlockSize - blockOffset); PayloadBlockStatus blockStatus = chunk.GetBlockStatus(blockIndex); if (blockStatus == PayloadBlockStatus.FullyPresent) { _fileStream.Position = chunk.GetBlockPosition(blockIndex) + blockOffset; int read = StreamUtilities.ReadMaximum(_fileStream, buffer, offset + totalRead, Math.Min(blockBytesRemaining, totalToRead - totalRead)); totalRead += read; } else if (blockStatus == PayloadBlockStatus.PartiallyPresent) { BlockBitmap bitmap = chunk.GetBlockBitmap(blockIndex); bool present; int numSectors = bitmap.ContiguousSectors(sectorIndex, out present); int toRead = (int)Math.Min(numSectors * _metadata.LogicalSectorSize, totalToRead - totalRead); int read; if (present) { _fileStream.Position = chunk.GetBlockPosition(blockIndex) + blockOffset; read = StreamUtilities.ReadMaximum(_fileStream, buffer, offset + totalRead, toRead); } else { _parentStream.Position = _position + totalRead; read = StreamUtilities.ReadMaximum(_parentStream, buffer, offset + totalRead, toRead); } totalRead += read; } else if (blockStatus == PayloadBlockStatus.NotPresent) { _parentStream.Position = _position + totalRead; int read = StreamUtilities.ReadMaximum(_parentStream, buffer, offset + totalRead, Math.Min(blockBytesRemaining, totalToRead - totalRead)); totalRead += read; } else { int zeroed = Math.Min(blockBytesRemaining, totalToRead - totalRead); Array.Clear(buffer, offset + totalRead, zeroed); totalRead += zeroed; } } _position += totalRead; return(totalRead); }
/// <summary> /// Created this to test the custom neuron network with binary inputs. /// </summary> /// <param name="writer"></param> public static void Test( string file, int numberOfInputNeurons, int numberOfHiddenNeurons, int numberOfOutputNeurons, int numberOfCycles = 50000, double learningRate = 0.25) { TrainingSample sample = new TrainingSample( new double[] { }, new double[] { }); //We might make a gui for this later. double[] errorList = new double[numberOfCycles]; int totalNumberOfNeurons = numberOfInputNeurons + numberOfOutputNeurons; LinearLayer inputLayer = new LinearLayer(numberOfInputNeurons); SigmoidLayer hiddenLayer = new SigmoidLayer(numberOfHiddenNeurons); SigmoidLayer outputLayer = new SigmoidLayer(numberOfOutputNeurons); // This layer is a event handler that fires when the output is generated, hence backpropagation. BackpropagationConnector conn1 = new BackpropagationConnector(inputLayer, hiddenLayer); BackpropagationConnector conn2 = new BackpropagationConnector(hiddenLayer, outputLayer); BackpropagationNetwork network = new BackpropagationNetwork(inputLayer, outputLayer); network.SetLearningRate(learningRate); TrainingSet trainingSet = new TrainingSet(10, 8); // A file stream reader. var inDefaule = Console.In; using (StreamReader reader = new StreamReader(file)) { Console.SetIn(reader); String line = ""; //trainingSet.Add(new TrainingSample(new double[] { 0, 0, 0, 0, 1 }, new double[1] { 1 })); while ((line = reader.ReadLine()) != null) { String[] array = line.Split(','); double[] inputArray = new double[10]; double[] outputArray = new double[8]; for (int i = 0; i < 10; i++) { inputArray[i] = Convert.ToDouble(array[i]); } for (int i = 0; i < 8; i++) { outputArray[i] = Convert.ToDouble(array[i + 11]); } trainingSet.Add(new TrainingSample(inputArray, outputArray)); } } double max = 0; // create an anonymous function to capture the error value of each iteration, and report back the percent of completion. network.EndEpochEvent += delegate(object networkInput, TrainingEpochEventArgs args) { errorList[args.TrainingIteration] = network.MeanSquaredError; max = Math.Max(max, network.MeanSquaredError); // PercentComplete = args.TrainingIteration * 100 / numberOfCycles; }; network.Learn(trainingSet, numberOfCycles); double[] indices = new double[numberOfCycles]; // for (int i = 0; i < numberOfCycles; i++) { indices[i] = i; } .. oh nvm, its for graphing the learning curve // what to do for error list? // errorList => for plotting stuff. // for (int i = 0; i < numberOfCycles; i++) // { //Console.WriteLine(errorList[i]); // } // print out the error list for scientific evaluation. StreamUtilities.DumpData("dumpErrorValues.txt", errorList); double[] outputResult = network.OutputLayer.GetOutput(); outputResult = network.Run(new double[] { 0.47, 0.41, 0.12, 0.05, 0.1, 0.5, 0.1, 0.1, 0.05, 0.1 }); foreach (var d in outputResult) { Console.WriteLine("output: " + d); } // Console.WriteLine("final output"); }
internal static DynamicHeader FromStream(Stream stream) { return(FromBytes(StreamUtilities.ReadFully(stream, 1024), 0)); }
public void StreamUtilities_RegisterNull_ThrowsArgumentNullException() { Assert.Throws <ArgumentNullException>(() => StreamUtilities.Initialize(null)); }
/// <summary> /// Updates the validation state of the given support file. /// </summary> /// <param name="whichFile">Which file to validate.</param> /// <param name="crc">If non-zero, the CRC of the program ROM to compare against if validating the ROM file.</param> /// <param name="programDescription">The program description being validated (if applicable).</param> /// <param name="peripherals">The peripherals attached to the system, used for compatibility checks.</param> /// <param name="connectedPeripheralsHistory">The peripherals that have been attached to the system over time.</param> /// <param name="reportIfModified">If <c>true</c>, check if the file has been modified, not just whether it exists.</param> /// <returns>The updated state of the file.</returns> public ProgramSupportFileState ValidateSupportFile(ProgramFileKind whichFile, uint crc, IProgramDescription programDescription, IEnumerable <IPeripheral> peripherals, IEnumerable <IPeripheral> connectedPeripheralsHistory, bool reportIfModified) { var validationState = ProgramSupportFileState.None; switch (whichFile) { case ProgramFileKind.Rom: var isValid = Rom.Validate(); if (!string.IsNullOrEmpty(RomImagePath)) { var previousValidationState = ProgramSupportFileState.None; _supportFileStates.TryGetValue(whichFile, out previousValidationState); if (!StreamUtilities.FileExists(RomImagePath)) { validationState = ProgramSupportFileState.Missing; if (AlternateRomImagePaths.Any(p => StreamUtilities.FileExists(p))) { validationState = ProgramSupportFileState.MissingWithAlternateFound; } } else if (reportIfModified) { isValid = _programRom.IsValid; if (crc != 0) { // In some cases, the CRC provided is actually Rom.Crc, so if they match, recompute the CRC. var cfgCrc = 0u; isValid = (Rom.Crc == crc) && (crc == GetRefreshedCrcForRom(RomImagePath, RomConfigurationFilePath, out cfgCrc) && (Rom.CfgCrc == cfgCrc)); } validationState = isValid ? ProgramSupportFileState.PresentAndUnchanged : ProgramSupportFileState.PresentButModified; } switch (validationState) { case ProgramSupportFileState.PresentAndUnchanged: case ProgramSupportFileState.None: // Treat a ROM file's missing or modified state as higher priority to report than peripheral-related information. // This bit of code is entirely LTO Flash!-specific in its assumptions. If there should ever be other // peripheral-specific needs to address here, a larger architectural change may be necessary. While the // language of the states here is neutral, the basis of this check is not. var rom = programDescription == null ? Rom : programDescription.Rom; var requiresPeripheral = rom.IsLtoFlashOnlyRom(); if (requiresPeripheral) { var isUniversallyCompatible = rom.GetTargetDeviceUniqueId() == LuigiScrambleKeyBlock.AnyLTOFlashId; var matchesPeripheralInDeviceHistory = isUniversallyCompatible || ((connectedPeripheralsHistory != null) && (connectedPeripheralsHistory.FirstOrDefault(p => p.IsRomCompatible(programDescription)) != null)); var canRunOnConnected = isUniversallyCompatible || ((peripherals != null) && (peripherals.FirstOrDefault(p => p.IsRomCompatible(programDescription)) != null)); if (peripherals == null) { // If previous validation state was due to peripheral, retain it, since we don't // have any peripherals to check against. if (validationState != previousValidationState) { switch (previousValidationState) { case ProgramSupportFileState.RequiredPeripheralAvailable: case ProgramSupportFileState.RequiredPeripheralIncompatible: case ProgramSupportFileState.RequiredPeripheralNotAttached: case ProgramSupportFileState.RequiredPeripheralUnknown: validationState = previousValidationState; break; case ProgramSupportFileState.None: validationState = matchesPeripheralInDeviceHistory ? ProgramSupportFileState.RequiredPeripheralNotAttached : ProgramSupportFileState.RequiredPeripheralUnknown; break; default: // TODO: Decide if the following is a bug: // 0: Presume a scrambled (unique) LUIGI, no device or device history provided (null) // 1. Initially ROM's file is missing, but its alternate is found - this caches the 'MissingButAlternateFound' state // 2. Update ROM to use alternate path as primary path // 3. Re-validate // At this point, the "Present and unmodified" state is used -- despite the ROM requiring // a specific device. // Why is this considered correct at this time? // a) When no devices or device history are give (nulls), it's impossible to know. So just use the simple state of he file. // b) It MAY be a bug that, if we pass in EMPTY peripheral / history lists that we should consider something different... but // then again, should we report 'unknown peripheral' at that time? Or would reporting 'not attached' be better? // What about 'universally' scrambled ROMs? Using 'not attached' may be more accurate then as well... // The case of scrambled ROMs likely needs more careful consideration generally... break; } } } else { if (peripherals.Any()) { if (canRunOnConnected) { validationState = ProgramSupportFileState.RequiredPeripheralAvailable; } else { validationState = ProgramSupportFileState.RequiredPeripheralIncompatible; } } else { validationState = matchesPeripheralInDeviceHistory ? ProgramSupportFileState.RequiredPeripheralNotAttached : ProgramSupportFileState.RequiredPeripheralUnknown; } } } break; default: break; } } break; default: // TODO: Implement remaining validation code. break; } _supportFileStates[whichFile] = validationState; return(validationState); }
public void StreamUtilities_RemoveNull_ThrowsArgumentNullException() { Assert.Throws <ArgumentNullException>(() => StreamUtilities.Remove(null)); }
public override int Read(long pos, byte[] buffer, int offset, int count) { if (pos > _inode.FileSize) { return(0); } uint blockSize = _context.SuperBlock.BlockSize; int totalRead = 0; int totalBytesRemaining = (int)Math.Min(count, _inode.FileSize - pos); while (totalBytesRemaining > 0) { uint logicalBlock = (uint)((pos + totalRead) / blockSize); int blockOffset = (int)(pos + totalRead - logicalBlock * (long)blockSize); uint physicalBlock = 0; if (logicalBlock < 12) { physicalBlock = _inode.DirectBlocks[logicalBlock]; } else { logicalBlock -= 12; if (logicalBlock < blockSize / 4) { if (_inode.IndirectBlock != 0) { _context.RawStream.Position = _inode.IndirectBlock * (long)blockSize + logicalBlock * 4; byte[] indirectData = StreamUtilities.ReadFully(_context.RawStream, 4); physicalBlock = EndianUtilities.ToUInt32LittleEndian(indirectData, 0); } } else { logicalBlock -= blockSize / 4; if (logicalBlock < blockSize / 4 * (blockSize / 4)) { if (_inode.DoubleIndirectBlock != 0) { _context.RawStream.Position = _inode.DoubleIndirectBlock * (long)blockSize + logicalBlock / (blockSize / 4) * 4; byte[] indirectData = StreamUtilities.ReadFully(_context.RawStream, 4); uint indirectBlock = EndianUtilities.ToUInt32LittleEndian(indirectData, 0); if (indirectBlock != 0) { _context.RawStream.Position = indirectBlock * (long)blockSize + logicalBlock % (blockSize / 4) * 4; StreamUtilities.ReadFully(_context.RawStream, indirectData, 0, 4); physicalBlock = EndianUtilities.ToUInt32LittleEndian(indirectData, 0); } } } else { throw new NotSupportedException("Triple indirection"); } } } int toRead = (int)Math.Min(totalBytesRemaining, blockSize - blockOffset); int numRead; if (physicalBlock == 0) { Array.Clear(buffer, offset + totalRead, toRead); numRead = toRead; } else { _context.RawStream.Position = physicalBlock * (long)blockSize + blockOffset; numRead = _context.RawStream.Read(buffer, offset + totalRead, toRead); } totalBytesRemaining -= numRead; totalRead += numRead; } return(totalRead); }
public void StreamUtilitiesWithTestStorage_CallSizeWithNonexistentPath_ThrowsFileNotFoundException() { var storage = new TestStorageAccess(); Assert.Throws <FileNotFoundException>(() => StreamUtilities.FileSize(@"SomeBogusPathThatHasNoSize", storage)); }
/// <summary> /// Write *to* this stream *from* the source stream in a buffered manner analogous to Write() /// </summary> /// <param name="sourceStream">Stream get data from</param> public void BufferedWrite(Stream sourceStream) { StreamUtilities.BufferedStreamCopy(sourceStream, this); }
private static uint ReadDigest(Stream stream) { byte[] data = StreamUtilities.ReadFully(stream, 4); return(EndianUtilities.ToUInt32BigEndian(data, 0)); }
private void DoCheck() { _context.RawStream.Position = 0; byte[] bytes = StreamUtilities.ReadFully(_context.RawStream, 512); _context.BiosParameterBlock = BiosParameterBlock.FromBytes(bytes, 0); //----------------------------------------------------------------------- // MASTER FILE TABLE // // Bootstrap the Master File Table _context.Mft = new MasterFileTable(_context); File mftFile = new File(_context, _context.Mft.GetBootstrapRecord()); // Verify basic MFT records before initializing the Master File Table PreVerifyMft(mftFile); _context.Mft.Initialize(mftFile); // Now the MFT is up and running, do more detailed analysis of it's contents - double-accounted clusters, etc VerifyMft(); _context.Mft.Dump(_report, "INFO: "); //----------------------------------------------------------------------- // INDEXES // // Need UpperCase in order to verify some indexes (i.e. directories). File ucFile = new File(_context, _context.Mft.GetRecord(MasterFileTable.UpCaseIndex, false)); _context.UpperCase = new UpperCase(ucFile); SelfCheckIndexes(); //----------------------------------------------------------------------- // DIRECTORIES // VerifyDirectories(); //----------------------------------------------------------------------- // WELL KNOWN FILES // VerifyWellKnownFilesExist(); //----------------------------------------------------------------------- // OBJECT IDS // VerifyObjectIds(); //----------------------------------------------------------------------- // FINISHED // // Temporary... using (NtfsFileSystem fs = new NtfsFileSystem(_context.RawStream)) { if ((_reportLevels & ReportLevels.Information) != 0) { ReportDump(fs); } } }