diff --git a/LibHac.Nand/Nand.cs b/LibHac.Nand/Nand.cs index 4a67d988..136aa130 100644 --- a/LibHac.Nand/Nand.cs +++ b/LibHac.Nand/Nand.cs @@ -21,7 +21,7 @@ namespace LibHac.Nand public Nand(Stream stream, Keyset keyset) { var disc = new GuidPartitionTable(stream, Geometry.Null); - var partitions = disc.Partitions.Select(x => (GuidPartitionInfo)x).ToArray(); + GuidPartitionInfo[] partitions = disc.Partitions.Select(x => (GuidPartitionInfo)x).ToArray(); ProdInfo = partitions.FirstOrDefault(x => x.Name == "PRODINFO"); ProdInfoF = partitions.FirstOrDefault(x => x.Name == "PRODINFOF"); Safe = partitions.FirstOrDefault(x => x.Name == "SAFE"); @@ -32,45 +32,45 @@ namespace LibHac.Nand public Stream OpenProdInfo() { - var encStream = ProdInfo.Open(); - var xts = XtsAes128.Create(Keyset.BisKeys[0]); + SparseStream encStream = ProdInfo.Open(); + Xts xts = XtsAes128.Create(Keyset.BisKeys[0]); var decStream = new RandomAccessSectorStream(new XtsSectorStream(encStream, xts, 0x4000, 0), true); return decStream; } public NandPartition OpenProdInfoF() { - var encStream = ProdInfoF.Open(); - var xts = XtsAes128.Create(Keyset.BisKeys[0]); + SparseStream encStream = ProdInfoF.Open(); + Xts xts = XtsAes128.Create(Keyset.BisKeys[0]); var decStream = new RandomAccessSectorStream(new XtsSectorStream(encStream, xts, 0x4000, 0), true); - FatFileSystem fat = new FatFileSystem(decStream, Ownership.None); + var fat = new FatFileSystem(decStream, Ownership.None); return new NandPartition(fat); } public NandPartition OpenSafePartition() { - var encStream = Safe.Open(); - var xts = XtsAes128.Create(Keyset.BisKeys[1]); + SparseStream encStream = Safe.Open(); + Xts xts = XtsAes128.Create(Keyset.BisKeys[1]); var decStream = new RandomAccessSectorStream(new XtsSectorStream(encStream, xts, 0x4000, 0), true); - FatFileSystem fat = new FatFileSystem(decStream, Ownership.None); + var fat = new FatFileSystem(decStream, Ownership.None); return new NandPartition(fat); } public NandPartition OpenSystemPartition() { - var encStream = System.Open(); - var xts = XtsAes128.Create(Keyset.BisKeys[2]); + SparseStream encStream = System.Open(); + Xts xts = XtsAes128.Create(Keyset.BisKeys[2]); var decStream = new RandomAccessSectorStream(new XtsSectorStream(encStream, xts, 0x4000, 0), true); - FatFileSystem fat = new FatFileSystem(decStream, Ownership.None); + var fat = new FatFileSystem(decStream, Ownership.None); return new NandPartition(fat); } public NandPartition OpenUserPartition() { - var encStream = User.Open(); - var xts = XtsAes128.Create(Keyset.BisKeys[3]); + SparseStream encStream = User.Open(); + Xts xts = XtsAes128.Create(Keyset.BisKeys[3]); var decStream = new RandomAccessSectorStream(new XtsSectorStream(encStream, xts, 0x4000, 0), true); - FatFileSystem fat = new FatFileSystem(decStream, Ownership.None); + var fat = new FatFileSystem(decStream, Ownership.None); return new NandPartition(fat); } } diff --git a/LibHac.Nand/NandPartition.cs b/LibHac.Nand/NandPartition.cs index a3ef4bcf..16406371 100644 --- a/LibHac.Nand/NandPartition.cs +++ b/LibHac.Nand/NandPartition.cs @@ -40,8 +40,8 @@ namespace LibHac.Nand public string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption) { - var files = Fs.GetFiles(path, searchPattern, searchOption); - var dirs = Fs.GetDirectories(path, searchPattern, searchOption); + string[] files = Fs.GetFiles(path, searchPattern, searchOption); + string[] dirs = Fs.GetDirectories(path, searchPattern, searchOption); return files.Concat(dirs).ToArray(); } diff --git a/LibHac/Aes128CtrStream.cs b/LibHac/Aes128CtrStream.cs index 073becb2..382251b2 100644 --- a/LibHac/Aes128CtrStream.cs +++ b/LibHac/Aes128CtrStream.cs @@ -157,7 +157,7 @@ namespace LibHac { ValidateSize(count); - var bytesRead = base.Read(_tempBuffer, 0, count); + int bytesRead = base.Read(_tempBuffer, 0, count); if (bytesRead == 0) return 0; return _decryptor.TransformBlock(_tempBuffer, 0, bytesRead, buffer, offset); diff --git a/LibHac/Aes128CtrTransform.cs b/LibHac/Aes128CtrTransform.cs index 38db3ada..79a5cf04 100644 --- a/LibHac/Aes128CtrTransform.cs +++ b/LibHac/Aes128CtrTransform.cs @@ -42,7 +42,7 @@ namespace LibHac if (inputCount > _maxSize) throw new ArgumentException($"{nameof(inputCount)} cannot be greater than {_maxSize}"); - var blockCount = Util.DivideByRoundUp(inputCount, BlockSizeBytes); + int blockCount = Util.DivideByRoundUp(inputCount, BlockSizeBytes); FillDecryptedCounter(blockCount); @@ -76,7 +76,7 @@ namespace LibHac { var inputVec = new Vector(inputBuffer, inputOffset + i); var xorVec = new Vector(xor, i); - var outputVec = inputVec ^ xorVec; + Vector outputVec = inputVec ^ xorVec; outputVec.CopyTo(outputBuffer, outputOffset + i); } } diff --git a/LibHac/Bktr.cs b/LibHac/Bktr.cs index b240457c..f5f60275 100644 --- a/LibHac/Bktr.cs +++ b/LibHac/Bktr.cs @@ -52,7 +52,7 @@ namespace LibHac private RelocationEntry GetRelocationEntry(long offset) { - var index = RelocationOffsets.BinarySearch(offset); + int index = RelocationOffsets.BinarySearch(offset); if (index < 0) index = ~index - 1; return RelocationEntries[index]; } @@ -63,12 +63,12 @@ namespace LibHac if (remaining <= 0) return 0; if (remaining < count) count = (int)remaining; - var toOutput = count; + int toOutput = count; int pos = 0; while (toOutput > 0) { - var remainInEntry = CurrentEntry.VirtOffsetEnd - Position; + long remainInEntry = CurrentEntry.VirtOffsetEnd - Position; int toRead = (int)Math.Min(toOutput, remainInEntry); ReadCurrent(buffer, pos, toRead); pos += toRead; @@ -97,7 +97,7 @@ namespace LibHac // At end of virtual stream if (CurrentEntry == null) return; - var entryOffset = Position - CurrentEntry.VirtOffset; + long entryOffset = Position - CurrentEntry.VirtOffset; if (CurrentEntry.IsPatch) { diff --git a/LibHac/BktrCryptoStream.cs b/LibHac/BktrCryptoStream.cs index f1600303..e39a32fc 100644 --- a/LibHac/BktrCryptoStream.cs +++ b/LibHac/BktrCryptoStream.cs @@ -30,7 +30,7 @@ namespace LibHac SubsectionBlock = new SubsectionBlock(reader); } - foreach (var bucket in SubsectionBlock.Buckets) + foreach (SubsectionBucket bucket in SubsectionBlock.Buckets) { SubsectionEntries.AddRange(bucket.Entries); } @@ -71,7 +71,7 @@ namespace LibHac public override int Read(byte[] buffer, int offset, int count) { int totalBytesRead = 0; - var outPos = offset; + int outPos = offset; while (count > 0) { @@ -94,7 +94,7 @@ namespace LibHac private SubsectionEntry GetSubsectionEntry(long offset) { - var index = SubsectionOffsets.BinarySearch(offset); + int index = SubsectionOffsets.BinarySearch(offset); if (index < 0) index = ~index - 1; return SubsectionEntries[index]; } diff --git a/LibHac/BktrStructs.cs b/LibHac/BktrStructs.cs index 14091900..94901332 100644 --- a/LibHac/BktrStructs.cs +++ b/LibHac/BktrStructs.cs @@ -12,7 +12,7 @@ namespace LibHac public RelocationBlock(BinaryReader reader) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; Field0 = reader.ReadUInt32(); BucketCount = reader.ReadInt32(); @@ -43,7 +43,7 @@ namespace LibHac public RelocationBucket(BinaryReader reader) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; BucketNum = reader.ReadInt32(); EntryCount = reader.ReadInt32(); @@ -85,7 +85,7 @@ namespace LibHac public SubsectionBlock(BinaryReader reader) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; Field0 = reader.ReadUInt32(); BucketCount = reader.ReadInt32(); @@ -115,7 +115,7 @@ namespace LibHac public SubsectionEntry[] Entries; public SubsectionBucket(BinaryReader reader) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; BucketNum = reader.ReadInt32(); EntryCount = reader.ReadInt32(); diff --git a/LibHac/Cnmt.cs b/LibHac/Cnmt.cs index 1ebd26db..5b578afe 100644 --- a/LibHac/Cnmt.cs +++ b/LibHac/Cnmt.cs @@ -29,7 +29,7 @@ namespace LibHac using (var reader = new BinaryReader(file)) { TitleId = reader.ReadUInt64(); - var version = reader.ReadUInt32(); + uint version = reader.ReadUInt32(); Type = (TitleType)reader.ReadByte(); TitleVersion = new TitleVersion(version, Type < TitleType.Application); FieldD = reader.ReadByte(); @@ -92,7 +92,7 @@ namespace LibHac Hash = reader.ReadBytes(0x20); NcaId = reader.ReadBytes(0x10); Size = reader.ReadUInt32(); - Size |= ((long)reader.ReadUInt16() << 32); + Size |= (long)reader.ReadUInt16() << 32; Type = (CnmtContentType)reader.ReadByte(); reader.BaseStream.Position += 1; } @@ -261,8 +261,8 @@ namespace LibHac NcaIdNew = reader.ReadBytes(0x10); SizeOld = reader.ReadUInt32(); - SizeOld |= ((long)reader.ReadUInt16() << 32); - SizeNew |= ((long)reader.ReadUInt16() << 32); + SizeOld |= (long)reader.ReadUInt16() << 32; + SizeNew |= (long)reader.ReadUInt16() << 32; SizeNew = reader.ReadUInt32(); Field2C = reader.ReadInt16(); @@ -282,7 +282,7 @@ namespace LibHac { NcaId = reader.ReadBytes(0x10); Size = reader.ReadUInt32(); - Size |= ((long)reader.ReadUInt16() << 32); + Size |= (long)reader.ReadUInt16() << 32; Type = (CnmtContentType)reader.ReadByte(); reader.BaseStream.Position += 1; } diff --git a/LibHac/Crypto.cs b/LibHac/Crypto.cs index 342b4417..ad1c1d1d 100644 --- a/LibHac/Crypto.cs +++ b/LibHac/Crypto.cs @@ -21,7 +21,7 @@ namespace LibHac public static void DecryptEcb(byte[] key, byte[] src, int srcIndex, byte[] dest, int destIndex, int length) { - using (var aes = Aes.Create()) + using (Aes aes = Aes.Create()) { if (aes == null) throw new CryptographicException("Unable to create AES object"); aes.Key = key; @@ -36,7 +36,7 @@ namespace LibHac public static void DecryptCbc(byte[] key, byte[] iv, byte[] src, int srcIndex, byte[] dest, int destIndex, int length) { - using (var aes = Aes.Create()) + using (Aes aes = Aes.Create()) { if (aes == null) throw new CryptographicException("Unable to create AES object"); aes.Key = key; @@ -52,7 +52,7 @@ namespace LibHac public static void EncryptCbc(byte[] key, byte[] iv, byte[] src, int srcIndex, byte[] dest, int destIndex, int length) { - using (var aes = Aes.Create()) + using (Aes aes = Aes.Create()) { if (aes == null) throw new CryptographicException("Unable to create AES object"); aes.Key = key; @@ -112,9 +112,9 @@ namespace LibHac Array.Copy(dec, 0x100, n, 0, 0x100); Array.Copy(dec, 0x200, e, 0, 4); - var dInt = GetBigInteger(d); - var nInt = GetBigInteger(n); - var eInt = GetBigInteger(e); + BigInteger dInt = GetBigInteger(d); + BigInteger nInt = GetBigInteger(n); + BigInteger eInt = GetBigInteger(e); RSAParameters rsaParams = RecoverRsaParameters(nInt, eInt, dInt); TestRsaKey(rsaParams); @@ -261,7 +261,7 @@ namespace LibHac Q = GetBytes(q, halfModLen), DP = GetBytes(dp, halfModLen), DQ = GetBytes(dq, halfModLen), - InverseQ = GetBytes(inverseQ, halfModLen), + InverseQ = GetBytes(inverseQ, halfModLen) }; } } @@ -322,7 +322,7 @@ namespace LibHac // https://stackoverflow.com/questions/29163493/aes-cmac-calculation-c-sharp public static void CalculateAesCmac(byte[] key, byte[] src, int srcIndex, byte[] dest, int destIndex, int length) { - byte[] l = new byte[16]; + var l = new byte[16]; EncryptCbc(key, new byte[16], new byte[16], l, 0x10); byte[] firstSubkey = Rol(l); @@ -334,7 +334,7 @@ namespace LibHac secondSubkey[15] ^= 0x87; int paddingBytes = 16 - length % 16; - byte[] srcPadded = new byte[length + paddingBytes]; + var srcPadded = new byte[length + paddingBytes]; Array.Copy(src, srcIndex, srcPadded, 0, length); @@ -351,7 +351,7 @@ namespace LibHac srcPadded[length - 16 + j] ^= secondSubkey[j]; } - byte[] encResult = new byte[length]; + var encResult = new byte[length]; EncryptCbc(key, new byte[16], srcPadded, encResult, length); Array.Copy(encResult, length - 0x10, dest, destIndex, 0x10); @@ -359,7 +359,7 @@ namespace LibHac private static byte[] Rol(byte[] b) { - byte[] r = new byte[b.Length]; + var r = new byte[b.Length]; byte carry = 0; for (int i = b.Length - 1; i >= 0; i--) diff --git a/LibHac/FileSystem.cs b/LibHac/FileSystem.cs index 1cb5e033..6c1f9755 100644 --- a/LibHac/FileSystem.cs +++ b/LibHac/FileSystem.cs @@ -52,8 +52,8 @@ namespace LibHac if (searchOption == SearchOption.TopDirectoryOnly) return result.ToArray(); - var searchDirectories = Directory.GetDirectories(Path.Combine(Root, path)); - foreach (var search in searchDirectories) + string[] searchDirectories = Directory.GetDirectories(Path.Combine(Root, path)); + foreach (string search in searchDirectories) { try { diff --git a/LibHac/Keyset.cs b/LibHac/Keyset.cs index c8c15777..1d709495 100644 --- a/LibHac/Keyset.cs +++ b/LibHac/Keyset.cs @@ -276,8 +276,8 @@ namespace LibHac static ExternalKeys() { - var commonKeys = CreateCommonKeyList(); - var uniqueKeys = CreateUniqueKeyList(); + List commonKeys = CreateCommonKeyList(); + List uniqueKeys = CreateUniqueKeyList(); CommonKeyDict = commonKeys.ToDictionary(k => k.Name, k => k); UniqueKeyDict = uniqueKeys.ToDictionary(k => k.Name, k => k); @@ -317,26 +317,26 @@ namespace LibHac string line; while ((line = reader.ReadLine()) != null) { - var a = line.Split(',', '='); + string[] a = line.Split(',', '='); if (a.Length != 2) continue; - var key = a[0].Trim(); - var valueStr = a[1].Trim(); + string key = a[0].Trim(); + string valueStr = a[1].Trim(); - if (!keyDict.TryGetValue(key, out var kv)) + if (!keyDict.TryGetValue(key, out KeyValue kv)) { logger?.LogMessage($"Failed to match key {key}"); continue; } - var value = valueStr.ToBytes(); + byte[] value = valueStr.ToBytes(); if (value.Length != kv.Size) { logger?.LogMessage($"Key {key} had incorrect size {value.Length}. (Expected {kv.Size})"); continue; } - var dest = kv.GetKey(keyset); + byte[] dest = kv.GetKey(keyset); Array.Copy(value, dest, value.Length); } } @@ -404,7 +404,7 @@ namespace LibHac byte[] key = keySlot.GetKey(keyset); if (key.IsEmpty()) continue; - var line = $"{keySlot.Name.PadRight(maxNameLength)} = {key.ToHexString()}"; + string line = $"{keySlot.Name.PadRight(maxNameLength)} = {key.ToHexString()}"; sb.AppendLine(line); } @@ -435,7 +435,7 @@ namespace LibHac { byte[] key = kv.Key; byte[] value = kv.Value; - var line = $"{key.ToHexString().PadRight(maxNameLength)} = {value.ToHexString()}"; + string line = $"{key.ToHexString().PadRight(maxNameLength)} = {value.ToHexString()}"; sb.AppendLine(line); } diff --git a/LibHac/Lz4.cs b/LibHac/Lz4.cs index cb4583cf..06620347 100644 --- a/LibHac/Lz4.cs +++ b/LibHac/Lz4.cs @@ -8,7 +8,7 @@ namespace LibHac { public static byte[] Decompress(byte[] cmp, int decLength) { - byte[] dec = new byte[decLength]; + var dec = new byte[decLength]; int cmpPos = 0; int decPos = 0; @@ -21,7 +21,7 @@ namespace LibHac { do { - length += (sum = cmp[cmpPos++]); + length += sum = cmp[cmpPos++]; } while (sum == 0xff); } diff --git a/LibHac/Nacp.cs b/LibHac/Nacp.cs index f452d087..8dd7fe81 100644 --- a/LibHac/Nacp.cs +++ b/LibHac/Nacp.cs @@ -63,7 +63,7 @@ namespace LibHac public Nacp(BinaryReader reader) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; for (int i = 0; i < 16; i++) { @@ -132,7 +132,7 @@ namespace LibHac for (int i = 0; i < 16; i++) { - var value = reader.ReadUInt64(); + ulong value = reader.ReadUInt64(); if (value != 0) PlayLogQueryableApplicationId.Add(value); } @@ -155,7 +155,7 @@ namespace LibHac public NacpLang(BinaryReader reader) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; Title = reader.ReadUtf8Z(); reader.BaseStream.Position = start + 0x200; Developer = reader.ReadUtf8Z(); diff --git a/LibHac/Nca.cs b/LibHac/Nca.cs index 9675a127..a36e0e9e 100644 --- a/LibHac/Nca.cs +++ b/LibHac/Nca.cs @@ -43,7 +43,7 @@ namespace LibHac } else { - if (keyset.TitleKeys.TryGetValue(Header.RightsId, out var titleKey)) + if (keyset.TitleKeys.TryGetValue(Header.RightsId, out byte[] titleKey)) { TitleKey = titleKey; Crypto.DecryptEcb(keyset.Titlekeks[CryptoType], titleKey, TitleKeyDec, 0x10); @@ -57,13 +57,13 @@ namespace LibHac for (int i = 0; i < 4; i++) { - var section = ParseSection(i); + NcaSection section = ParseSection(i); if (section == null) continue; Sections[i] = section; ValidateSuperblockHash(i); } - foreach (var pfsSection in Sections.Where(x => x != null && x.Type == SectionType.Pfs0)) + foreach (NcaSection pfsSection in Sections.Where(x => x != null && x.Type == SectionType.Pfs0)) { Stream sectionStream = OpenSection(pfsSection.SectionNum, false, false); if (sectionStream == null) continue; @@ -183,8 +183,8 @@ namespace LibHac private void DecryptHeader(Keyset keyset, Stream stream) { - byte[] headerBytes = new byte[0xC00]; - var xts = XtsAes128.Create(keyset.HeaderKey); + var headerBytes = new byte[0xC00]; + Xts xts = XtsAes128.Create(keyset.HeaderKey); using (var headerDec = new RandomAccessSectorStream(new XtsSectorStream(stream, xts, 0x200))) { headerDec.Read(headerBytes, 0, headerBytes.Length); @@ -206,8 +206,8 @@ namespace LibHac private NcaSection ParseSection(int index) { - var entry = Header.SectionEntries[index]; - var header = Header.FsHeaders[index]; + NcaSectionEntry entry = Header.SectionEntries[index]; + NcaFsHeader header = Header.FsHeaders[index]; if (entry.MediaStartOffset == 0) return null; var sect = new NcaSection(); @@ -235,13 +235,13 @@ namespace LibHac { sect.Romfs = new RomfsSection(); sect.Romfs.Superblock = sect.Header.Romfs; - var headers = sect.Romfs.Superblock.IvfcHeader.LevelHeaders; + IvfcLevelHeader[] headers = sect.Romfs.Superblock.IvfcHeader.LevelHeaders; for (int i = 0; i < Romfs.IvfcMaxLevel; i++) { var level = new IvfcLevel(); sect.Romfs.IvfcLevels[i] = level; - var header = headers[i]; + IvfcLevelHeader header = headers[i]; level.DataOffset = header.LogicalOffset; level.DataSize = header.HashDataSize; level.HashBlockSize = 1 << header.BlockSize; @@ -257,12 +257,12 @@ namespace LibHac private void CheckBktrKey(NcaSection sect) { - var offset = sect.Header.Bktr.SubsectionHeader.Offset; + long offset = sect.Header.Bktr.SubsectionHeader.Offset; using (var streamDec = new RandomAccessSectorStream(new Aes128CtrStream(GetStream(), DecryptedKeys[2], sect.Offset, sect.Size, sect.Offset, sect.Header.Ctr))) { var reader = new BinaryReader(streamDec); streamDec.Position = offset + 8; - var size = reader.ReadInt64(); + long size = reader.ReadInt64(); if (size != offset) { @@ -274,7 +274,7 @@ namespace LibHac private void ValidateSuperblockHash(int index) { if (Sections[index] == null) throw new ArgumentOutOfRangeException(nameof(index)); - var sect = Sections[index]; + NcaSection sect = Sections[index]; byte[] expected = null; byte[] actual; @@ -286,13 +286,13 @@ namespace LibHac case SectionType.Invalid: break; case SectionType.Pfs0: - var pfs0 = sect.Header.Pfs; + PfsSuperblock pfs0 = sect.Header.Pfs; expected = pfs0.MasterHash; offset = pfs0.HashTableOffset; size = pfs0.HashTableSize; break; case SectionType.Romfs: - var ivfc = sect.Header.Romfs.IvfcHeader; + IvfcHeader ivfc = sect.Header.Romfs.IvfcHeader; expected = ivfc.MasterHash; offset = ivfc.LevelHeaders[0].LogicalOffset; size = 1 << ivfc.LevelHeaders[0].BlockSize; @@ -315,7 +315,7 @@ namespace LibHac actual = hash.ComputeHash(hashTable); } - var validity = Util.ArraysEqual(expected, actual) ? Validity.Valid : Validity.Invalid; + Validity validity = Util.ArraysEqual(expected, actual) ? Validity.Valid : Validity.Invalid; sect.SuperblockHashValidity = validity; if (sect.Type == SectionType.Romfs) sect.Romfs.IvfcLevels[0].HashValidity = validity; @@ -324,8 +324,8 @@ namespace LibHac public void VerifySection(int index, IProgressReport logger = null) { if (Sections[index] == null) throw new ArgumentOutOfRangeException(nameof(index)); - var sect = Sections[index]; - var stream = OpenSection(index, true, false); + NcaSection sect = Sections[index]; + Stream stream = OpenSection(index, true, false); logger?.LogMessage($"Verifying section {index}..."); switch (sect.Type) @@ -345,7 +345,7 @@ namespace LibHac private void VerifyPfs0(Stream section, Pfs0Section pfs0, IProgressReport logger = null) { - var sb = pfs0.Superblock; + PfsSuperblock sb = pfs0.Superblock; var table = new byte[sb.HashTableSize]; section.Position = sb.HashTableOffset; section.Read(table, 0, table.Length); @@ -358,7 +358,7 @@ namespace LibHac for (int i = 1; i < levels.Length; i++) { logger?.LogMessage($" Verifying IVFC Level {i}..."); - var level = levels[i]; + IvfcLevel level = levels[i]; var table = new byte[level.HashSize]; section.Position = level.HashOffset; section.Read(table, 0, table.Length); @@ -372,7 +372,7 @@ namespace LibHac const int hashSize = 0x20; var currentBlock = new byte[blockSize]; var expectedHash = new byte[hashSize]; - var blockCount = Util.DivideByRoundUp(dataLen, blockSize); + long blockCount = Util.DivideByRoundUp(dataLen, blockSize); int curBlockSize = (int)blockSize; section.Position = dataOffset; logger?.SetTotal(blockCount); @@ -381,7 +381,7 @@ namespace LibHac { for (long i = 0; i < blockCount; i++) { - var remaining = (dataLen - i * blockSize); + long remaining = dataLen - i * blockSize; if (remaining < blockSize) { Array.Clear(currentBlock, 0, currentBlock.Length); @@ -389,7 +389,7 @@ namespace LibHac } Array.Copy(hashTable, i * hashSize, expectedHash, 0, hashSize); section.Read(currentBlock, 0, curBlockSize); - var actualHash = sha256.ComputeHash(currentBlock, 0, curBlockSize); + byte[] actualHash = sha256.ComputeHash(currentBlock, 0, curBlockSize); if (!Util.ArraysEqual(expectedHash, actualHash)) { @@ -433,8 +433,8 @@ namespace LibHac if (index < 0 || index > 3) throw new IndexOutOfRangeException(); if (nca.Sections[index] == null) return; - var section = nca.OpenSection(index, raw, verify); - var dir = Path.GetDirectoryName(filename); + Stream section = nca.OpenSection(index, raw, verify); + string dir = Path.GetDirectoryName(filename); if (!string.IsNullOrWhiteSpace(dir)) Directory.CreateDirectory(dir); using (var outFile = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite)) @@ -448,8 +448,8 @@ namespace LibHac if (index < 0 || index > 3) throw new IndexOutOfRangeException(); if (nca.Sections[index] == null) return; - var section = nca.Sections[index]; - var stream = nca.OpenSection(index, false, verify); + NcaSection section = nca.Sections[index]; + Stream stream = nca.OpenSection(index, false, verify); switch (section.Type) { diff --git a/LibHac/NcaStructs.cs b/LibHac/NcaStructs.cs index 82de56a9..0a0c8f02 100644 --- a/LibHac/NcaStructs.cs +++ b/LibHac/NcaStructs.cs @@ -101,7 +101,7 @@ namespace LibHac public NcaFsHeader(BinaryReader reader) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; Field0 = reader.ReadByte(); Field1 = reader.ReadByte(); PartitionType = (SectionPartitionType)reader.ReadByte(); diff --git a/LibHac/Nso.cs b/LibHac/Nso.cs index 555cc7b3..5e3e21b3 100644 --- a/LibHac/Nso.cs +++ b/LibHac/Nso.cs @@ -16,15 +16,15 @@ namespace LibHac public Nso(Stream stream) { StreamSource = new SharedStreamSource(stream); - BinaryReader reader = new BinaryReader(StreamSource.CreateStream()); + var reader = new BinaryReader(StreamSource.CreateStream()); if (reader.ReadAscii(4) != "NSO0") throw new InvalidDataException("NSO magic is incorrect!"); reader.ReadUInt32(); // Version reader.ReadUInt32(); // Reserved/Unused - BitArray flags = new BitArray(new[] { (int)reader.ReadUInt32() }); - NsoSection textSection = new NsoSection(StreamSource); - NsoSection rodataSection = new NsoSection(StreamSource); - NsoSection dataSection = new NsoSection(StreamSource); + var flags = new BitArray(new[] { (int)reader.ReadUInt32() }); + var textSection = new NsoSection(StreamSource); + var rodataSection = new NsoSection(StreamSource); + var dataSection = new NsoSection(StreamSource); textSection.IsCompressed = flags[0]; rodataSection.IsCompressed = flags[1]; dataSection.IsCompressed = flags[2]; @@ -81,7 +81,7 @@ namespace LibHac public byte[] DecompressSection() { - byte[] compressed = new byte[CompressedSize]; + var compressed = new byte[CompressedSize]; OpenSection().Read(compressed, 0, (int)CompressedSize); if (IsCompressed) diff --git a/LibHac/Pfs.cs b/LibHac/Pfs.cs index 83290b13..bafff8e1 100644 --- a/LibHac/Pfs.cs +++ b/LibHac/Pfs.cs @@ -202,11 +202,11 @@ namespace LibHac { public static void Extract(this Pfs pfs, string outDir, IProgressReport logger = null) { - foreach (var file in pfs.Header.Files) + foreach (PfsFileEntry file in pfs.Header.Files) { - var stream = pfs.OpenFile(file); - var outName = Path.Combine(outDir, file.Name); - var dir = Path.GetDirectoryName(outName); + Stream stream = pfs.OpenFile(file); + string outName = Path.Combine(outDir, file.Name); + string dir = Path.GetDirectoryName(outName); if (!string.IsNullOrWhiteSpace(dir)) Directory.CreateDirectory(dir); using (var outFile = new FileStream(outName, FileMode.Create, FileAccess.ReadWrite)) diff --git a/LibHac/Pfs0Builder.cs b/LibHac/Pfs0Builder.cs index 7ccab810..b8f9ceb7 100644 --- a/LibHac/Pfs0Builder.cs +++ b/LibHac/Pfs0Builder.cs @@ -29,14 +29,14 @@ namespace LibHac var stringWriter = new BinaryWriter(strings); var writer = new BinaryWriter(output); - foreach (var entry in Entries) + foreach (Entry entry in Entries) { entry.StringOffset = (int)strings.Length; stringWriter.WriteUTF8Z(entry.Name); } strings.Position = Util.GetNextMultiple(strings.Length, 0x10); - var stringTable = strings.ToArray(); + byte[] stringTable = strings.ToArray(); output.Position = 0; writer.WriteUTF8("PFS0"); @@ -44,7 +44,7 @@ namespace LibHac writer.Write(stringTable.Length); writer.Write(0); - foreach (var entry in Entries) + foreach (Entry entry in Entries) { writer.Write(entry.Offset); writer.Write(entry.Length); @@ -54,7 +54,7 @@ namespace LibHac writer.Write(stringTable); - foreach (var entry in Entries) + foreach (Entry entry in Entries) { logger?.LogMessage(entry.Name); entry.Stream.Position = 0; diff --git a/LibHac/ProgressBar.cs b/LibHac/ProgressBar.cs index 5f9d7e69..b5d4f5f0 100644 --- a/LibHac/ProgressBar.cs +++ b/LibHac/ProgressBar.cs @@ -74,7 +74,7 @@ namespace LibHac private void UpdateText(string text) { - StringBuilder outputBuilder = new StringBuilder(); + var outputBuilder = new StringBuilder(); if (LogText.Length > 0) { diff --git a/LibHac/Romfs.cs b/LibHac/Romfs.cs index 1e7fbb0b..6892303f 100644 --- a/LibHac/Romfs.cs +++ b/LibHac/Romfs.cs @@ -78,7 +78,7 @@ namespace LibHac public byte[] GetFile(string filename) { - var stream = OpenFile(filename); + Stream stream = OpenFile(filename); var file = new byte[stream.Length]; using (var ms = new MemoryStream(file)) { @@ -94,10 +94,10 @@ namespace LibHac private void SetReferences() { - var dirDict = Directories.ToDictionary(x => x.Offset, x => x); - var fileDict = Files.ToDictionary(x => x.Offset, x => x); + Dictionary dirDict = Directories.ToDictionary(x => x.Offset, x => x); + Dictionary fileDict = Files.ToDictionary(x => x.Offset, x => x); - foreach (var dir in Directories) + foreach (RomfsDir dir in Directories) { if (dir.ParentOffset >= 0 && dir.ParentOffset != dir.Offset) dir.Parent = dirDict[dir.ParentOffset]; if (dir.NextSiblingOffset >= 0) dir.NextSibling = dirDict[dir.NextSiblingOffset]; @@ -106,7 +106,7 @@ namespace LibHac if (dir.NextDirHashOffset >= 0) dir.NextDirHash = dirDict[dir.NextDirHashOffset]; } - foreach (var file in Files) + foreach (RomfsFile file in Files) { if (file.ParentDirOffset >= 0) file.ParentDir = dirDict[file.ParentDirOffset]; if (file.NextSiblingOffset >= 0) file.NextSibling = fileDict[file.NextSiblingOffset]; @@ -118,11 +118,11 @@ namespace LibHac { var list = new List(); var sb = new StringBuilder(); - var delimiter = "/"; - foreach (var file in Files) + string delimiter = "/"; + foreach (RomfsFile file in Files) { list.Add(file.Name); - var dir = file.ParentDir; + RomfsDir dir = file.ParentDir; while (dir != null) { list.Add(delimiter); @@ -246,11 +246,11 @@ namespace LibHac { public static void Extract(this Romfs romfs, string outDir, IProgressReport logger = null) { - foreach (var file in romfs.Files) + foreach (RomfsFile file in romfs.Files) { - var stream = romfs.OpenFile(file); - var outName = outDir + file.FullPath; - var dir = Path.GetDirectoryName(outName); + Stream stream = romfs.OpenFile(file); + string outName = outDir + file.FullPath; + string dir = Path.GetDirectoryName(outName); if (!string.IsNullOrWhiteSpace(dir)) Directory.CreateDirectory(dir); using (var outFile = new FileStream(outName, FileMode.Create, FileAccess.ReadWrite)) diff --git a/LibHac/Savefile/AllocationTableIterator.cs b/LibHac/Savefile/AllocationTableIterator.cs index 15f4be92..8bd477aa 100644 --- a/LibHac/Savefile/AllocationTableIterator.cs +++ b/LibHac/Savefile/AllocationTableIterator.cs @@ -21,7 +21,7 @@ namespace LibHac.Savefile public bool BeginIteration(int initialBlock) { - var tableEntry = Fat.Entries[initialBlock + 1]; + AllocationTableEntry tableEntry = Fat.Entries[initialBlock + 1]; if (!tableEntry.IsListStart()) { @@ -34,7 +34,7 @@ namespace LibHac.Savefile } else { - var lengthEntry = Fat.Entries[initialBlock + 2]; + AllocationTableEntry lengthEntry = Fat.Entries[initialBlock + 2]; CurrentSegmentSize = lengthEntry.Next - initialBlock; } @@ -45,11 +45,11 @@ namespace LibHac.Savefile public bool MoveNext() { - var currentEntry = Fat.Entries[PhysicalBlock + 1]; + AllocationTableEntry currentEntry = Fat.Entries[PhysicalBlock + 1]; if (currentEntry.IsListEnd()) return false; int newBlock = currentEntry.Next & 0x7FFFFFFF; - var newEntry = Fat.Entries[newBlock]; + AllocationTableEntry newEntry = Fat.Entries[newBlock]; VirtualBlock += CurrentSegmentSize; if (newEntry.IsSingleBlockSegment()) @@ -58,7 +58,7 @@ namespace LibHac.Savefile } else { - var lengthEntry = Fat.Entries[newBlock + 1]; + AllocationTableEntry lengthEntry = Fat.Entries[newBlock + 1]; CurrentSegmentSize = lengthEntry.Next - (newBlock - 1); } @@ -68,11 +68,11 @@ namespace LibHac.Savefile public bool MovePrevious() { - var currentEntry = Fat.Entries[PhysicalBlock + 1]; + AllocationTableEntry currentEntry = Fat.Entries[PhysicalBlock + 1]; if (currentEntry.IsListStart()) return false; int newBlock = currentEntry.Prev & 0x7FFFFFFF; - var newEntry = Fat.Entries[newBlock]; + AllocationTableEntry newEntry = Fat.Entries[newBlock]; if (newEntry.IsSingleBlockSegment()) { @@ -80,7 +80,7 @@ namespace LibHac.Savefile } else { - var lengthEntry = Fat.Entries[newBlock + 1]; + AllocationTableEntry lengthEntry = Fat.Entries[newBlock + 1]; CurrentSegmentSize = lengthEntry.Next - (newBlock - 1); } diff --git a/LibHac/Savefile/AllocationTableStream.cs b/LibHac/Savefile/AllocationTableStream.cs index e67dd808..5e7ac86f 100644 --- a/LibHac/Savefile/AllocationTableStream.cs +++ b/LibHac/Savefile/AllocationTableStream.cs @@ -33,7 +33,7 @@ namespace LibHac.Savefile while (remaining > 0) { - var remainingInSegment = Iterator.CurrentSegmentSize * BlockSize - SegmentPos; + int remainingInSegment = Iterator.CurrentSegmentSize * BlockSize - SegmentPos; int bytesToRead = Math.Min(remaining, remainingInSegment); int bytesRead = Data.Read(buffer, outOffset, bytesToRead); @@ -91,7 +91,7 @@ namespace LibHac.Savefile } } - var segmentPos = value - (Iterator.VirtualBlock * BlockSize); + long segmentPos = value - (Iterator.VirtualBlock * BlockSize); Data.Position = Iterator.PhysicalBlock * BlockSize + segmentPos; } } diff --git a/LibHac/Savefile/DuplexFs.cs b/LibHac/Savefile/DuplexFs.cs index 70ae4fb3..eae08cd1 100644 --- a/LibHac/Savefile/DuplexFs.cs +++ b/LibHac/Savefile/DuplexFs.cs @@ -44,7 +44,7 @@ namespace LibHac.Savefile int blockPos = (int)(Position % BlockSize); int bytesToRead = (int)Math.Min(remaining, BlockSize - blockPos); - var data = Bitmap.Bitmap[blockNum] ? DataB : DataA; + Stream data = Bitmap.Bitmap[blockNum] ? DataB : DataA; data.Position = blockNum * BlockSize + blockPos; data.Read(buffer, outOffset, bytesToRead); diff --git a/LibHac/Savefile/FsEntry.cs b/LibHac/Savefile/FsEntry.cs index 1729e891..ab9ab87e 100644 --- a/LibHac/Savefile/FsEntry.cs +++ b/LibHac/Savefile/FsEntry.cs @@ -18,11 +18,11 @@ namespace LibHac.Savefile { var list = new List(); var sb = new StringBuilder(); - var delimiter = "/"; - foreach (var file in entries) + string delimiter = "/"; + foreach (FsEntry file in entries) { list.Add(file.Name); - var dir = file.ParentDir; + DirectoryEntry dir = file.ParentDir; while (dir != null) { list.Add(delimiter); @@ -55,7 +55,7 @@ namespace LibHac.Savefile public FileEntry(BinaryReader reader) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; ParentDirIndex = reader.ReadInt32(); Name = reader.ReadUtf8Z(0x40); reader.BaseStream.Position = start + 0x44; @@ -83,7 +83,7 @@ namespace LibHac.Savefile public DirectoryEntry(BinaryReader reader) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; ParentDirIndex = reader.ReadInt32(); Name = reader.ReadUtf8Z(0x40); reader.BaseStream.Position = start + 0x44; diff --git a/LibHac/Savefile/Header.cs b/LibHac/Savefile/Header.cs index 17c95bdf..47f28c23 100644 --- a/LibHac/Savefile/Header.cs +++ b/LibHac/Savefile/Header.cs @@ -93,7 +93,7 @@ namespace LibHac.Savefile { using (SHA256 sha256 = SHA256.Create()) { - var hash = sha256.ComputeHash(Data, 0x300, 0x3d00); + byte[] hash = sha256.ComputeHash(Data, 0x300, 0x3d00); return Util.ArraysEqual(hash, Layout.Hash) ? Validity.Valid : Validity.Invalid; } } diff --git a/LibHac/Savefile/Journal.cs b/LibHac/Savefile/Journal.cs index 017701cf..ad511206 100644 --- a/LibHac/Savefile/Journal.cs +++ b/LibHac/Savefile/Journal.cs @@ -28,12 +28,12 @@ namespace LibHac.Savefile if (remaining <= 0) return 0; if (remaining < count) count = (int)remaining; - var toOutput = count; + int toOutput = count; int outPos = offset; while (toOutput > 0) { - var remainInEntry = BlockSize - Position % BlockSize; + long remainInEntry = BlockSize - Position % BlockSize; int toRead = (int)Math.Min(toOutput, remainInEntry); BaseStream.Read(buffer, outPos, toRead); @@ -77,8 +77,8 @@ namespace LibHac.Savefile { _position = value; if (value >= Length) return; - var currentBlock = value / BlockSize; - var blockPos = value % BlockSize; + long currentBlock = value / BlockSize; + long blockPos = value % BlockSize; CurrentMapEntry = Map[currentBlock]; BaseStream.Position = CurrentMapEntry.PhysicalIndex * BlockSize + blockPos; } diff --git a/LibHac/Savefile/RemapStream.cs b/LibHac/Savefile/RemapStream.cs index f2803c93..f0f5e735 100644 --- a/LibHac/Savefile/RemapStream.cs +++ b/LibHac/Savefile/RemapStream.cs @@ -52,12 +52,12 @@ namespace LibHac.Savefile if (remaining <= 0) return 0; if (remaining < count) count = (int)remaining; - var toOutput = count; + int toOutput = count; int outPos = offset; while (toOutput > 0) { - var remainInEntry = CurrentEntry.VirtualOffsetEnd - Position; + long remainInEntry = CurrentEntry.VirtualOffsetEnd - Position; int toRead = (int)Math.Min(toOutput, remainInEntry); BaseStream.Read(buffer, outPos, toRead); outPos += toRead; @@ -104,7 +104,7 @@ namespace LibHac.Savefile private MapEntry GetMapEntry(long offset) { // todo: is O(n) search a possible performance issue? - var entry = MapEntries.FirstOrDefault(x => offset >= x.VirtualOffset && offset < x.VirtualOffsetEnd); + MapEntry entry = MapEntries.FirstOrDefault(x => offset >= x.VirtualOffset && offset < x.VirtualOffsetEnd); if (entry == null) throw new ArgumentOutOfRangeException(nameof(offset)); return entry; } @@ -113,7 +113,7 @@ namespace LibHac.Savefile { // At end of virtual stream if (CurrentEntry == null) return; - var entryOffset = Position - CurrentEntry.VirtualOffset; + long entryOffset = Position - CurrentEntry.VirtualOffset; BaseStream.Position = CurrentEntry.PhysicalOffset + entryOffset; } diff --git a/LibHac/Savefile/Savefile.cs b/LibHac/Savefile/Savefile.cs index f0e87977..d87dc2f8 100644 --- a/LibHac/Savefile/Savefile.cs +++ b/LibHac/Savefile/Savefile.cs @@ -99,9 +99,9 @@ namespace LibHac.Savefile JournalFat = MetaRemapSource.CreateStream(layout.FatOffset, layout.FatSize); AllocationTable = new AllocationTable(JournalFat); - var journalMap = JournalStream.ReadMappingEntries(JournalTable, Header.Journal.MainDataBlockCount); + MappingEntry[] journalMap = JournalStream.ReadMappingEntries(JournalTable, Header.Journal.MainDataBlockCount); - var journalData = FileRemapSource.CreateStream(layout.JournalDataOffset, + SharedStream journalData = FileRemapSource.CreateStream(layout.JournalDataOffset, layout.JournalDataSizeB + layout.SizeReservedArea); JournalStream = new JournalStream(journalData, journalMap, (int)Header.Journal.BlockSize); JournalStreamSource = new SharedStreamSource(JournalStream); @@ -110,7 +110,7 @@ namespace LibHac.Savefile IvfcStreamSource = new SharedStreamSource(IvfcStream); ReadFileInfo(); - Dictionary dictionary = new Dictionary(); + var dictionary = new Dictionary(); foreach (FileEntry entry in Files) { dictionary[entry.FullPath] = entry; @@ -184,8 +184,8 @@ namespace LibHac.Savefile private void ReadFileInfo() { // todo: Query the FAT for the file size when none is given - var dirTableStream = OpenFatBlock(Header.Save.DirectoryTableBlock, 1000000); - var fileTableStream = OpenFatBlock(Header.Save.FileTableBlock, 1000000); + AllocationTableStream dirTableStream = OpenFatBlock(Header.Save.DirectoryTableBlock, 1000000); + AllocationTableStream fileTableStream = OpenFatBlock(Header.Save.FileTableBlock, 1000000); DirectoryEntry[] dirEntries = ReadDirEntries(dirTableStream); FileEntry[] fileEntries = ReadFileEntries(fileTableStream); @@ -210,7 +210,7 @@ namespace LibHac.Savefile RootDirectory = dirEntries[2]; - var fileChain = fileEntries[1].NextInChain; + FileEntry fileChain = fileEntries[1].NextInChain; var files = new List(); while (fileChain != null) { @@ -218,7 +218,7 @@ namespace LibHac.Savefile fileChain = fileChain.NextInChain; } - var dirChain = dirEntries[1].NextInChain; + DirectoryEntry dirChain = dirEntries[1].NextInChain; var dirs = new List(); while (dirChain != null) { @@ -236,7 +236,7 @@ namespace LibHac.Savefile private FileEntry[] ReadFileEntries(Stream stream) { var reader = new BinaryReader(stream); - var count = reader.ReadInt32(); + int count = reader.ReadInt32(); reader.BaseStream.Position -= 4; @@ -252,7 +252,7 @@ namespace LibHac.Savefile private DirectoryEntry[] ReadDirEntries(Stream stream) { var reader = new BinaryReader(stream); - var count = reader.ReadInt32(); + int count = reader.ReadInt32(); reader.BaseStream.Position -= 4; @@ -272,7 +272,7 @@ namespace LibHac.Savefile var data = new byte[0x200]; var cmac = new byte[0x10]; - var headerStream = SavefileSource.CreateStream(); + SharedStream headerStream = SavefileSource.CreateStream(); headerStream.Position = 0x100; headerStream.Read(data, 0, 0x200); @@ -299,11 +299,11 @@ namespace LibHac.Savefile { public static void Extract(this Savefile save, string outDir, IProgressReport logger = null) { - foreach (var file in save.Files) + foreach (FileEntry file in save.Files) { - var stream = save.OpenFile(file); - var outName = outDir + file.FullPath; - var dir = Path.GetDirectoryName(outName); + Stream stream = save.OpenFile(file); + string outName = outDir + file.FullPath; + string dir = Path.GetDirectoryName(outName); if (!string.IsNullOrWhiteSpace(dir)) Directory.CreateDirectory(dir); using (var outFile = new FileStream(outName, FileMode.Create, FileAccess.ReadWrite)) diff --git a/LibHac/Streams/CombinationStream.cs b/LibHac/Streams/CombinationStream.cs index 937ae496..e37a3883 100644 --- a/LibHac/Streams/CombinationStream.cs +++ b/LibHac/Streams/CombinationStream.cs @@ -56,7 +56,7 @@ namespace LibHac.Streams _streamsStartPos = new List(streams.Count); long pos = 0; - foreach (var strm in streams) + foreach (Stream strm in streams) { _streamsStartPos.Add(pos); pos += strm.Length; @@ -170,7 +170,7 @@ namespace LibHac.Streams #else public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { - CombinationStreamAsyncResult asyncResult = new CombinationStreamAsyncResult(state); + var asyncResult = new CombinationStreamAsyncResult(state); if (count > 0) { int buffPostion = offset; @@ -302,7 +302,7 @@ namespace LibHac.Streams base.Dispose(disposing); if (_streamsToDispose == null) { - foreach (var stream in InternalStreams) + foreach (Stream stream in InternalStreams) stream.Dispose(); } else @@ -335,7 +335,7 @@ namespace LibHac.Streams if (_length == -1) { _length = 0; - foreach (var stream in _streams) + foreach (Stream stream in _streams) _length += stream.Length; } diff --git a/LibHac/Streams/RandomAccessSectorStream.cs b/LibHac/Streams/RandomAccessSectorStream.cs index abd257ac..29ccda27 100644 --- a/LibHac/Streams/RandomAccessSectorStream.cs +++ b/LibHac/Streams/RandomAccessSectorStream.cs @@ -117,7 +117,7 @@ namespace LibHac.Streams { if (_readBytes == 0) FillBuffer(Position / _bufferSize); - var bytesToWrite = Math.Min(remaining, _readBytes - _bufferPos); + int bytesToWrite = Math.Min(remaining, _readBytes - _bufferPos); Buffer.BlockCopy(buffer, outOffset, _buffer, _bufferPos, bytesToWrite); diff --git a/LibHac/Streams/SharedStream.cs b/LibHac/Streams/SharedStream.cs index 325a511c..6a26d71c 100644 --- a/LibHac/Streams/SharedStream.cs +++ b/LibHac/Streams/SharedStream.cs @@ -24,7 +24,7 @@ namespace LibHac.Streams if (remaining <= 0) return 0; if (remaining < count) count = (int)remaining; - var bytesRead = _stream.Read(_offset + _position, buffer, offset, count); + int bytesRead = _stream.Read(_offset + _position, buffer, offset, count); _position += bytesRead; return bytesRead; } diff --git a/LibHac/SwitchFs.cs b/LibHac/SwitchFs.cs index 0649ffa2..a009ff83 100644 --- a/LibHac/SwitchFs.cs +++ b/LibHac/SwitchFs.cs @@ -59,7 +59,7 @@ namespace LibHac { string[] files = Fs.GetFileSystemEntries(ContentsDir, "*.nca", SearchOption.AllDirectories); - foreach (var file in files) + foreach (string file in files) { Nca nca = null; try @@ -77,7 +77,7 @@ namespace LibHac if (isNax0) { - var sdPath = "/" + Util.GetRelativePath(file, ContentsDir).Replace('\\', '/'); + string sdPath = "/" + Util.GetRelativePath(file, ContentsDir).Replace('\\', '/'); var nax0 = new Nax0(Keyset, stream, sdPath, false); nca = new Nca(Keyset, nax0.Stream, false); } @@ -87,7 +87,7 @@ namespace LibHac } nca.NcaId = Path.GetFileNameWithoutExtension(file); - var extension = nca.Header.ContentType == ContentType.Meta ? ".cnmt.nca" : ".nca"; + string extension = nca.Header.ContentType == ContentType.Meta ? ".cnmt.nca" : ".nca"; nca.Filename = nca.NcaId + extension; } catch (MissingKeyException ex) @@ -142,14 +142,14 @@ namespace LibHac private void ReadTitles() { - foreach (var nca in Ncas.Values.Where(x => x.Header.ContentType == ContentType.Meta)) + foreach (Nca nca in Ncas.Values.Where(x => x.Header.ContentType == ContentType.Meta)) { var title = new Title(); // Meta contents always have 1 Partition FS section with 1 file in it Stream sect = nca.OpenSection(0, false, true); var pfs0 = new Pfs(sect); - var file = pfs0.OpenFile(pfs0.Files[0]); + Stream file = pfs0.OpenFile(pfs0.Files[0]); var metadata = new Cnmt(file); title.Id = metadata.TitleId; @@ -158,9 +158,9 @@ namespace LibHac title.MetaNca = nca; title.Ncas.Add(nca); - foreach (var content in metadata.ContentEntries) + foreach (CnmtContentEntry content in metadata.ContentEntries) { - var ncaId = content.NcaId.ToHexString(); + string ncaId = content.NcaId.ToHexString(); if (Ncas.TryGetValue(ncaId, out Nca contentNca)) { @@ -185,15 +185,15 @@ namespace LibHac private void ReadControls() { - foreach (var title in Titles.Values.Where(x => x.ControlNca != null)) + foreach (Title title in Titles.Values.Where(x => x.ControlNca != null)) { var romfs = new Romfs(title.ControlNca.OpenSection(0, false, true)); - var control = romfs.GetFile("/control.nacp"); + byte[] control = romfs.GetFile("/control.nacp"); var reader = new BinaryReader(new MemoryStream(control)); title.Control = new Nacp(reader); - foreach (var lang in title.Control.Languages) + foreach (NacpLang lang in title.Control.Languages) { if (!string.IsNullOrWhiteSpace(lang.Title)) { @@ -206,12 +206,12 @@ namespace LibHac private void CreateApplications() { - foreach (var title in Titles.Values.Where(x => x.Metadata.Type >= TitleType.Application)) + foreach (Title title in Titles.Values.Where(x => x.Metadata.Type >= TitleType.Application)) { - var meta = title.Metadata; + Cnmt meta = title.Metadata; ulong appId = meta.ApplicationTitleId; - if (!Applications.TryGetValue(appId, out var app)) + if (!Applications.TryGetValue(appId, out Application app)) { app = new Application(); Applications.Add(appId, app); @@ -220,10 +220,10 @@ namespace LibHac app.AddTitle(title); } - foreach (var app in Applications.Values) + foreach (Application app in Applications.Values) { - var main = app.Main?.MainNca; - var patch = app.Patch?.MainNca; + Nca main = app.Main?.MainNca; + Nca patch = app.Patch?.MainNca; if (main != null) { @@ -234,14 +234,14 @@ namespace LibHac internal static Stream OpenSplitNcaStream(IFileSystem fs, string path) { - List files = new List(); - List streams = new List(); + var files = new List(); + var streams = new List(); if (fs.DirectoryExists(path)) { while (true) { - var partName = Path.Combine(path, $"{files.Count:D2}"); + string partName = Path.Combine(path, $"{files.Count:D2}"); if (!fs.FileExists(partName)) break; files.Add(partName); @@ -260,7 +260,7 @@ namespace LibHac throw new FileNotFoundException("Could not find the input file or directory"); } - foreach (var file in files) + foreach (string file in files) { streams.Add(fs.OpenFile(file, FileMode.Open, FileAccess.Read)); } diff --git a/LibHac/Ticket.cs b/LibHac/Ticket.cs index 8fb4ac4a..ad81becd 100644 --- a/LibHac/Ticket.cs +++ b/LibHac/Ticket.cs @@ -38,7 +38,7 @@ namespace LibHac public Ticket(BinaryReader reader) { - var fileStart = reader.BaseStream.Position; + long fileStart = reader.BaseStream.Position; SignatureType = (TicketSigType)reader.ReadUInt32(); switch (SignatureType) @@ -62,7 +62,7 @@ namespace LibHac throw new ArgumentOutOfRangeException(); } - var dataStart = reader.BaseStream.Position; + long dataStart = reader.BaseStream.Position; Issuer = reader.ReadUtf8Z(0x40); reader.BaseStream.Position = dataStart + 0x40; @@ -111,7 +111,7 @@ namespace LibHac throw new ArgumentOutOfRangeException(); } - var bodyStart = Util.GetNextMultiple(4 + sigLength, 0x40); + long bodyStart = Util.GetNextMultiple(4 + sigLength, 0x40); writer.Write((int)SignatureType); diff --git a/LibHac/Util.cs b/LibHac/Util.cs index 60ae9e1f..72496542 100644 --- a/LibHac/Util.cs +++ b/LibHac/Util.cs @@ -66,7 +66,7 @@ namespace LibHac { const int bufferSize = 0x8000; long remaining = length; - byte[] buffer = new byte[bufferSize]; + var buffer = new byte[bufferSize]; progress?.SetTotal(length); int read; @@ -90,7 +90,7 @@ namespace LibHac public static string ReadAsciiZ(this BinaryReader reader, int maxLength = int.MaxValue) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; int size = 0; // Read until we hit the end of the stream (-1) or a zero @@ -107,7 +107,7 @@ namespace LibHac public static string ReadUtf8Z(this BinaryReader reader, int maxLength = int.MaxValue) { - var start = reader.BaseStream.Position; + long start = reader.BaseStream.Position; int size = 0; // Read until we hit the end of the stream (-1) or a zero @@ -267,11 +267,11 @@ namespace LibHac public static string ToHexString(this byte[] bytes) { - var lookup32 = Lookup32; + uint[] lookup32 = Lookup32; var result = new char[bytes.Length * 2]; for (int i = 0; i < bytes.Length; i++) { - var val = lookup32[bytes[i]]; + uint val = lookup32[bytes[i]]; result[2 * i] = (char)val; result[2 * i + 1] = (char)(val >> 16); } @@ -283,37 +283,38 @@ namespace LibHac return MediaSize * media; } + // https://stackoverflow.com/a/11124118 public static string GetBytesReadable(long bytes) { // Get absolute value - long absBytes = (bytes < 0 ? -bytes : bytes); + long absBytes = bytes < 0 ? -bytes : bytes; // Determine the suffix and readable value string suffix; double readable; if (absBytes >= 0x1000000000000000) // Exabyte { suffix = "EB"; - readable = (bytes >> 50); + readable = bytes >> 50; } else if (absBytes >= 0x4000000000000) // Petabyte { suffix = "PB"; - readable = (bytes >> 40); + readable = bytes >> 40; } else if (absBytes >= 0x10000000000) // Terabyte { suffix = "TB"; - readable = (bytes >> 30); + readable = bytes >> 30; } else if (absBytes >= 0x40000000) // Gigabyte { suffix = "GB"; - readable = (bytes >> 20); + readable = bytes >> 20; } else if (absBytes >= 0x100000) // Megabyte { suffix = "MB"; - readable = (bytes >> 10); + readable = bytes >> 10; } else if (absBytes >= 0x400) // Kilobyte { @@ -325,7 +326,7 @@ namespace LibHac return bytes.ToString("0 B"); // Byte } // Divide by 1024 to get fractional value - readable = (readable / 1024); + readable = readable / 1024; // Return formatted number with suffix return readable.ToString("0.### ") + suffix; } @@ -362,7 +363,7 @@ namespace LibHac { int max = 32; - var remaining = data.Length; + int remaining = data.Length; bool first = true; int offset = 0; @@ -438,11 +439,10 @@ namespace LibHac throw new ArgumentException("Length must be 16 bytes"); } - var hi = BitConverter.ToUInt64(obj, 0); - var lo = BitConverter.ToUInt64(obj, 8); + ulong hi = BitConverter.ToUInt64(obj, 0); + ulong lo = BitConverter.ToUInt64(obj, 8); return (hi.GetHashCode() * 397) ^ lo.GetHashCode(); } - } } diff --git a/LibHac/XTSSharp/XtsAes128.cs b/LibHac/XTSSharp/XtsAes128.cs index 72656bf8..c18ab2cf 100644 --- a/LibHac/XTSSharp/XtsAes128.cs +++ b/LibHac/XTSSharp/XtsAes128.cs @@ -70,8 +70,8 @@ namespace LibHac.XTSSharp { VerifyKey(KeyLength * 2, key); - byte[] key1 = new byte[KeyByteLength]; - byte[] key2 = new byte[KeyByteLength]; + var key1 = new byte[KeyByteLength]; + var key2 = new byte[KeyByteLength]; Buffer.BlockCopy(key, 0, key1, 0, KeyByteLength); Buffer.BlockCopy(key, KeyByteLength, key2, 0, KeyByteLength); diff --git a/LibHac/XTSSharp/XtsCryptoTransform.cs b/LibHac/XTSSharp/XtsCryptoTransform.cs index 844e364d..d295cef0 100644 --- a/LibHac/XTSSharp/XtsCryptoTransform.cs +++ b/LibHac/XTSSharp/XtsCryptoTransform.cs @@ -100,8 +100,8 @@ namespace LibHac.XTSSharp int lim; /* get number of blocks */ - var m = inputCount >> 4; - var mo = inputCount & 15; + int m = inputCount >> 4; + int mo = inputCount & 15; /* encrypt the tweak */ _key2.TransformBlock(_tweak, 0, _tweak.Length, _t, 0); @@ -112,7 +112,7 @@ namespace LibHac.XTSSharp else lim = m - 1; - for (var i = 0; i < lim; i++) + for (int i = 0; i < lim; i++) { TweakCrypt(inputBuffer, inputOffset, outputBuffer, outputOffset, _t); inputOffset += 16; @@ -194,14 +194,14 @@ namespace LibHac.XTSSharp /// private void TweakCrypt(byte[] inputBuffer, int inputOffset, byte[] outputBuffer, int outputOffset, byte[] t) { - for (var x = 0; x < 16; x++) + for (int x = 0; x < 16; x++) { outputBuffer[x + outputOffset] = (byte)(inputBuffer[x + inputOffset] ^ t[x]); } _key1.TransformBlock(outputBuffer, outputOffset, 16, outputBuffer, outputOffset); - for (var x = 0; x < 16; x++) + for (int x = 0; x < 16; x++) { outputBuffer[x + outputOffset] = (byte)(outputBuffer[x + outputOffset] ^ t[x]); } @@ -217,7 +217,7 @@ namespace LibHac.XTSSharp { byte t = 0, tt = 0; - for (var x = 0; x < 16; x++) + for (int x = 0; x < 16; x++) { tt = (byte)(i[x] >> 7); i[x] = (byte)(((i[x] << 1) | t) & 0xFF); diff --git a/LibHac/XTSSharp/XtsSectorStream.cs b/LibHac/XTSSharp/XtsSectorStream.cs index 9a02af22..812dc25f 100644 --- a/LibHac/XTSSharp/XtsSectorStream.cs +++ b/LibHac/XTSSharp/XtsSectorStream.cs @@ -108,7 +108,7 @@ namespace LibHac.XTSSharp return; //get the current sector - var currentSector = CurrentSector; + long currentSector = CurrentSector; if (_encryptor == null) _encryptor = _xts.CreateEncryptor(); @@ -134,10 +134,10 @@ namespace LibHac.XTSSharp ValidateSize(count); //get the current sector - var currentSector = CurrentSector; + long currentSector = CurrentSector; //read the sector from the base stream - var ret = base.Read(_tempBuffer, 0, count); + int ret = base.Read(_tempBuffer, 0, count); if (ret == 0) return 0; @@ -146,7 +146,7 @@ namespace LibHac.XTSSharp _decryptor = _xts.CreateDecryptor(); //decrypt the sector - var retV = _decryptor.TransformBlock(_tempBuffer, 0, ret, buffer, offset, (ulong) currentSector); + int retV = _decryptor.TransformBlock(_tempBuffer, 0, ret, buffer, offset, (ulong) currentSector); //Console.WriteLine("Decrypting sector {0} == {1} bytes", currentSector, retV); diff --git a/LibHac/XciHeader.cs b/LibHac/XciHeader.cs index 9f524bef..fbe8decc 100644 --- a/LibHac/XciHeader.cs +++ b/LibHac/XciHeader.cs @@ -114,7 +114,7 @@ namespace LibHac if (!keyset.XciHeaderKey.IsEmpty()) { - var encHeader = reader.ReadBytes(EncryptedHeaderSize); + byte[] encHeader = reader.ReadBytes(EncryptedHeaderSize); var decHeader = new byte[EncryptedHeaderSize]; Crypto.DecryptCbc(keyset.XciHeaderKey, AesCbcIv, encHeader, decHeader, EncryptedHeaderSize); diff --git a/NandReader/Program.cs b/NandReader/Program.cs index 8b9f04cc..37c9d3bf 100644 --- a/NandReader/Program.cs +++ b/NandReader/Program.cs @@ -25,17 +25,17 @@ namespace NandReader using (var logger = new ProgressBar()) using (var stream = new FileStream(nandFile, FileMode.Open, FileAccess.Read)) { - var keyset = OpenKeyset(); + Keyset keyset = OpenKeyset(); var nand = new Nand(stream, keyset); - var prodinfo = nand.OpenProdInfo(); + Stream prodinfo = nand.OpenProdInfo(); var calibration = new Calibration(prodinfo); keyset.EticketExtKeyRsa = Crypto.DecryptRsaKey(calibration.EticketExtKeyRsa, keyset.EticketRsaKek); - var tickets = GetTickets(keyset, nand, logger); + Ticket[] tickets = GetTickets(keyset, nand, logger); - foreach (var ticket in tickets) + foreach (Ticket ticket in tickets) { - var key = ticket.GetTitleKey(keyset); + byte[] key = ticket.GetTitleKey(keyset); logger.LogMessage($"{ticket.RightsId.ToHexString()},{key.ToHexString()}"); } } @@ -46,9 +46,9 @@ namespace NandReader using (var logger = new ProgressBar()) using (var stream = new FileStream(nandFile, FileMode.Open, FileAccess.Read)) { - var keyset = OpenKeyset(); + Keyset keyset = OpenKeyset(); var nand = new Nand(stream, keyset); - var user = nand.OpenSystemPartition(); + NandPartition user = nand.OpenSystemPartition(); var sdfs = new SwitchFs(keyset, user); } } @@ -58,9 +58,9 @@ namespace NandReader using (var logger = new ProgressBar()) using (var stream = new FileStream(nandFile, FileMode.Open, FileAccess.Read)) { - var keyset = OpenKeyset(); + Keyset keyset = OpenKeyset(); var nand = new Nand(stream, keyset); - var prodinfo = nand.OpenProdInfo(); + Stream prodinfo = nand.OpenProdInfo(); var calibration = new Calibration(prodinfo); } } @@ -70,14 +70,14 @@ namespace NandReader using (var logger = new ProgressBar()) using (var stream = new FileStream(nandFile, FileMode.Open, FileAccess.Read)) { - var keyset = OpenKeyset(); + Keyset keyset = OpenKeyset(); var nand = new Nand(stream, keyset); - var tickets = GetTickets(keyset, nand, logger); + Ticket[] tickets = GetTickets(keyset, nand, logger); Directory.CreateDirectory("tickets"); - foreach (var ticket in tickets) + foreach (Ticket ticket in tickets) { - var filename = Path.Combine("tickets", $"{ticket.RightsId.ToHexString()}.tik"); + string filename = Path.Combine("tickets", $"{ticket.RightsId.ToHexString()}.tik"); File.WriteAllBytes(filename, ticket.File); } } @@ -86,12 +86,12 @@ namespace NandReader private static Ticket[] GetTickets(Keyset keyset, Nand nand, IProgressReport logger = null) { var tickets = new List(); - var system = nand.OpenSystemPartition(); + NandPartition system = nand.OpenSystemPartition(); - var saveE1File = system.OpenFile("save\\80000000000000E1", FileMode.Open, FileAccess.Read); + Stream saveE1File = system.OpenFile("save\\80000000000000E1", FileMode.Open, FileAccess.Read); tickets.AddRange(ReadTickets(keyset, saveE1File)); - var saveE2 = system.OpenFile("save\\80000000000000E2", FileMode.Open, FileAccess.Read); + Stream saveE2 = system.OpenFile("save\\80000000000000E2", FileMode.Open, FileAccess.Read); tickets.AddRange(ReadTickets(keyset, saveE2)); logger?.LogMessage($"Found {tickets.Count} tickets"); @@ -106,11 +106,11 @@ namespace NandReader var ticketList = new BinaryReader(save.OpenFile("/ticket_list.bin")); var ticketFile = new BinaryReader(save.OpenFile("/ticket.bin")); - var titleId = ticketList.ReadUInt64(); + ulong titleId = ticketList.ReadUInt64(); while (titleId != ulong.MaxValue) { ticketList.BaseStream.Position += 0x18; - var start = ticketFile.BaseStream.Position; + long start = ticketFile.BaseStream.Position; tickets.Add(new Ticket(ticketFile)); ticketFile.BaseStream.Position = start + 0x400; titleId = ticketList.ReadUInt64(); @@ -121,10 +121,10 @@ namespace NandReader private static Keyset OpenKeyset() { - var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - var homeKeyFile = Path.Combine(home, ".switch", "prod.keys"); - var homeTitleKeyFile = Path.Combine(home, ".switch", "title.keys"); - var homeConsoleKeyFile = Path.Combine(home, ".switch", "console.keys"); + string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + string homeKeyFile = Path.Combine(home, ".switch", "prod.keys"); + string homeTitleKeyFile = Path.Combine(home, ".switch", "title.keys"); + string homeConsoleKeyFile = Path.Combine(home, ".switch", "console.keys"); string keyFile = null; string titleKeyFile = null; string consoleKeyFile = null; diff --git a/NandReaderGui/ViewModel/NandViewModel.cs b/NandReaderGui/ViewModel/NandViewModel.cs index 7e638887..2f4a1504 100644 --- a/NandReaderGui/ViewModel/NandViewModel.cs +++ b/NandReaderGui/ViewModel/NandViewModel.cs @@ -25,7 +25,7 @@ namespace NandReaderGui.ViewModel var query = new WqlObjectQuery("SELECT * FROM Win32_DiskDrive"); using (var searcher = new ManagementObjectSearcher(query)) { - foreach (var drive in searcher.Get()) + foreach (ManagementBaseObject drive in searcher.Get()) { if (drive.GetPropertyValue("Size") == null) continue; var info = new DiskInfo(); @@ -43,23 +43,23 @@ namespace NandReaderGui.ViewModel public void Open() { - var disk = SelectedDisk; + DiskInfo disk = SelectedDisk; var stream = new RandomAccessSectorStream(new SectorStream(new DeviceStream(disk.PhysicalName, disk.Length), disk.SectorSize * 100)); - var keyset = OpenKeyset(); + Keyset keyset = OpenKeyset(); var nand = new Nand(stream, keyset); - var prodinfo = nand.OpenProdInfo(); + Stream prodinfo = nand.OpenProdInfo(); var calibration = new Calibration(prodinfo); keyset.EticketExtKeyRsa = Crypto.DecryptRsaKey(calibration.EticketExtKeyRsa, keyset.EticketRsaKek); - var tickets = GetTickets(keyset, nand); + Ticket[] tickets = GetTickets(keyset, nand); using (var outStream = new StreamWriter("titlekeys.txt")) { - foreach (var ticket in tickets) + foreach (Ticket ticket in tickets) { - var key = ticket.GetTitleKey(keyset); + byte[] key = ticket.GetTitleKey(keyset); outStream.WriteLine($"{ticket.RightsId.ToHexString()},{key.ToHexString()}"); } } @@ -68,12 +68,12 @@ namespace NandReaderGui.ViewModel private static Ticket[] GetTickets(Keyset keyset, Nand nand, IProgressReport logger = null) { var tickets = new List(); - var system = nand.OpenSystemPartition(); + NandPartition system = nand.OpenSystemPartition(); - var saveE1File = system.OpenFile("save\\80000000000000E1", FileMode.Open, FileAccess.Read); + Stream saveE1File = system.OpenFile("save\\80000000000000E1", FileMode.Open, FileAccess.Read); tickets.AddRange(ReadTickets(keyset, saveE1File)); - var saveE2 = system.OpenFile("save\\80000000000000E2", FileMode.Open, FileAccess.Read); + Stream saveE2 = system.OpenFile("save\\80000000000000E2", FileMode.Open, FileAccess.Read); tickets.AddRange(ReadTickets(keyset, saveE2)); logger?.LogMessage($"Found {tickets.Count} tickets"); @@ -88,11 +88,11 @@ namespace NandReaderGui.ViewModel var ticketList = new BinaryReader(save.OpenFile("/ticket_list.bin")); var ticketFile = new BinaryReader(save.OpenFile("/ticket.bin")); - var titleId = ticketList.ReadUInt64(); + ulong titleId = ticketList.ReadUInt64(); while (titleId != ulong.MaxValue) { ticketList.BaseStream.Position += 0x18; - var start = ticketFile.BaseStream.Position; + long start = ticketFile.BaseStream.Position; tickets.Add(new Ticket(ticketFile)); ticketFile.BaseStream.Position = start + 0x400; titleId = ticketList.ReadUInt64(); @@ -103,10 +103,10 @@ namespace NandReaderGui.ViewModel private static Keyset OpenKeyset() { - var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - var homeKeyFile = Path.Combine(home, ".switch", "prod.keys"); - var homeTitleKeyFile = Path.Combine(home, ".switch", "title.keys"); - var homeConsoleKeyFile = Path.Combine(home, ".switch", "console.keys"); + string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + string homeKeyFile = Path.Combine(home, ".switch", "prod.keys"); + string homeTitleKeyFile = Path.Combine(home, ".switch", "title.keys"); + string homeConsoleKeyFile = Path.Combine(home, ".switch", "console.keys"); string keyFile = null; string titleKeyFile = null; string consoleKeyFile = null; diff --git a/hactoolnet/CliParser.cs b/hactoolnet/CliParser.cs index 84a213d7..0d3f3b07 100644 --- a/hactoolnet/CliParser.cs +++ b/hactoolnet/CliParser.cs @@ -51,7 +51,7 @@ namespace hactoolnet public static Options Parse(string[] args) { var options = new Options(); - var inputSpecified = false; + bool inputSpecified = false; for (int i = 0; i < args.Length; i++) { @@ -78,7 +78,7 @@ namespace hactoolnet continue; } - var option = CliOptions.FirstOrDefault(x => x.Long == arg || x.Short == arg); + CliOption option = CliOptions.FirstOrDefault(x => x.Long == arg || x.Short == arg); if (option == null) { PrintWithUsage($"Unknown option {args[i]}"); @@ -124,7 +124,7 @@ namespace hactoolnet PrintWithUsage("Title ID must be 16 hex characters long"); } - if (!ulong.TryParse(input, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var id)) + if (!ulong.TryParse(input, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong id)) { PrintWithUsage("Could not parse title ID"); } diff --git a/hactoolnet/ProcessNca.cs b/hactoolnet/ProcessNca.cs index 8557b3b0..4192c824 100644 --- a/hactoolnet/ProcessNca.cs +++ b/hactoolnet/ProcessNca.cs @@ -43,7 +43,7 @@ namespace hactoolnet { var romfs = new Romfs(nca.OpenSection(1, false, ctx.Options.EnableHash)); - foreach (var romfsFile in romfs.Files) + foreach (RomfsFile romfsFile in romfs.Files) { ctx.Logger.LogMessage(romfsFile.FullPath); } @@ -178,7 +178,7 @@ namespace hactoolnet void PrintPfs0(NcaSection sect) { - var sBlock = sect.Pfs0.Superblock; + PfsSuperblock sBlock = sect.Pfs0.Superblock; PrintItem(sb, colLen, $" Superblock Hash{sect.SuperblockHashValidity.GetValidityString()}:", sBlock.MasterHash); sb.AppendLine($" Hash Table{sect.Pfs0.Validity.GetValidityString()}:"); @@ -191,8 +191,8 @@ namespace hactoolnet void PrintRomfs(NcaSection sect) { - var sBlock = sect.Romfs.Superblock; - var levels = sect.Romfs.IvfcLevels; + RomfsSuperblock sBlock = sect.Romfs.Superblock; + IvfcLevel[] levels = sect.Romfs.IvfcLevels; PrintItem(sb, colLen, $" Superblock Hash{sect.SuperblockHashValidity.GetValidityString()}:", sBlock.IvfcHeader.MasterHash); PrintItem(sb, colLen, " Magic:", sBlock.IvfcHeader.Magic); @@ -200,7 +200,7 @@ namespace hactoolnet for (int i = 0; i < Romfs.IvfcMaxLevel; i++) { - var level = levels[i]; + IvfcLevel level = levels[i]; sb.AppendLine($" Level {i}{level.HashValidity.GetValidityString()}:"); PrintItem(sb, colLen, " Data Offset:", $"0x{level.DataOffset:x12}"); PrintItem(sb, colLen, " Data Size:", $"0x{level.DataSize:x12}"); diff --git a/hactoolnet/ProcessNsp.cs b/hactoolnet/ProcessNsp.cs index 15510edf..b12d2c51 100644 --- a/hactoolnet/ProcessNsp.cs +++ b/hactoolnet/ProcessNsp.cs @@ -8,14 +8,14 @@ namespace hactoolnet { public static void CreateNsp(Context ctx, SwitchFs switchFs) { - var id = ctx.Options.TitleId; + ulong id = ctx.Options.TitleId; if (id == 0) { ctx.Logger.LogMessage("Title ID must be specified to save title"); return; } - if (!switchFs.Titles.TryGetValue(id, out var title)) + if (!switchFs.Titles.TryGetValue(id, out Title title)) { ctx.Logger.LogMessage($"Could not find title {id:X16}"); return; @@ -23,7 +23,7 @@ namespace hactoolnet var builder = new Pfs0Builder(); - foreach (var nca in title.Ncas) + foreach (Nca nca in title.Ncas) { builder.AddFile(nca.Filename, nca.GetStream()); } @@ -39,11 +39,11 @@ namespace hactoolnet CryptoType = title.MainNca.Header.CryptoType2, SectHeaderOffset = 0x2C0 }; - var ticketBytes = ticket.GetBytes(); + byte[] ticketBytes = ticket.GetBytes(); builder.AddFile($"{ticket.RightsId.ToHexString()}.tik", new MemoryStream(ticketBytes)); - var thisAssembly = Assembly.GetExecutingAssembly(); - var cert = thisAssembly.GetManifestResourceStream("hactoolnet.CA00000003_XS00000020"); + Assembly thisAssembly = Assembly.GetExecutingAssembly(); + Stream cert = thisAssembly.GetManifestResourceStream("hactoolnet.CA00000003_XS00000020"); builder.AddFile($"{ticket.RightsId.ToHexString()}.cert", cert); diff --git a/hactoolnet/ProcessSave.cs b/hactoolnet/ProcessSave.cs index 81487cd9..91efb08c 100644 --- a/hactoolnet/ProcessSave.cs +++ b/hactoolnet/ProcessSave.cs @@ -23,7 +23,7 @@ namespace hactoolnet if (ctx.Options.DebugOutDir != null) { - var dir = ctx.Options.DebugOutDir; + string dir = ctx.Options.DebugOutDir; Directory.CreateDirectory(dir); File.WriteAllBytes(Path.Combine(dir, "L0_0_MasterHashA"), save.Header.MasterHashA); diff --git a/hactoolnet/ProcessSwitchFs.cs b/hactoolnet/ProcessSwitchFs.cs index 540dd61b..816e9b15 100644 --- a/hactoolnet/ProcessSwitchFs.cs +++ b/hactoolnet/ProcessSwitchFs.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; @@ -25,14 +26,14 @@ namespace hactoolnet if (ctx.Options.ExefsOutDir != null || ctx.Options.ExefsOut != null) { - var id = ctx.Options.TitleId; + ulong id = ctx.Options.TitleId; if (id == 0) { ctx.Logger.LogMessage("Title ID must be specified to dump ExeFS"); return; } - if (!switchFs.Titles.TryGetValue(id, out var title)) + if (!switchFs.Titles.TryGetValue(id, out Title title)) { ctx.Logger.LogMessage($"Could not find title {id:X16}"); return; @@ -44,7 +45,7 @@ namespace hactoolnet return; } - var section = title.MainNca.Sections.FirstOrDefault(x => x.IsExefs); + NcaSection section = title.MainNca.Sections.FirstOrDefault(x => x.IsExefs); if (section == null) { @@ -65,14 +66,14 @@ namespace hactoolnet if (ctx.Options.RomfsOutDir != null || ctx.Options.RomfsOut != null) { - var id = ctx.Options.TitleId; + ulong id = ctx.Options.TitleId; if (id == 0) { ctx.Logger.LogMessage("Title ID must be specified to dump RomFS"); return; } - if (!switchFs.Titles.TryGetValue(id, out var title)) + if (!switchFs.Titles.TryGetValue(id, out Title title)) { ctx.Logger.LogMessage($"Could not find title {id:X16}"); return; @@ -84,7 +85,7 @@ namespace hactoolnet return; } - var section = title.MainNca.Sections.FirstOrDefault(x => x?.Type == SectionType.Romfs || x?.Type == SectionType.Bktr); + NcaSection section = title.MainNca.Sections.FirstOrDefault(x => x?.Type == SectionType.Romfs || x?.Type == SectionType.Bktr); if (section == null) { @@ -122,26 +123,26 @@ namespace hactoolnet private static void SaveTitle(Context ctx, SwitchFs switchFs) { - var id = ctx.Options.TitleId; + ulong id = ctx.Options.TitleId; if (id == 0) { ctx.Logger.LogMessage("Title ID must be specified to save title"); return; } - if (!switchFs.Titles.TryGetValue(id, out var title)) + if (!switchFs.Titles.TryGetValue(id, out Title title)) { ctx.Logger.LogMessage($"Could not find title {id:X16}"); return; } - var saveDir = Path.Combine(ctx.Options.OutDir, $"{title.Id:X16}v{title.Version.Version}"); + string saveDir = Path.Combine(ctx.Options.OutDir, $"{title.Id:X16}v{title.Version.Version}"); Directory.CreateDirectory(saveDir); - foreach (var nca in title.Ncas) + foreach (Nca nca in title.Ncas) { - var stream = nca.GetStream(); - var outFile = Path.Combine(saveDir, nca.Filename); + Stream stream = nca.GetStream(); + string outFile = Path.Combine(saveDir, nca.Filename); ctx.Logger.LogMessage(nca.Filename); using (var outStream = new FileStream(outFile, FileMode.Create, FileAccess.ReadWrite)) { @@ -152,22 +153,22 @@ namespace hactoolnet static void ListTitles(SwitchFs sdfs) { - foreach (var title in sdfs.Titles.Values.OrderBy(x => x.Id)) + foreach (Title title in sdfs.Titles.Values.OrderBy(x => x.Id)) { Console.WriteLine($"{title.Name} {title.Control?.DisplayVersion}"); Console.WriteLine($"{title.Id:X16} v{title.Version.Version} ({title.Version}) {title.Metadata.Type}"); - foreach (var content in title.Metadata.ContentEntries) + foreach (CnmtContentEntry content in title.Metadata.ContentEntries) { Console.WriteLine( $" {content.NcaId.ToHexString()}.nca {content.Type} {Util.GetBytesReadable(content.Size)}"); } - foreach (var nca in title.Ncas) + foreach (Nca nca in title.Ncas) { Console.WriteLine($" {nca.HasRightsId} {nca.NcaId} {nca.Header.ContentType}"); - foreach (var sect in nca.Sections.Where(x => x != null)) + foreach (NcaSection sect in nca.Sections.Where(x => x != null)) { Console.WriteLine($" {sect.SectionNum} {sect.Type} {sect.Header.CryptType} {sect.SuperblockHashValidity}"); } @@ -181,7 +182,7 @@ namespace hactoolnet { var sb = new StringBuilder(); - foreach (var app in sdfs.Applications.Values.OrderBy(x => x.Name)) + foreach (Application app in sdfs.Applications.Values.OrderBy(x => x.Name)) { sb.AppendLine($"{app.Name} v{app.DisplayVersion}"); @@ -215,9 +216,9 @@ namespace hactoolnet private static void ExportSdSaves(Context ctx, SwitchFs switchFs) { - foreach (var save in switchFs.Saves) + foreach (KeyValuePair save in switchFs.Saves) { - var outDir = Path.Combine(ctx.Options.SaveOutDir, save.Key); + string outDir = Path.Combine(ctx.Options.SaveOutDir, save.Key); save.Value.Extract(outDir, ctx.Logger); } } diff --git a/hactoolnet/ProcessXci.cs b/hactoolnet/ProcessXci.cs index df721908..8edb511a 100644 --- a/hactoolnet/ProcessXci.cs +++ b/hactoolnet/ProcessXci.cs @@ -43,17 +43,17 @@ namespace hactoolnet if (ctx.Options.OutDir != null && xci.RootPartition != null) { - var root = xci.RootPartition; + XciPartition root = xci.RootPartition; if (root == null) { ctx.Logger.LogMessage("Could not find root partition"); return; } - foreach (var sub in root.Files) + foreach (PfsFileEntry sub in root.Files) { var subPfs = new Pfs(root.OpenFile(sub)); - var subDir = Path.Combine(ctx.Options.OutDir, sub.Name); + string subDir = Path.Combine(ctx.Options.OutDir, sub.Name); subPfs.Extract(subDir, ctx.Logger); } @@ -61,7 +61,7 @@ namespace hactoolnet if (ctx.Options.ExefsOutDir != null || ctx.Options.ExefsOut != null) { - var mainNca = GetXciMainNca(xci, ctx); + Nca mainNca = GetXciMainNca(xci, ctx); if (mainNca == null) { @@ -69,7 +69,7 @@ namespace hactoolnet return; } - var exefsSection = mainNca.Sections.FirstOrDefault(x => x.IsExefs); + NcaSection exefsSection = mainNca.Sections.FirstOrDefault(x => x.IsExefs); if (exefsSection == null) { @@ -90,7 +90,7 @@ namespace hactoolnet if (ctx.Options.RomfsOutDir != null || ctx.Options.RomfsOut != null) { - var mainNca = GetXciMainNca(xci, ctx); + Nca mainNca = GetXciMainNca(xci, ctx); if (mainNca == null) { @@ -98,7 +98,7 @@ namespace hactoolnet return; } - var romfsSection = mainNca.Sections.FirstOrDefault(x => x.Type == SectionType.Romfs); + NcaSection romfsSection = mainNca.Sections.FirstOrDefault(x => x.Type == SectionType.Romfs); if (romfsSection == null) { @@ -130,9 +130,9 @@ namespace hactoolnet Nca mainNca = null; - foreach (var fileEntry in xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".nca"))) + foreach (PfsFileEntry fileEntry in xci.SecurePartition.Files.Where(x => x.Name.EndsWith(".nca"))) { - var ncaStream = xci.SecurePartition.OpenFile(fileEntry); + Stream ncaStream = xci.SecurePartition.OpenFile(fileEntry); var nca = new Nca(ctx.Keyset, ncaStream, true); if (nca.Header.ContentType == ContentType.Program) diff --git a/hactoolnet/Program.cs b/hactoolnet/Program.cs index 8b180180..7b32c088 100644 --- a/hactoolnet/Program.cs +++ b/hactoolnet/Program.cs @@ -69,13 +69,13 @@ namespace hactoolnet private static void OpenKeyset(Context ctx) { - var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - var homeKeyFile = Path.Combine(home, ".switch", "prod.keys"); - var homeTitleKeyFile = Path.Combine(home, ".switch", "title.keys"); - var homeConsoleKeyFile = Path.Combine(home, ".switch", "console.keys"); - var keyFile = ctx.Options.Keyfile; - var titleKeyFile = ctx.Options.TitleKeyFile; - var consoleKeyFile = ctx.Options.ConsoleKeyFile; + string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + string homeKeyFile = Path.Combine(home, ".switch", "prod.keys"); + string homeTitleKeyFile = Path.Combine(home, ".switch", "title.keys"); + string homeConsoleKeyFile = Path.Combine(home, ".switch", "console.keys"); + string keyFile = ctx.Options.Keyfile; + string titleKeyFile = ctx.Options.TitleKeyFile; + string consoleKeyFile = ctx.Options.ConsoleKeyFile; if (keyFile == null && File.Exists(homeKeyFile)) {