diff --git a/7zip/Common/CRC.cs b/7zip/Common/CRC.cs index 668b491..ce5e76c 100644 --- a/7zip/Common/CRC.cs +++ b/7zip/Common/CRC.cs @@ -35,14 +35,14 @@ namespace SevenZip public void UpdateByte(byte b) { - _value = Table[((byte)(_value)) ^ b] ^ (_value >> 8); + _value = Table[((byte)_value) ^ b] ^ (_value >> 8); } public void Update(byte[] data, uint offset, uint size) { for (uint i = 0; i < size; i++) { - _value = Table[((byte)(_value)) ^ data[offset + i]] ^ (_value >> 8); + _value = Table[((byte)_value) ^ data[offset + i]] ^ (_value >> 8); } } diff --git a/7zip/Common/CommandLineParser.cs b/7zip/Common/CommandLineParser.cs index c1134fe..1419528 100644 --- a/7zip/Common/CommandLineParser.cs +++ b/7zip/Common/CommandLineParser.cs @@ -134,7 +134,7 @@ namespace SevenZip.CommandLineParser } else { - matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus); + matchedSwitch.WithMinus = srcString[pos] == kSwitchMinus; if (matchedSwitch.WithMinus) { pos++; diff --git a/7zip/Common/InBuffer.cs b/7zip/Common/InBuffer.cs index 2c56d2e..6205287 100644 --- a/7zip/Common/InBuffer.cs +++ b/7zip/Common/InBuffer.cs @@ -38,7 +38,7 @@ namespace SevenZip.Buffer int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize); m_Pos = 0; m_Limit = (uint)aNumProcessedBytes; - m_StreamWasExhausted = (aNumProcessedBytes == 0); + m_StreamWasExhausted = aNumProcessedBytes == 0; return !m_StreamWasExhausted; } @@ -50,12 +50,9 @@ namespace SevenZip.Buffer public bool ReadByte(byte b) // check it { - if (m_Pos >= m_Limit) + if (m_Pos >= m_Limit && !ReadBlock()) { - if (!ReadBlock()) - { - return false; - } + return false; } b = m_Buffer[m_Pos++]; @@ -65,12 +62,9 @@ namespace SevenZip.Buffer public byte ReadByte() { // return (byte)m_Stream.ReadByte(); - if (m_Pos >= m_Limit) + if (m_Pos >= m_Limit && !ReadBlock()) { - if (!ReadBlock()) - { - return 0xFF; - } + return 0xFF; } return m_Buffer[m_Pos++]; diff --git a/7zip/Compress/LZ/LzBinTree.cs b/7zip/Compress/LZ/LzBinTree.cs index 93dfd0e..c8df03c 100644 --- a/7zip/Compress/LZ/LzBinTree.cs +++ b/7zip/Compress/LZ/LzBinTree.cs @@ -33,7 +33,7 @@ namespace SevenZip.Compression.LZ public void SetType(int numHashBytes) { - HASH_ARRAY = (numHashBytes > 2); + HASH_ARRAY = numHashBytes > 2; if (HASH_ARRAY) { kNumHashDirectBytes = 0; @@ -97,7 +97,7 @@ namespace SevenZip.Compression.LZ UInt32 windowReservSize = ((historySize + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2) + 256; - base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); + Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); _matchMaxLen = matchMaxLen; @@ -112,10 +112,10 @@ namespace SevenZip.Compression.LZ if (HASH_ARRAY) { hs = historySize - 1; - hs |= (hs >> 1); - hs |= (hs >> 2); - hs |= (hs >> 4); - hs |= (hs >> 8); + hs |= hs >> 1; + hs |= hs >> 2; + hs |= hs >> 4; + hs |= hs >> 8; hs >>= 1; hs |= 0xFFFF; if (hs > (1 << 24)) @@ -160,13 +160,13 @@ namespace SevenZip.Compression.LZ { UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; hash2Value = temp & (kHash2Size - 1); - temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); + temp ^= (UInt32)_bufferBase[cur + 2] << 8; hash3Value = temp & (kHash3Size - 1); hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else { - hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); + hashValue = _bufferBase[cur] ^ ((UInt32)_bufferBase[cur + 1] << 8); } UInt32 curMatch = _hash[kFixHashSize + hashValue]; @@ -176,28 +176,22 @@ namespace SevenZip.Compression.LZ UInt32 curMatch3 = _hash[kHash3Offset + hash3Value]; _hash[hash2Value] = _pos; _hash[kHash3Offset + hash3Value] = _pos; - if (curMatch2 > matchMinPos) + if (curMatch2 > matchMinPos && _bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) { - if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) - { - distances[offset++] = maxLen = 2; - distances[offset++] = _pos - curMatch2 - 1; - } + distances[offset++] = maxLen = 2; + distances[offset++] = _pos - curMatch2 - 1; } - if (curMatch3 > matchMinPos) + if (curMatch3 > matchMinPos && _bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) { - if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) + if (curMatch3 == curMatch2) { - if (curMatch3 == curMatch2) - { - offset -= 2; - } - - distances[offset++] = maxLen = 3; - distances[offset++] = _pos - curMatch3 - 1; - curMatch2 = curMatch3; + offset -= 2; } + + distances[offset++] = maxLen = 3; + distances[offset++] = _pos - curMatch3 - 1; + curMatch2 = curMatch3; } if (offset != 0 && curMatch2 == curMatch) @@ -210,21 +204,18 @@ namespace SevenZip.Compression.LZ _hash[kFixHashSize + hashValue] = _pos; UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; - UInt32 ptr1 = (_cyclicBufferPos << 1); + UInt32 ptr1 = _cyclicBufferPos << 1; UInt32 len0, len1; len0 = len1 = kNumHashDirectBytes; - if (kNumHashDirectBytes != 0) + if (kNumHashDirectBytes != 0 && curMatch > matchMinPos) { - if (curMatch > matchMinPos) + if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != + _bufferBase[cur + kNumHashDirectBytes]) { - if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != - _bufferBase[cur + kNumHashDirectBytes]) - { - distances[offset++] = maxLen = kNumHashDirectBytes; - distances[offset++] = _pos - curMatch - 1; - } + distances[offset++] = maxLen = kNumHashDirectBytes; + distances[offset++] = _pos - curMatch - 1; } } @@ -314,21 +305,21 @@ namespace SevenZip.Compression.LZ UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; UInt32 hash2Value = temp & (kHash2Size - 1); _hash[hash2Value] = _pos; - temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); + temp ^= (UInt32)_bufferBase[cur + 2] << 8; UInt32 hash3Value = temp & (kHash3Size - 1); _hash[kHash3Offset + hash3Value] = _pos; hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else { - hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); + hashValue = _bufferBase[cur] ^ ((UInt32)_bufferBase[cur + 1] << 8); } UInt32 curMatch = _hash[kFixHashSize + hashValue]; _hash[kFixHashSize + hashValue] = _pos; UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; - UInt32 ptr1 = (_cyclicBufferPos << 1); + UInt32 ptr1 = _cyclicBufferPos << 1; UInt32 len0, len1; len0 = len1 = kNumHashDirectBytes; diff --git a/7zip/Compress/LZ/LzInWindow.cs b/7zip/Compress/LZ/LzInWindow.cs index 6b18168..f54e368 100644 --- a/7zip/Compress/LZ/LzInWindow.cs +++ b/7zip/Compress/LZ/LzInWindow.cs @@ -50,7 +50,7 @@ namespace SevenZip.Compression.LZ while (true) { - int size = (int)((0 - _bufferOffset) + _blockSize - _streamPos); + int size = (int)(0 - _bufferOffset + _blockSize - _streamPos); if (size == 0) { return; @@ -125,12 +125,9 @@ namespace SevenZip.Compression.LZ // index + limit have not to exceed _keepSizeAfter; public UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) { - if (_streamEndWasReached) + if (_streamEndWasReached && _pos + index + limit > _streamPos) { - if (_pos + index + limit > _streamPos) - { - limit = _streamPos - (UInt32)(_pos + index); - } + limit = _streamPos - (UInt32)(_pos + index); } distance++; diff --git a/7zip/Compress/LZMA/LzmaBase.cs b/7zip/Compress/LZMA/LzmaBase.cs index 61b35ee..6b74137 100644 --- a/7zip/Compress/LZMA/LzmaBase.cs +++ b/7zip/Compress/LZMA/LzmaBase.cs @@ -60,7 +60,7 @@ namespace SevenZip.Compression.LZMA public const int kNumAlignBits = 4; public const uint kAlignTableSize = 1 << kNumAlignBits; - public const uint kAlignMask = (kAlignTableSize - 1); + public const uint kAlignMask = kAlignTableSize - 1; public const uint kStartPosModelIndex = 4; public const uint kEndPosModelIndex = 14; @@ -72,9 +72,9 @@ namespace SevenZip.Compression.LZMA public const uint kNumLitContextBitsMax = 8; public const int kNumPosStatesBitsMax = 4; - public const uint kNumPosStatesMax = (1 << kNumPosStatesBitsMax); + public const uint kNumPosStatesMax = 1 << kNumPosStatesBitsMax; public const int kNumPosStatesBitsEncodingMax = 4; - public const uint kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax); + public const uint kNumPosStatesEncodingMax = 1 << kNumPosStatesBitsEncodingMax; public const int kNumLowLenBits = 3; public const int kNumMidLenBits = 3; diff --git a/7zip/Compress/LZMA/LzmaDecoder.cs b/7zip/Compress/LZMA/LzmaDecoder.cs index a67d349..a2b0847 100644 --- a/7zip/Compress/LZMA/LzmaDecoder.cs +++ b/7zip/Compress/LZMA/LzmaDecoder.cs @@ -362,7 +362,7 @@ namespace SevenZip.Compression.LZMA if (posSlot >= Base.kStartPosModelIndex) { int numDirectBits = (int)((posSlot >> 1) - 1); - rep0 = ((2 | (posSlot & 1)) << numDirectBits); + rep0 = (2 | (posSlot & 1)) << numDirectBits; if (posSlot < Base.kEndPosModelIndex) { rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, @@ -370,8 +370,8 @@ namespace SevenZip.Compression.LZMA } else { - rep0 += (m_RangeDecoder.DecodeDirectBits( - numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); + rep0 += m_RangeDecoder.DecodeDirectBits( + numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits; rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); } } @@ -423,7 +423,7 @@ namespace SevenZip.Compression.LZMA UInt32 dictionarySize = 0; for (int i = 0; i < 4; i++) { - dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8); + dictionarySize += ((UInt32)properties[1 + i]) << (i * 8); } SetDictionarySize(dictionarySize); diff --git a/7zip/Compress/LZMA/LzmaEncoder.cs b/7zip/Compress/LZMA/LzmaEncoder.cs index 7281099..f1b8461 100644 --- a/7zip/Compress/LZMA/LzmaEncoder.cs +++ b/7zip/Compress/LZMA/LzmaEncoder.cs @@ -27,7 +27,7 @@ namespace SevenZip.Compression.LZMA g_FastPos[1] = 1; for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++) { - UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1)); + UInt32 k = (UInt32)1 << ((slotFast >> 1) - 1); for (UInt32 j = 0; j < k; j++, c++) { g_FastPos[c] = slotFast; @@ -118,8 +118,8 @@ namespace SevenZip.Compression.LZMA if (same) { uint matchBit = (uint)((matchByte >> i) & 1); - state += ((1 + matchBit) << 8); - same = (matchBit == bit); + state += (1 + matchBit) << 8; + same = matchBit == bit; } m_Encoders[state].Encode(rangeEncoder, bit); context = (context << 1) | bit; @@ -379,14 +379,14 @@ namespace SevenZip.Compression.LZMA private readonly UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; private UInt32 _alignPriceCount; - private UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2); + private UInt32 _distTableSize = kDefaultDictionaryLogSize * 2; private int _posStateBits = 2; - private UInt32 _posStateMask = (4 - 1); + private UInt32 _posStateMask = 4 - 1; private int _numLiteralPosStateBits = 0; private int _numLiteralContextBits = 3; - private UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); + private UInt32 _dictionarySize = 1 << kDefaultDictionaryLogSize; private UInt32 _dictionarySizePrev = 0xFFFFFFFF; private UInt32 _numFastBytesPrev = 0xFFFFFFFF; @@ -665,7 +665,7 @@ namespace SevenZip.Compression.LZMA _optimum[0].State = _state; - UInt32 posState = (position & _posStateMask); + UInt32 posState = position & _posStateMask; _optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte); @@ -684,7 +684,7 @@ namespace SevenZip.Compression.LZMA } } - UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); + UInt32 lenEnd = (lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]; if (lenEnd < 2) { @@ -732,7 +732,7 @@ namespace SevenZip.Compression.LZMA UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); - len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); + len = (repLens[0] >= 2) ? repLens[0] + 1 : 2; if (len <= lenMain) { UInt32 offs = 0; @@ -878,7 +878,7 @@ namespace SevenZip.Compression.LZMA } else { - reps[0] = (pos - Base.kNumRepDistances); + reps[0] = pos - Base.kNumRepDistances; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; @@ -894,7 +894,7 @@ namespace SevenZip.Compression.LZMA currentByte = _matchFinder.GetIndexByte(0 - 1); matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1)); - posState = (position & _posStateMask); + posState = position & _posStateMask; UInt32 curAnd1Price = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + @@ -1154,7 +1154,7 @@ namespace SevenZip.Compression.LZMA private bool ChangePair(UInt32 smallDist, UInt32 bigDist) { const int kDif = 7; - return smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif); + return smallDist < ((UInt32)1 << (32 - kDif)) && bigDist >= (smallDist << kDif); } private void WriteEndMarker(UInt32 posState) @@ -1173,7 +1173,7 @@ namespace SevenZip.Compression.LZMA UInt32 lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); const int footerBits = 30; - UInt32 posReduced = (((UInt32)1) << footerBits) - 1; + const UInt32 posReduced = (((UInt32)1) << footerBits) - 1; _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); } @@ -1221,11 +1221,11 @@ namespace SevenZip.Compression.LZMA } // it's not used ReadMatchDistances(out uint len, out uint numDistancePairs); - UInt32 posState = (UInt32)(nowPos64) & _posStateMask; + UInt32 posState = (UInt32)nowPos64 & _posStateMask; _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0); _state.UpdateChar(); Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); - _literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); + _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte).Encode(_rangeEncoder, curByte); _previousByte = curByte; _additionalOffset--; nowPos64++; @@ -1323,12 +1323,12 @@ namespace SevenZip.Compression.LZMA if (posSlot >= Base.kStartPosModelIndex) { int footerBits = (int)((posSlot >> 1) - 1); - UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); + UInt32 baseVal = (2 | (posSlot & 1)) << footerBits; UInt32 posReduced = pos - baseVal; if (posSlot < Base.kEndPosModelIndex) { - RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders, + BitTreeEncoder.ReverseEncode(_posEncoders, baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); } else @@ -1471,7 +1471,7 @@ namespace SevenZip.Compression.LZMA { UInt32 posSlot = GetPosSlot(i); int footerBits = (int)((posSlot >> 1) - 1); - UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); + UInt32 baseVal = (2 | (posSlot & 1)) << footerBits; tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, baseVal - posSlot - 1, footerBits, i - baseVal); } @@ -1481,7 +1481,7 @@ namespace SevenZip.Compression.LZMA UInt32 posSlot; BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; - UInt32 st = (lenToPosState << Base.kNumPosSlotBits); + UInt32 st = lenToPosState << Base.kNumPosSlotBits; for (posSlot = 0; posSlot < _distTableSize; posSlot++) { _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); @@ -1489,7 +1489,7 @@ namespace SevenZip.Compression.LZMA for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) { - _posSlotPrices[st + posSlot] += (((posSlot >> 1) - 1 - Base.kNumAlignBits) << RangeCoder.BitEncoder.kNumBitPriceShiftBits); + _posSlotPrices[st + posSlot] += ((posSlot >> 1) - 1 - Base.kNumAlignBits) << BitEncoder.kNumBitPriceShiftBits; } UInt32 st2 = lenToPosState * Base.kNumFullDistances; @@ -1610,7 +1610,7 @@ namespace SevenZip.Compression.LZMA int dicLogSize; for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) { - if (dictionarySize <= ((UInt32)(1) << dicLogSize)) + if (dictionarySize <= ((UInt32)1 << dicLogSize)) { break; } diff --git a/7zip/Compress/RangeCoder/RangeCoder.cs b/7zip/Compress/RangeCoder/RangeCoder.cs index 45025d1..9b5d50d 100644 --- a/7zip/Compress/RangeCoder/RangeCoder.cs +++ b/7zip/Compress/RangeCoder/RangeCoder.cs @@ -4,7 +4,7 @@ namespace SevenZip.Compression.RangeCoder { internal class Encoder { - public const uint kTopValue = (1 << 24); + public const uint kTopValue = 1 << 24; private System.IO.Stream Stream; @@ -128,7 +128,7 @@ namespace SevenZip.Compression.RangeCoder internal class Decoder { - public const uint kTopValue = (1 << 24); + public const uint kTopValue = 1 << 24; public uint Range; public uint Code; // public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16); diff --git a/7zip/Compress/RangeCoder/RangeCoderBit.cs b/7zip/Compress/RangeCoder/RangeCoderBit.cs index cb88d5c..d7162f8 100644 --- a/7zip/Compress/RangeCoder/RangeCoderBit.cs +++ b/7zip/Compress/RangeCoder/RangeCoderBit.cs @@ -5,7 +5,7 @@ namespace SevenZip.Compression.RangeCoder internal struct BitEncoder { public const int kNumBitModelTotalBits = 11; - public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); + public const uint kBitModelTotal = 1 << kNumBitModelTotalBits; private const int kNumMoveBits = 5; private const int kNumMoveReducingBits = 2; public const int kNumBitPriceShiftBits = 6; @@ -53,7 +53,7 @@ namespace SevenZip.Compression.RangeCoder static BitEncoder() { - const int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); + const int kNumBits = kNumBitModelTotalBits - kNumMoveReducingBits; for (int i = kNumBits - 1; i >= 0; i--) { UInt32 start = (UInt32)1 << (kNumBits - i - 1); @@ -77,7 +77,7 @@ namespace SevenZip.Compression.RangeCoder internal struct BitDecoder { public const int kNumBitModelTotalBits = 11; - public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); + public const uint kBitModelTotal = 1 << kNumBitModelTotalBits; private const int kNumMoveBits = 5; private uint Prob; diff --git a/7zip/Compress/RangeCoder/RangeCoderBitTree.cs b/7zip/Compress/RangeCoder/RangeCoderBitTree.cs index 7d3c026..a98084b 100644 --- a/7zip/Compress/RangeCoder/RangeCoderBitTree.cs +++ b/7zip/Compress/RangeCoder/RangeCoderBitTree.cs @@ -141,7 +141,7 @@ namespace SevenZip.Compression.RangeCoder uint bit = Models[m].Decode(rangeDecoder); m <<= 1; m += bit; - symbol |= (bit << bitIndex); + symbol |= bit << bitIndex; } return symbol; } @@ -156,7 +156,7 @@ namespace SevenZip.Compression.RangeCoder uint bit = Models[startIndex + m].Decode(rangeDecoder); m <<= 1; m += bit; - symbol |= (bit << bitIndex); + symbol |= bit << bitIndex; } return symbol; } diff --git a/7zip/ICoder.cs b/7zip/ICoder.cs index a6773cf..5a09466 100644 --- a/7zip/ICoder.cs +++ b/7zip/ICoder.cs @@ -11,6 +11,14 @@ namespace SevenZip internal class DataErrorException : ApplicationException { public DataErrorException() : base("Data Error") { } + + public DataErrorException(string message) : base(message) + { + } + + public DataErrorException(string message, Exception innerException) : base(message, innerException) + { + } } /// @@ -19,6 +27,14 @@ namespace SevenZip internal class InvalidParamException : ApplicationException { public InvalidParamException() : base("Invalid Parameter") { } + + public InvalidParamException(string message) : base(message) + { + } + + public InvalidParamException(string message, Exception innerException) : base(message, innerException) + { + } } public interface ICodeProgress diff --git a/CommandLine.cs b/CommandLine.cs index ee4cabf..e9fa7f6 100644 --- a/CommandLine.cs +++ b/CommandLine.cs @@ -182,7 +182,7 @@ namespace WPinternals Notifier = new PhoneNotifierViewModel(); UIContext.Send(s => Notifier.Start(), null); - FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Bootloader)); // This also works for Bootloader Spec A + FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Bootloader); // This also works for Bootloader Spec A GPT GPT = FlashModel.ReadGPT(); // May throw NotSupportedException foreach (Partition Partition in GPT.Partitions) @@ -221,9 +221,9 @@ namespace WPinternals { Notifier = new PhoneNotifierViewModel(); UIContext.Send(s => Notifier.Start(), null); - FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); GPT GPT = FlashModel.ReadGPT(); // May throw NotSupportedException - System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(args[2])); + Directory.CreateDirectory(Path.GetDirectoryName(args[2])); GPT.WritePartitions(args[2]); FlashModel.SwitchToFlashAppContext(); Notifier.Stop(); @@ -248,7 +248,7 @@ namespace WPinternals { Notifier = new PhoneNotifierViewModel(); UIContext.Send(s => Notifier.Start(), null); - FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); byte[] GptChunk = LumiaUnlockBootloaderViewModel.GetGptChunk(FlashModel, 0x20000); GPT GPT = new(GptChunk); string Xml = File.ReadAllText(args[2]); @@ -344,7 +344,7 @@ namespace WPinternals { if (FFU.IsPartitionPresentInFFU(Partition.Name)) { - FFU.WritePartition(Partition.Name, System.IO.Path.Combine(args[3], Partition.Name + ".bin")); + FFU.WritePartition(Partition.Name, Path.Combine(args[3], Partition.Name + ".bin")); } } } @@ -356,7 +356,7 @@ namespace WPinternals throw new InvalidOperationException("Partition not found in FFU!"); } - FFU.WritePartition(Target.Name, System.IO.Path.Combine(args[3], Target.Name + ".bin")); + FFU.WritePartition(Target.Name, Path.Combine(args[3], Target.Name + ".bin")); } break; case "dumpuefi": @@ -512,7 +512,7 @@ namespace WPinternals try { UIContext.Send(s => Notifier.Start(), null); - FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); Info = FlashModel.ReadPhoneInfo(); Info.Log(LogType.ConsoleOnly); @@ -536,7 +536,7 @@ namespace WPinternals if (ProfileFFU == null) { - List FFUs = App.Config.FFURepository.Where(e => (Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists())).ToList(); + List FFUs = App.Config.FFURepository.Where(e => Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists()).ToList(); ProfileFFU = FFUs.Count > 0 ? new FFU(FFUs[0].Path) : throw new WPinternalsException("Profile FFU missing", "No profile FFU has been found in the repository for your device. You can add a profile FFU within the download section of the tool or by using the command line."); @@ -661,7 +661,7 @@ namespace WPinternals LogFile.Log("Command: Show phone info", LogType.FileAndConsole); Notifier = new PhoneNotifierViewModel(); UIContext.Send(s => Notifier.Start(), null); - FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); Info = FlashModel.ReadPhoneInfo(); Info.Log(LogType.ConsoleOnly); Notifier.Stop(); @@ -673,7 +673,7 @@ namespace WPinternals LogFile.Log("Command: Unlock Bootloader", LogType.FileAndConsole); Notifier = new PhoneNotifierViewModel(); UIContext.Send(s => Notifier.Start(), null); - FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); Info = FlashModel.ReadPhoneInfo(); Info.Log(LogType.ConsoleOnly); @@ -704,7 +704,7 @@ namespace WPinternals if (ProfileFFU == null) { - List FFUs = App.Config.FFURepository.Where(e => (Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists())).ToList(); + List FFUs = App.Config.FFURepository.Where(e => Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists()).ToList(); ProfileFFU = FFUs.Count > 0 ? new FFU(FFUs[0].Path) : throw new WPinternalsException("Profile FFU missing", "No profile FFU has been found in the repository for your device. You can add a profile FFU within the download section of the tool or by using the command line."); @@ -746,7 +746,7 @@ namespace WPinternals LogFile.Log("Custom ROM: " + CustomRomPath, LogType.FileAndConsole); Notifier = new PhoneNotifierViewModel(); UIContext.Send(s => Notifier.Start(), null); - FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); Info = FlashModel.ReadPhoneInfo(); Info.Log(LogType.ConsoleOnly); LogFile.Log("Preparing to flash Custom ROM", LogType.FileAndConsole); @@ -777,7 +777,7 @@ namespace WPinternals LogFile.Log("FFU file: " + FFUPath, LogType.FileAndConsole); Notifier = new PhoneNotifierViewModel(); UIContext.Send(s => Notifier.Start(), null); - FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); Info = FlashModel.ReadPhoneInfo(); Info.Log(LogType.ConsoleOnly); LogFile.Log("Flashing FFU...", LogType.FileAndConsole); @@ -1251,7 +1251,7 @@ namespace WPinternals } else { - NormalModel = (NokiaPhoneModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Normal)); + NormalModel = (NokiaPhoneModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Normal); ProductCode = NormalModel.ExecuteJsonMethodAsString("ReadProductCode", "ProductCode"); } URL = LumiaDownloadModel.SearchFFU(null, ProductCode, null, out ProductType); @@ -1267,7 +1267,7 @@ namespace WPinternals LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1303,7 +1303,7 @@ namespace WPinternals URL = LumiaDownloadModel.SearchFFU(ProductType, null, OperatorCode); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1336,7 +1336,7 @@ namespace WPinternals LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1369,7 +1369,7 @@ namespace WPinternals URL = LumiaDownloadModel.SearchFFU(ProductType, null, null); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1392,7 +1392,7 @@ namespace WPinternals URL = LumiaDownloadModel.SearchFFU(ProductType, null, null); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); break; case "downloademergency": @@ -1416,7 +1416,7 @@ namespace WPinternals } else { - NormalModel = (NokiaPhoneModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Normal)); + NormalModel = (NokiaPhoneModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Normal); ProductType = NormalModel.ExecuteJsonMethodAsString("ReadManufacturerModelName", "ManufacturerModelName"); if (ProductType.Contains('_')) { @@ -1440,7 +1440,7 @@ namespace WPinternals { LogFile.Log("URL: " + URLs[i], LogType.FileAndConsole); URI = new Uri(URLs[i]); - EmergencyFileName = System.IO.Path.GetFileName(URI.LocalPath); + EmergencyFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole); EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName); if (i == 0) @@ -1488,7 +1488,7 @@ namespace WPinternals { LogFile.Log("URL: " + URLs[i], LogType.FileAndConsole); URI = new Uri(URLs[i]); - EmergencyFileName = System.IO.Path.GetFileName(URI.LocalPath); + EmergencyFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole); EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName); if (i == 0) @@ -1527,7 +1527,7 @@ namespace WPinternals } else { - NormalModel = (NokiaPhoneModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Normal)); + NormalModel = (NokiaPhoneModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Normal); ProductCode = NormalModel.ExecuteJsonMethodAsString("ReadProductCode", "ProductCode"); } URL = LumiaDownloadModel.SearchFFU(null, ProductCode, null, out ProductType); @@ -1543,7 +1543,7 @@ namespace WPinternals LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1561,7 +1561,7 @@ namespace WPinternals { LogFile.Log("URL: " + URLs[i], LogType.FileAndConsole); URI = new Uri(URLs[i]); - EmergencyFileName = System.IO.Path.GetFileName(URI.LocalPath); + EmergencyFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole); EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName); if (i == 0) @@ -1600,7 +1600,7 @@ namespace WPinternals LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1640,7 +1640,7 @@ namespace WPinternals URL = LumiaDownloadModel.SearchFFU(ProductType, null, null); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1658,7 +1658,7 @@ namespace WPinternals { LogFile.Log("URL: " + URLs[i], LogType.FileAndConsole); URI = new Uri(URLs[i]); - EmergencyFileName = System.IO.Path.GetFileName(URI.LocalPath); + EmergencyFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole); EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName); if (i == 0) @@ -1697,7 +1697,7 @@ namespace WPinternals LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1736,7 +1736,7 @@ namespace WPinternals LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1754,7 +1754,7 @@ namespace WPinternals { LogFile.Log("URL: " + URLs[i], LogType.FileAndConsole); URI = new Uri(URLs[i]); - EmergencyFileName = System.IO.Path.GetFileName(URI.LocalPath); + EmergencyFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole); EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName); if (i == 0) @@ -1793,7 +1793,7 @@ namespace WPinternals LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1834,7 +1834,7 @@ namespace WPinternals URL = LumiaDownloadModel.SearchFFU(ProductType, null, OperatorCode); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -1852,7 +1852,7 @@ namespace WPinternals { LogFile.Log("URL: " + URLs[i], LogType.FileAndConsole); URI = new Uri(URLs[i]); - EmergencyFileName = System.IO.Path.GetFileName(URI.LocalPath); + EmergencyFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole); EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName); if (i == 0) @@ -1891,7 +1891,7 @@ namespace WPinternals LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole); LogFile.Log("URL: " + URL, LogType.FileAndConsole); URI = new Uri(URL); - FFUFileName = System.IO.Path.GetFileName(URI.LocalPath); + FFUFileName = Path.GetFileName(URI.LocalPath); LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole); FFUFilePath = Path.Combine(DownloadFolder, FFUFileName); LogFile.Log("Downloading...", LogType.FileAndConsole); @@ -2054,12 +2054,12 @@ namespace WPinternals IntPtr stdHandle = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new(stdHandle, true); FileStream fileStream = new(safeFileHandle, FileAccess.Write); - Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE); + Encoding encoding = Encoding.GetEncoding(MY_CODE_PAGE); StreamWriter standardOutput = new(fileStream, encoding); standardOutput.AutoFlush = true; Console.SetOut(standardOutput); } - catch (Exception) + catch { } } diff --git a/DiscUtils/DiscUtils.Core/Internal/Utilities.cs b/DiscUtils/DiscUtils.Core/Internal/Utilities.cs index dc042bc..a6f15f4 100644 --- a/DiscUtils/DiscUtils.Core/Internal/Utilities.cs +++ b/DiscUtils/DiscUtils.Core/Internal/Utilities.cs @@ -61,7 +61,7 @@ namespace DiscUtils.Internal /// The resultant array. public static U[] Map(IEnumerable source, Func func) { - List result = new List(); + List result = new(); foreach (T sVal in source) { @@ -81,7 +81,7 @@ namespace DiscUtils.Internal /// The new collection, containing all entries where the predicate returns true. public static C Filter(ICollection source, Func predicate) where C : ICollection, new() { - C result = new C(); + C result = new(); foreach (T val in source) { if (predicate(val)) @@ -268,7 +268,7 @@ namespace DiscUtils.Internal /// The relative path. /// The absolute path. If no is specified /// then relativePath is returned as-is. If - /// contains more '..' characters than the base path contains levels of + /// contains more '..' characters than the base path contains levels of /// directory, the resultant string be the root drive followed by the file name. /// If no the basePath starts with '\' (no drive specified) then the returned /// path will also start with '\'. @@ -306,9 +306,9 @@ namespace DiscUtils.Internal public static string MakeRelativePath(string path, string basePath) { List pathElements = - new List(path.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)); + new(path.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)); List basePathElements = - new List(basePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)); + new(basePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)); if (!basePath.EndsWith("\\", StringComparison.Ordinal) && basePathElements.Count > 0) { @@ -319,7 +319,7 @@ namespace DiscUtils.Internal int i = 0; while (i < Math.Min(pathElements.Count - 1, basePathElements.Count)) { - if (pathElements[i].ToUpperInvariant() != basePathElements[i].ToUpperInvariant()) + if (!string.Equals(pathElements[i], basePathElements[i], StringComparison.InvariantCultureIgnoreCase)) { break; } @@ -328,7 +328,7 @@ namespace DiscUtils.Internal } // For each remaining part of the base path, insert '..' - StringBuilder result = new StringBuilder(); + StringBuilder result = new(); if (i == basePathElements.Count) { result.Append(@".\"); @@ -348,7 +348,7 @@ namespace DiscUtils.Internal result.Append(@"\"); } - result.Append(pathElements[pathElements.Count - 1]); + result.Append(pathElements[^1]); // If the target was a directory, put the terminator back if (path.EndsWith(@"\", StringComparison.Ordinal)) @@ -441,25 +441,17 @@ namespace DiscUtils.Internal public static FileAttributes FileAttributesFromUnixFileType(UnixFileType fileType) { - switch (fileType) + return fileType switch { - case UnixFileType.Fifo: - return FileAttributes.Device | FileAttributes.System; - case UnixFileType.Character: - return FileAttributes.Device | FileAttributes.System; - case UnixFileType.Directory: - return FileAttributes.Directory; - case UnixFileType.Block: - return FileAttributes.Device | FileAttributes.System; - case UnixFileType.Regular: - return FileAttributes.Normal; - case UnixFileType.Link: - return FileAttributes.ReparsePoint; - case UnixFileType.Socket: - return FileAttributes.Device | FileAttributes.System; - default: - return 0; - } + UnixFileType.Fifo => FileAttributes.Device | FileAttributes.System, + UnixFileType.Character => FileAttributes.Device | FileAttributes.System, + UnixFileType.Directory => FileAttributes.Directory, + UnixFileType.Block => FileAttributes.Device | FileAttributes.System, + UnixFileType.Regular => FileAttributes.Normal, + UnixFileType.Link => FileAttributes.ReparsePoint, + UnixFileType.Socket => FileAttributes.Device | FileAttributes.System, + _ => 0, + }; } #endregion diff --git a/DiscUtils/DiscUtils.Fat/ClusterReader.cs b/DiscUtils/DiscUtils.Fat/ClusterReader.cs index 7831056..94a3b16 100644 --- a/DiscUtils/DiscUtils.Fat/ClusterReader.cs +++ b/DiscUtils/DiscUtils.Fat/ClusterReader.cs @@ -62,7 +62,7 @@ namespace DiscUtils.Fat "buffer is too small - cluster would overflow buffer"); } - uint firstSector = (uint)((cluster - 2) * _sectorsPerCluster + _firstDataSector); + uint firstSector = (uint)(((cluster - 2) * _sectorsPerCluster) + _firstDataSector); _stream.Position = firstSector * _bytesPerSector; StreamUtilities.ReadExact(_stream, buffer, offset, _clusterSize); @@ -76,7 +76,7 @@ namespace DiscUtils.Fat "buffer is too small - cluster would overflow buffer"); } - uint firstSector = (uint)((cluster - 2) * _sectorsPerCluster + _firstDataSector); + uint firstSector = (uint)(((cluster - 2) * _sectorsPerCluster) + _firstDataSector); _stream.Position = firstSector * _bytesPerSector; @@ -85,7 +85,7 @@ namespace DiscUtils.Fat internal void WipeCluster(uint cluster) { - uint firstSector = (uint)((cluster - 2) * _sectorsPerCluster + _firstDataSector); + uint firstSector = (uint)(((cluster - 2) * _sectorsPerCluster) + _firstDataSector); _stream.Position = firstSector * _bytesPerSector; diff --git a/DiscUtils/DiscUtils.Fat/ClusterStream.cs b/DiscUtils/DiscUtils.Fat/ClusterStream.cs index 310b291..67f050f 100644 --- a/DiscUtils/DiscUtils.Fat/ClusterStream.cs +++ b/DiscUtils/DiscUtils.Fat/ClusterStream.cs @@ -194,8 +194,7 @@ namespace DiscUtils.Fat if (desiredNumClusters < actualNumClusters) { - uint cluster; - if (!TryGetClusterByPosition(value, out cluster)) + if (!TryGetClusterByPosition(value, out uint cluster)) { throw new IOException("Internal state corrupt - unable to find cluster"); } @@ -218,8 +217,7 @@ namespace DiscUtils.Fat } else if (desiredNumClusters > actualNumClusters) { - uint cluster; - while (!TryGetClusterByPosition(value, out cluster)) + while (!TryGetClusterByPosition(value, out uint cluster)) { cluster = ExtendChain(); _reader.WipeCluster(cluster); @@ -314,7 +312,7 @@ namespace DiscUtils.Fat // Partial cluster, so need to read existing cluster data first LoadCluster(cluster); - int copyLength = Math.Min(count, _reader.ClusterSize - pos % _reader.ClusterSize); + int copyLength = Math.Min(count, _reader.ClusterSize - (pos % _reader.ClusterSize)); Array.Copy(buffer, offset, _clusterBuffer, pos, copyLength); WriteCurrentCluster(); @@ -331,13 +329,12 @@ namespace DiscUtils.Fat private uint ExtendChain() { // Sanity check - make sure the final known cluster is the EOC marker - if (!_fat.IsEndOfChain(_knownClusters[_knownClusters.Count - 1])) + if (!_fat.IsEndOfChain(_knownClusters[^1])) { throw new IOException("Corrupt file system: final cluster isn't End-of-Chain"); } - uint cluster; - if (!_fat.TryGetFreeCluster(out cluster)) + if (!_fat.TryGetFreeCluster(out uint cluster)) { throw new IOException("Out of disk space"); } @@ -349,10 +346,10 @@ namespace DiscUtils.Fat } else { - _fat.SetNext(_knownClusters[_knownClusters.Count - 2], cluster); + _fat.SetNext(_knownClusters[^2], cluster); } - _knownClusters[_knownClusters.Count - 1] = cluster; + _knownClusters[^1] = cluster; _knownClusters.Add(_fat.GetNext(cluster)); return cluster; @@ -373,8 +370,7 @@ namespace DiscUtils.Fat private bool TryLoadClusterByPosition(long pos) { - uint cluster; - if (!TryGetClusterByPosition(pos, out cluster)) + if (!TryGetClusterByPosition(pos, out uint cluster)) { return false; } @@ -408,13 +404,10 @@ namespace DiscUtils.Fat { int index = (int)(pos / _reader.ClusterSize); - if (_knownClusters.Count <= index) + if (_knownClusters.Count <= index && !TryPopulateKnownClusters(index)) { - if (!TryPopulateKnownClusters(index)) - { - cluster = uint.MaxValue; - return false; - } + cluster = uint.MaxValue; + return false; } // Chain is shorter than the current stream position @@ -438,7 +431,7 @@ namespace DiscUtils.Fat private bool TryPopulateKnownClusters(int index) { - uint lastKnown = _knownClusters[_knownClusters.Count - 1]; + uint lastKnown = _knownClusters[^1]; while (!_fat.IsEndOfChain(lastKnown) && _knownClusters.Count <= index) { lastKnown = _fat.GetNext(lastKnown); @@ -450,7 +443,7 @@ namespace DiscUtils.Fat private uint DetectLength() { - while (!_fat.IsEndOfChain(_knownClusters[_knownClusters.Count - 1])) + while (!_fat.IsEndOfChain(_knownClusters[^1])) { if (!TryPopulateKnownClusters(_knownClusters.Count)) { diff --git a/DiscUtils/DiscUtils.Fat/DirectoryEntry.cs b/DiscUtils/DiscUtils.Fat/DirectoryEntry.cs index 7c9a618..a631616 100644 --- a/DiscUtils/DiscUtils.Fat/DirectoryEntry.cs +++ b/DiscUtils/DiscUtils.Fat/DirectoryEntry.cs @@ -159,7 +159,7 @@ namespace DiscUtils.Fat int day = date & 0x001F; int hour = (time & 0xF800) >> 11; int minute = (time & 0x07E0) >> 5; - int second = (time & 0x001F) * 2 + tenths / 100; + int second = ((time & 0x001F) * 2) + (tenths / 100); int millis = tenths % 100 * 10; return new DateTime(year, month, day, hour, minute, second, millis); @@ -167,15 +167,12 @@ namespace DiscUtils.Fat private static void DateTimeToFileTime(DateTime value, out ushort date) { - byte tenths; - ushort time; - DateTimeToFileTime(value, out date, out time, out tenths); + DateTimeToFileTime(value, out date, out ushort time, out byte tenths); } private static void DateTimeToFileTime(DateTime value, out ushort date, out ushort time) { - byte tenths; - DateTimeToFileTime(value, out date, out time, out tenths); + DateTimeToFileTime(value, out date, out time, out byte tenths); } private static void DateTimeToFileTime(DateTime value, out ushort date, out ushort time, out byte tenths) @@ -189,7 +186,7 @@ namespace DiscUtils.Fat (ushort)((((value.Year - 1980) << 9) & 0xFE00) | ((value.Month << 5) & 0x01E0) | (value.Day & 0x001F)); time = (ushort)(((value.Hour << 11) & 0xF800) | ((value.Minute << 5) & 0x07E0) | ((value.Second / 2) & 0x001F)); - tenths = (byte)(value.Second % 2 * 100 + value.Millisecond / 10); + tenths = (byte)((value.Second % 2 * 100) + (value.Millisecond / 10)); } private void Load(byte[] data, int offset) diff --git a/DiscUtils/DiscUtils.Fat/FatBuffer.cs b/DiscUtils/DiscUtils.Fat/FatBuffer.cs index 63dbddb..a18d3c2 100644 --- a/DiscUtils/DiscUtils.Fat/FatBuffer.cs +++ b/DiscUtils/DiscUtils.Fat/FatBuffer.cs @@ -71,15 +71,13 @@ namespace DiscUtils.Fat { get { - switch (_type) + return _type switch { - case FatType.Fat12: - return _buffer.Length / 3 * 2; - case FatType.Fat16: - return _buffer.Length / 2; - default: // FAT32 - return _buffer.Length / 4; - } + FatType.Fat12 => _buffer.Length / 3 * 2, + FatType.Fat16 => _buffer.Length / 2, + // FAT32 + _ => _buffer.Length / 4, + }; } } @@ -95,32 +93,24 @@ namespace DiscUtils.Fat internal bool IsEndOfChain(uint val) { - switch (_type) + return _type switch { - case FatType.Fat12: - return (val & 0x0FFF) >= 0x0FF8; - case FatType.Fat16: - return (val & 0xFFFF) >= 0xFFF8; - case FatType.Fat32: - return (val & 0x0FFFFFF8) >= 0x0FFFFFF8; - default: - throw new ArgumentException("Unknown FAT type"); - } + FatType.Fat12 => (val & 0x0FFF) >= 0x0FF8, + FatType.Fat16 => (val & 0xFFFF) >= 0xFFF8, + FatType.Fat32 => (val & 0x0FFFFFF8) >= 0x0FFFFFF8, + _ => throw new ArgumentException("Unknown FAT type"), + }; } internal bool IsBadCluster(uint val) { - switch (_type) + return _type switch { - case FatType.Fat12: - return (val & 0x0FFF) == 0x0FF7; - case FatType.Fat16: - return (val & 0xFFFF) == 0xFFF7; - case FatType.Fat32: - return (val & 0x0FFFFFF8) == 0x0FFFFFF7; - default: - throw new ArgumentException("Unknown FAT type"); - } + FatType.Fat12 => (val & 0x0FFF) == 0x0FF7, + FatType.Fat16 => (val & 0xFFFF) == 0xFFF7, + FatType.Fat32 => (val & 0x0FFFFFF8) == 0x0FFFFFF7, + _ => throw new ArgumentException("Unknown FAT type"), + }; } internal uint GetNext(uint cluster) @@ -138,9 +128,9 @@ namespace DiscUtils.Fat if ((cluster & 1) != 0) { return - (uint)((EndianUtilities.ToUInt16LittleEndian(_buffer, (int)(cluster + cluster / 2)) >> 4) & 0x0FFF); + (uint)((EndianUtilities.ToUInt16LittleEndian(_buffer, (int)(cluster + (cluster / 2))) >> 4) & 0x0FFF); } - return (uint)(EndianUtilities.ToUInt16LittleEndian(_buffer, (int)(cluster + cluster / 2)) & 0x0FFF); + return (uint)(EndianUtilities.ToUInt16LittleEndian(_buffer, (int)(cluster + (cluster / 2))) & 0x0FFF); } internal void SetEndOfChain(uint cluster) @@ -179,19 +169,19 @@ namespace DiscUtils.Fat } else { - uint offset = cluster + cluster / 2; + uint offset = cluster + (cluster / 2); MarkDirty(offset); MarkDirty(offset + 1); // On alternate sector boundaries, cluster info crosses two sectors ushort maskedOldVal; if ((cluster & 1) != 0) { - next = next << 4; + next <<= 4; maskedOldVal = (ushort)(EndianUtilities.ToUInt16LittleEndian(_buffer, (int)offset) & 0x000F); } else { - next = next & 0x0FFF; + next &= 0x0FFF; maskedOldVal = (ushort)(EndianUtilities.ToUInt16LittleEndian(_buffer, (int)offset) & 0xF000); } @@ -230,7 +220,7 @@ namespace DiscUtils.Fat internal List GetChain(uint head) { - List result = new List(); + List result = new(); if (head != 0) { @@ -254,7 +244,7 @@ namespace DiscUtils.Fat { foreach (uint val in _dirtySectors.Values) { - stream.Position = position + val * DirtyRegionSize; + stream.Position = position + (val * DirtyRegionSize); stream.Write(_buffer, (int)(val * DirtyRegionSize), (int)DirtyRegionSize); } } diff --git a/DiscUtils/DiscUtils.Fat/FatFileSystemOptions.cs b/DiscUtils/DiscUtils.Fat/FatFileSystemOptions.cs index 175f4f7..af7bfa0 100644 --- a/DiscUtils/DiscUtils.Fat/FatFileSystemOptions.cs +++ b/DiscUtils/DiscUtils.Fat/FatFileSystemOptions.cs @@ -39,7 +39,7 @@ namespace DiscUtils.Fat internal FatFileSystemOptions(FileSystemParameters parameters) { - if (parameters != null && parameters.FileNameEncoding != null) + if (parameters?.FileNameEncoding != null) { FileNameEncoding = parameters.FileNameEncoding; } diff --git a/DiscUtils/DiscUtils.Fat/FileAllocationTable.cs b/DiscUtils/DiscUtils.Fat/FileAllocationTable.cs index c034477..24f24b7 100644 --- a/DiscUtils/DiscUtils.Fat/FileAllocationTable.cs +++ b/DiscUtils/DiscUtils.Fat/FileAllocationTable.cs @@ -39,7 +39,7 @@ namespace DiscUtils.Fat _firstFatSector = firstFatSector; _numFats = numFats; - _stream.Position = (firstFatSector + fatSize * activeFat) * Sizes.Sector; + _stream.Position = (firstFatSector + (fatSize * activeFat)) * Sizes.Sector; _buffer = new FatBuffer(type, StreamUtilities.ReadExact(_stream, (int)(fatSize * Sizes.Sector))); } @@ -82,7 +82,7 @@ namespace DiscUtils.Fat { for (int i = 0; i < _numFats; ++i) { - _buffer.WriteDirtyRegions(_stream, _firstFatSector * Sizes.Sector + _buffer.Size * i); + _buffer.WriteDirtyRegions(_stream, (_firstFatSector * Sizes.Sector) + (_buffer.Size * i)); } _buffer.ClearDirtyRegions(); diff --git a/DiscUtils/DiscUtils.Fat/FileName.cs b/DiscUtils/DiscUtils.Fat/FileName.cs index ab2d58d..c1cd0c2 100644 --- a/DiscUtils/DiscUtils.Fat/FileName.cs +++ b/DiscUtils/DiscUtils.Fat/FileName.cs @@ -31,13 +31,13 @@ namespace DiscUtils.Fat private const byte SpaceByte = 0x20; public static readonly FileName SelfEntryName = - new FileName(new byte[] { 0x2E, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, 0); + new(new byte[] { 0x2E, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, 0); public static readonly FileName ParentEntryName = - new FileName(new byte[] { 0x2E, 0x2E, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, 0); + new(new byte[] { 0x2E, 0x2E, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, 0); public static readonly FileName Null = - new FileName(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0); + new(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0); private static readonly byte[] InvalidBytes = { 0x22, 0x2A, 0x2B, 0x2C, 0x2E, 0x2F, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x5B, 0x5C, 0x5D, 0x7C }; diff --git a/DiscUtils/DiscUtils.Fat/FileSystemFactory.cs b/DiscUtils/DiscUtils.Fat/FileSystemFactory.cs index 25982f7..8228f88 100644 --- a/DiscUtils/DiscUtils.Fat/FileSystemFactory.cs +++ b/DiscUtils/DiscUtils.Fat/FileSystemFactory.cs @@ -36,7 +36,7 @@ namespace DiscUtils.Fat return new FileSystemInfo[] { new VfsFileSystemInfo("FAT", "Microsoft FAT", Open) }; } - return new FileSystemInfo[0]; + return System.Array.Empty(); } private DiscFileSystem Open(Stream stream, VolumeInfo volumeInfo, FileSystemParameters parameters) diff --git a/DiscUtils/DiscUtils.Fat/Modified/Directory.cs b/DiscUtils/DiscUtils.Fat/Modified/Directory.cs index b0869d0..c1f2247 100644 --- a/DiscUtils/DiscUtils.Fat/Modified/Directory.cs +++ b/DiscUtils/DiscUtils.Fat/Modified/Directory.cs @@ -43,8 +43,8 @@ namespace DiscUtils.Fat private DirectoryEntry _parentEntry; private long _parentEntryLocation; - internal Dictionary LongFileNames_ShortKey = new Dictionary(StringComparer.OrdinalIgnoreCase); - internal Dictionary LongFileNames_LongKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + internal Dictionary LongFileNames_ShortKey = new(StringComparer.OrdinalIgnoreCase); + internal Dictionary LongFileNames_LongKey = new(StringComparer.OrdinalIgnoreCase); /// /// Initializes a new instance of the Directory class. Use this constructor to represent non-root directories. @@ -81,22 +81,22 @@ namespace DiscUtils.Fat // see http://home.teleport.com/~brainy/lfn.htm // NOTE: we assume ordinals are ok here. char[] chars = new char[13]; - chars[0] = (char)(256 * buffer[2] + buffer[1]); - chars[1] = (char)(256 * buffer[4] + buffer[3]); - chars[2] = (char)(256 * buffer[6] + buffer[5]); - chars[3] = (char)(256 * buffer[8] + buffer[7]); - chars[4] = (char)(256 * buffer[10] + buffer[9]); + chars[0] = (char)((256 * buffer[2]) + buffer[1]); + chars[1] = (char)((256 * buffer[4]) + buffer[3]); + chars[2] = (char)((256 * buffer[6]) + buffer[5]); + chars[3] = (char)((256 * buffer[8]) + buffer[7]); + chars[4] = (char)((256 * buffer[10]) + buffer[9]); - chars[5] = (char)(256 * buffer[15] + buffer[14]); - chars[6] = (char)(256 * buffer[17] + buffer[16]); - chars[7] = (char)(256 * buffer[19] + buffer[18]); - chars[8] = (char)(256 * buffer[21] + buffer[20]); - chars[9] = (char)(256 * buffer[23] + buffer[22]); - chars[10] = (char)(256 * buffer[25] + buffer[24]); + chars[5] = (char)((256 * buffer[15]) + buffer[14]); + chars[6] = (char)((256 * buffer[17]) + buffer[16]); + chars[7] = (char)((256 * buffer[19]) + buffer[18]); + chars[8] = (char)((256 * buffer[21]) + buffer[20]); + chars[9] = (char)((256 * buffer[23]) + buffer[22]); + chars[10] = (char)((256 * buffer[25]) + buffer[24]); - chars[11] = (char)(256 * buffer[29] + buffer[28]); - chars[12] = (char)(256 * buffer[31] + buffer[30]); - string chunk = new string(chars); + chars[11] = (char)((256 * buffer[29]) + buffer[28]); + chars[12] = (char)((256 * buffer[31]) + buffer[30]); + string chunk = new(chars); int zero = chunk.IndexOf('\0'); return zero >= 0 ? chunk.Substring(0, zero) : chunk; } @@ -133,10 +133,7 @@ namespace DiscUtils.Fat set { - if (_parent != null) - { - _parent.UpdateEntry(_parentId, value); - } + _parent?.UpdateEntry(_parentId, value); } } @@ -195,7 +192,7 @@ namespace DiscUtils.Fat public DirectoryEntry[] GetDirectories() { - List dirs = new List(_entries.Count); + List dirs = new(_entries.Count); foreach (DirectoryEntry dirEntry in _entries.Values) { if ((dirEntry.Attributes & FatAttributes.Directory) != 0) @@ -209,7 +206,7 @@ namespace DiscUtils.Fat public DirectoryEntry[] GetFiles() { - List files = new List(_entries.Count); + List files = new(_entries.Count); foreach (DirectoryEntry dirEntry in _entries.Values) { if ((dirEntry.Attributes & (FatAttributes.Directory | FatAttributes.VolumeId)) == 0) @@ -261,15 +258,14 @@ namespace DiscUtils.Fat { try { - uint firstCluster; - if (!_fileSystem.Fat.TryGetFreeCluster(out firstCluster)) + if (!_fileSystem.Fat.TryGetFreeCluster(out uint firstCluster)) { throw new IOException("Failed to allocate first cluster for new directory"); } _fileSystem.Fat.SetEndOfChain(firstCluster); - DirectoryEntry newEntry = new DirectoryEntry(_fileSystem.FatOptions, name, FatAttributes.Directory, _fileSystem.FatVariant); + DirectoryEntry newEntry = new(_fileSystem.FatOptions, name, FatAttributes.Directory, _fileSystem.FatVariant); newEntry.FirstCluster = firstCluster; newEntry.CreationTime = _fileSystem.ConvertFromUtc(DateTime.UtcNow); newEntry.LastWriteTime = newEntry.CreationTime; @@ -297,11 +293,11 @@ namespace DiscUtils.Fat throw new IOException("Directory entry already exists"); } - DirectoryEntry newEntry = new DirectoryEntry(newChild.ParentsChildEntry); + DirectoryEntry newEntry = new(newChild.ParentsChildEntry); newEntry.Name = name; AddEntry(newEntry); - DirectoryEntry newParentEntry = new DirectoryEntry(SelfEntry); + DirectoryEntry newParentEntry = new(SelfEntry); newParentEntry.Name = FileName.ParentEntryName; newChild.ParentEntry = newParentEntry; } @@ -367,7 +363,7 @@ namespace DiscUtils.Fat else if ((mode == FileMode.OpenOrCreate || mode == FileMode.CreateNew || mode == FileMode.Create) && !exists) { // Create new file - DirectoryEntry newEntry = new DirectoryEntry(_fileSystem.FatOptions, name, FatAttributes.Archive, _fileSystem.FatVariant); + DirectoryEntry newEntry = new(_fileSystem.FatOptions, name, FatAttributes.Archive, _fileSystem.FatVariant); newEntry.FirstCluster = 0; // i.e. Zero-length newEntry.CreationTime = _fileSystem.ConvertFromUtc(DateTime.UtcNow); newEntry.LastWriteTime = newEntry.CreationTime; @@ -421,7 +417,7 @@ namespace DiscUtils.Fat { DirectoryEntry entry = _entries[id]; - DirectoryEntry copy = new DirectoryEntry(entry); + DirectoryEntry copy = new(entry); copy.Name = entry.Name.Deleted(); _dirStream.Position = id; copy.WriteTo(_dirStream); @@ -466,7 +462,7 @@ namespace DiscUtils.Fat while (_dirStream.Position < _dirStream.Length) { long streamPos = _dirStream.Position; - DirectoryEntry entry = new DirectoryEntry(_fileSystem.FatOptions, _dirStream, _fileSystem.FatVariant); + DirectoryEntry entry = new(_fileSystem.FatOptions, _dirStream, _fileSystem.FatVariant); if (entry.Attributes == (FatAttributes.ReadOnly | FatAttributes.Hidden | FatAttributes.System | FatAttributes.VolumeId)) { @@ -542,20 +538,18 @@ namespace DiscUtils.Fat private void PopulateNewChildDirectory(DirectoryEntry newEntry) { // Populate new directory with initial (special) entries. First one is easy, just change the name! - using (ClusterStream stream = new ClusterStream(_fileSystem, FileAccess.Write, newEntry.FirstCluster, uint.MaxValue)) - { - // First is the self-referencing entry... - DirectoryEntry selfEntry = new DirectoryEntry(newEntry); - selfEntry.Name = FileName.SelfEntryName; - selfEntry.WriteTo(stream); + using ClusterStream stream = new(_fileSystem, FileAccess.Write, newEntry.FirstCluster, uint.MaxValue); + // First is the self-referencing entry... + DirectoryEntry selfEntry = new(newEntry); + selfEntry.Name = FileName.SelfEntryName; + selfEntry.WriteTo(stream); - // Second is a clone of our self entry (i.e. parent) - though dates are odd... - DirectoryEntry parentEntry = new DirectoryEntry(SelfEntry); - parentEntry.Name = FileName.ParentEntryName; - parentEntry.CreationTime = newEntry.CreationTime; - parentEntry.LastWriteTime = newEntry.LastWriteTime; - parentEntry.WriteTo(stream); - } + // Second is a clone of our self entry (i.e. parent) - though dates are odd... + DirectoryEntry parentEntry = new(SelfEntry); + parentEntry.Name = FileName.ParentEntryName; + parentEntry.CreationTime = newEntry.CreationTime; + parentEntry.LastWriteTime = newEntry.LastWriteTime; + parentEntry.WriteTo(stream); } private void Dispose(bool disposing) diff --git a/DiscUtils/DiscUtils.Fat/Modified/FatFileSystem.cs b/DiscUtils/DiscUtils.Fat/Modified/FatFileSystem.cs index f6df949..6ffc04b 100644 --- a/DiscUtils/DiscUtils.Fat/Modified/FatFileSystem.cs +++ b/DiscUtils/DiscUtils.Fat/Modified/FatFileSystem.cs @@ -40,7 +40,7 @@ namespace DiscUtils.Fat /// /// The Epoch for FAT file systems (1st Jan, 1980). /// - public static readonly DateTime Epoch = new DateTime(1980, 1, 1); + public static readonly DateTime Epoch = new(1980, 1, 1); private TimeConverter _timeConverter; private Stream _data; @@ -158,7 +158,7 @@ namespace DiscUtils.Fat { _dirCache = new Dictionary(); - if (parameters != null && parameters.TimeConverter != null) + if (parameters?.TimeConverter != null) { _timeConverter = parameters.TimeConverter; } @@ -196,13 +196,13 @@ namespace DiscUtils.Fat { get { - switch (_type) + return _type switch { - case FatType.Fat12: return "Microsoft FAT12"; - case FatType.Fat16: return "Microsoft FAT16"; - case FatType.Fat32: return "Microsoft FAT32"; - default: return "Unknown FAT"; - } + FatType.Fat12 => "Microsoft FAT12", + FatType.Fat16 => "Microsoft FAT16", + FatType.Fat32 => "Microsoft FAT32", + _ => "Unknown FAT", + }; } } @@ -463,14 +463,14 @@ namespace DiscUtils.Fat // Write both FAT copies uint fatSize = CalcFatSize(sectors, FatType.Fat12, 1); byte[] fat = new byte[fatSize * Sizes.Sector]; - FatBuffer fatBuffer = new FatBuffer(FatType.Fat12, fat); + FatBuffer fatBuffer = new(FatType.Fat12, fat); fatBuffer.SetNext(0, 0xFFFFFFF0); fatBuffer.SetEndOfChain(1); stream.Write(fat, 0, fat.Length); stream.Write(fat, 0, fat.Length); // Write the (empty) root directory - uint rootDirSectors = ((224 * 32) + Sizes.Sector - 1) / Sizes.Sector; + const uint rootDirSectors = ((224 * 32) + Sizes.Sector - 1) / Sizes.Sector; byte[] rootDir = new byte[rootDirSectors * Sizes.Sector]; stream.Write(rootDir, 0, rootDir.Length); @@ -493,16 +493,14 @@ namespace DiscUtils.Fat /// An object that provides access to the newly created partition file system. public static FatFileSystem FormatPartition(VirtualDisk disk, int partitionIndex, string label) { - using (Stream partitionStream = disk.Partitions[partitionIndex].Open()) - { - return FormatPartition( - partitionStream, - label, - disk.Geometry, - (int)disk.Partitions[partitionIndex].FirstSector, - (int)(1 + disk.Partitions[partitionIndex].LastSector - disk.Partitions[partitionIndex].FirstSector), - 0); - } + using Stream partitionStream = disk.Partitions[partitionIndex].Open(); + return FormatPartition( + partitionStream, + label, + disk.Geometry, + (int)disk.Partitions[partitionIndex].FirstSector, + (int)(1 + disk.Partitions[partitionIndex].LastSector - disk.Partitions[partitionIndex].FirstSector), + 0); } /// @@ -612,7 +610,7 @@ namespace DiscUtils.Fat */ byte[] fat = new byte[CalcFatSize((uint)sectorCount, fatType, sectorsPerCluster) * Sizes.Sector]; - FatBuffer fatBuffer = new FatBuffer(fatType, fat); + FatBuffer fatBuffer = new(fatType, fat); fatBuffer.SetNext(0, 0xFFFFFFF8); fatBuffer.SetEndOfChain(1); if (fatType >= FatType.Fat32) @@ -780,8 +778,7 @@ namespace DiscUtils.Fat return; } - Directory parent; - long id = GetDirectoryEntry(path, out parent); + long id = GetDirectoryEntry(path, out Directory parent); DirectoryEntry dirEntry = parent.GetEntry(id); FatAttributes newFatAttr = (FatAttributes)newValue; @@ -836,7 +833,7 @@ namespace DiscUtils.Fat return; } - UpdateDirEntry(path, (e) => { e.CreationTime = newTime; }); + UpdateDirEntry(path, (e) => e.CreationTime = newTime); } /// @@ -871,7 +868,7 @@ namespace DiscUtils.Fat return; } - UpdateDirEntry(path, (e) => { e.CreationTime = ConvertFromUtc(newTime); }); + UpdateDirEntry(path, (e) => e.CreationTime = ConvertFromUtc(newTime)); } /// @@ -906,7 +903,7 @@ namespace DiscUtils.Fat return; } - UpdateDirEntry(path, (e) => { e.LastAccessTime = newTime; }); + UpdateDirEntry(path, (e) => e.LastAccessTime = newTime); } /// @@ -941,7 +938,7 @@ namespace DiscUtils.Fat return; } - UpdateDirEntry(path, (e) => { e.LastAccessTime = ConvertFromUtc(newTime); }); + UpdateDirEntry(path, (e) => e.LastAccessTime = ConvertFromUtc(newTime)); } /// @@ -976,7 +973,7 @@ namespace DiscUtils.Fat return; } - UpdateDirEntry(path, (e) => { e.LastWriteTime = newTime; }); + UpdateDirEntry(path, (e) => e.LastWriteTime = newTime); } /// @@ -1011,7 +1008,7 @@ namespace DiscUtils.Fat return; } - UpdateDirEntry(path, (e) => { e.LastWriteTime = ConvertFromUtc(newTime); }); + UpdateDirEntry(path, (e) => e.LastWriteTime = ConvertFromUtc(newTime)); } /// @@ -1032,8 +1029,7 @@ namespace DiscUtils.Fat /// Whether to permit over-writing of an existing file. public override void CopyFile(string sourceFile, string destinationFile, bool overwrite) { - Directory sourceDir; - long sourceEntryId = GetDirectoryEntry(sourceFile, out sourceDir); + long sourceEntryId = GetDirectoryEntry(sourceFile, out Directory sourceDir); if (sourceDir == null || sourceEntryId < 0) { @@ -1047,12 +1043,11 @@ namespace DiscUtils.Fat throw new IOException("The source file is a directory"); } - DirectoryEntry newEntry = new DirectoryEntry(sourceEntry); + DirectoryEntry newEntry = new(sourceEntry); newEntry.Name = FileName.FromPath(destinationFile, FatOptions.FileNameEncoding); newEntry.FirstCluster = 0; - Directory destDir; - long destEntryId = GetDirectoryEntry(destinationFile, out destDir); + long destEntryId = GetDirectoryEntry(destinationFile, out Directory destDir); if (destDir == null) { @@ -1095,11 +1090,9 @@ namespace DiscUtils.Fat destEntryId = destDir.AddEntry(newEntry); // Copy the contents... - using (Stream sourceStream = new FatFileStream(this, sourceDir, sourceEntryId, FileAccess.Read), - destStream = new FatFileStream(this, destDir, destEntryId, FileAccess.Write)) - { - StreamUtilities.PumpStreams(sourceStream, destStream); - } + using Stream sourceStream = new FatFileStream(this, sourceDir, sourceEntryId, FileAccess.Read), + destStream = new FatFileStream(this, destDir, destEntryId, FileAccess.Write); + StreamUtilities.PumpStreams(sourceStream, destStream); } /// @@ -1151,8 +1144,7 @@ namespace DiscUtils.Fat throw new IOException("Unable to delete non-empty directory"); } - Directory parent; - long id = GetDirectoryEntry(path, out parent); + long id = GetDirectoryEntry(path, out Directory parent); if (parent == null && id == 0) { throw new IOException("Unable to delete root directory"); @@ -1175,8 +1167,7 @@ namespace DiscUtils.Fat /// The path of the file to delete. public override void DeleteFile(string path) { - Directory parent; - long id = GetDirectoryEntry(path, out parent); + long id = GetDirectoryEntry(path, out Directory parent); if (parent == null || id < 0) { throw new FileNotFoundException("No such file", path); @@ -1261,7 +1252,7 @@ namespace DiscUtils.Fat } DirectoryEntry[] entries = dir.GetDirectories(); - List dirs = new List(entries.Length); + List dirs = new(entries.Length); foreach (DirectoryEntry dirEntry in entries) { dirs.Add(Utilities.CombinePaths(path, dirEntry.Name.GetDisplayName(FatOptions.FileNameEncoding))); @@ -1282,7 +1273,7 @@ namespace DiscUtils.Fat { Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern); - List dirs = new List(); + List dirs = new(); DoSearch(dirs, path, re, searchOption == SearchOption.AllDirectories, true, false); return dirs.ToArray(); } @@ -1297,7 +1288,7 @@ namespace DiscUtils.Fat Directory dir = GetDirectory(path); DirectoryEntry[] entries = dir.GetFiles(); - List files = new List(entries.Length); + List files = new(entries.Length); foreach (DirectoryEntry dirEntry in entries) { files.Add(Utilities.CombinePaths(path, dirEntry.Name.GetDisplayName(FatOptions.FileNameEncoding))); @@ -1318,7 +1309,7 @@ namespace DiscUtils.Fat { Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern); - List results = new List(); + List results = new(); DoSearch(results, path, re, searchOption == SearchOption.AllDirectories, false, true); return results.ToArray(); } @@ -1333,7 +1324,7 @@ namespace DiscUtils.Fat Directory dir = GetDirectory(path); DirectoryEntry[] entries = dir.Entries; - List result = new List(entries.Length); + List result = new(entries.Length); foreach (DirectoryEntry dirEntry in entries) { result.Add(Utilities.CombinePaths(path, dirEntry.Name.GetDisplayName(FatOptions.FileNameEncoding))); @@ -1356,7 +1347,7 @@ namespace DiscUtils.Fat Directory dir = GetDirectory(path); DirectoryEntry[] entries = dir.Entries; - List result = new List(entries.Length); + List result = new(entries.Length); foreach (DirectoryEntry dirEntry in entries) { if (re.IsMatch(dirEntry.Name.GetSearchName(FatOptions.FileNameEncoding))) @@ -1387,8 +1378,7 @@ namespace DiscUtils.Fat } } - Directory destParent; - long destId = GetDirectoryEntry(destinationDirectoryName, out destParent); + long destId = GetDirectoryEntry(destinationDirectoryName, out Directory destParent); if (destParent == null) { throw new DirectoryNotFoundException("Target directory doesn't exist"); @@ -1398,8 +1388,7 @@ namespace DiscUtils.Fat throw new IOException("Target directory already exists"); } - Directory sourceParent; - long sourceId = GetDirectoryEntry(sourceDirectoryName, out sourceParent); + long sourceId = GetDirectoryEntry(sourceDirectoryName, out Directory sourceParent); if (sourceParent == null || sourceId < 0) { throw new IOException("Source directory doesn't exist"); @@ -1417,8 +1406,7 @@ namespace DiscUtils.Fat /// Whether to permit a destination file to be overwritten. public override void MoveFile(string sourceName, string destinationName, bool overwrite) { - Directory sourceDir; - long sourceEntryId = GetDirectoryEntry(sourceName, out sourceDir); + long sourceEntryId = GetDirectoryEntry(sourceName, out Directory sourceDir); if (sourceDir == null || sourceEntryId < 0) { @@ -1432,11 +1420,10 @@ namespace DiscUtils.Fat throw new IOException("The source file is a directory"); } - DirectoryEntry newEntry = new DirectoryEntry(sourceEntry); + DirectoryEntry newEntry = new(sourceEntry); newEntry.Name = FileName.FromPath(destinationName, FatOptions.FileNameEncoding); - Directory destDir; - long destEntryId = GetDirectoryEntry(destinationName, out destDir); + long destEntryId = GetDirectoryEntry(destinationName, out Directory destDir); if (destDir == null) { @@ -1492,14 +1479,13 @@ namespace DiscUtils.Fat internal Directory GetDirectory(string path) { - Directory parent; if (string.IsNullOrEmpty(path) || path == "\\") { return _rootDir; } - long id = GetDirectoryEntry(_rootDir, path, out parent); + long id = GetDirectoryEntry(_rootDir, path, out Directory parent); if (id >= 0) { return GetDirectory(parent, id); @@ -1524,8 +1510,7 @@ namespace DiscUtils.Fat } // If we have this one cached, return it - Directory result; - if (_dirCache.TryGetValue(dirEntry.FirstCluster, out result)) + if (_dirCache.TryGetValue(dirEntry.FirstCluster, out Directory result)) { return result; } @@ -1549,9 +1534,8 @@ namespace DiscUtils.Fat internal DirectoryEntry GetDirectoryEntry(string path) { - Directory parent; - long id = GetDirectoryEntry(_rootDir, path, out parent); + long id = GetDirectoryEntry(_rootDir, path, out Directory parent); if (parent == null || id < 0) { return null; @@ -1707,7 +1691,7 @@ namespace DiscUtils.Fat private static uint CalcFatSize(uint sectors, FatType fatType, byte sectorsPerCluster) { uint numClusters = (uint)(sectors / sectorsPerCluster); - uint fatBytes = (numClusters * (ushort)fatType) / 8; + uint fatBytes = numClusters * (ushort)fatType / 8; return (fatBytes + Sizes.Sector - 1) / Sizes.Sector; } @@ -1894,8 +1878,7 @@ namespace DiscUtils.Fat else { // Long filename support - translate long filename lookup to short filename - string ShortName; - if (dir.LongFileNames_LongKey.TryGetValue(pathEntries[pathOffset], out ShortName)) + if (dir.LongFileNames_LongKey.TryGetValue(pathEntries[pathOffset], out string ShortName)) pathEntries[pathOffset] = ShortName; entryId = dir.FindEntry(new FileName(pathEntries[pathOffset], FatOptions.FileNameEncoding)); @@ -1955,8 +1938,7 @@ namespace DiscUtils.Fat private void UpdateDirEntry(string path, EntryUpdateAction action) { - Directory parent; - long id = GetDirectoryEntry(path, out parent); + long id = GetDirectoryEntry(path, out Directory parent); DirectoryEntry entry = parent.GetEntry(id); action(entry); parent.UpdateEntry(id, entry); @@ -1973,7 +1955,7 @@ namespace DiscUtils.Fat /// /// Size of the Filesystem in bytes /// - public override long Size { get { return ((TotalSectors - ReservedSectorCount - (FatSize * FatCount)) * BytesPerSector); } } + public override long Size { get { return (TotalSectors - ReservedSectorCount - (FatSize * FatCount)) * BytesPerSector; } } /// /// Used space of the Filesystem in bytes @@ -1991,7 +1973,7 @@ namespace DiscUtils.Fat usedCluster++; } } - return (usedCluster * SectorsPerCluster * BytesPerSector); + return usedCluster * SectorsPerCluster * BytesPerSector; } } @@ -2016,8 +1998,7 @@ namespace DiscUtils.Fat if (dir == null) return fileName; - string lfn; - if (dir.LongFileNames_ShortKey.TryGetValue(Path.GetFileName(shortFullPath), out lfn)) + if (dir.LongFileNames_ShortKey.TryGetValue(Path.GetFileName(shortFullPath), out string lfn)) return lfn; return fileName; diff --git a/FilePickerControl.xaml.cs b/FilePickerControl.xaml.cs index 0156d93..780d51c 100644 --- a/FilePickerControl.xaml.cs +++ b/FilePickerControl.xaml.cs @@ -213,9 +213,9 @@ namespace WPinternals CaptionWidth += 10; } - bool SelectVisible = (Path == null); - bool ChangeVisible = (Path != null); - bool ClearVisible = ((Path != null) && AllowNull); + bool SelectVisible = Path == null; + bool ChangeVisible = Path != null; + bool ClearVisible = (Path != null) && AllowNull; double NewWidth = ActualWidth - CaptionWidth; if (SelectVisible) @@ -225,12 +225,12 @@ namespace WPinternals if (ChangeVisible) { - NewWidth -= (ChangeLink.ActualWidth + 10); + NewWidth -= ChangeLink.ActualWidth + 10; } if (ClearVisible) { - NewWidth -= (ClearLink.ActualWidth + 10); + NewWidth -= ClearLink.ActualWidth + 10; } SetText(NewWidth); diff --git a/HelperClasses.cs b/HelperClasses.cs index 493aa77..c7d8511 100644 --- a/HelperClasses.cs +++ b/HelperClasses.cs @@ -307,14 +307,11 @@ namespace WPinternals Blocks.Clear(); - if (IsInitialized) + if (IsInitialized && !value) { - if (!value) + foreach (Block Block in CollapsibleBlocks) { - foreach (Block Block in CollapsibleBlocks) - { - Blocks.Add(Block); - } + Blocks.Add(Block); } } } @@ -335,11 +332,11 @@ namespace WPinternals for (int i = 0; i < inlinesCount; i++) { Inline inline = this.Inlines.ElementAt(i); - if (inline is Run) + if (inline is Run run) { - if ((inline as Run)?.Text == Convert.ToChar(32).ToString()) //ACSII 32 is the white space + if (run.Text == Convert.ToChar(32).ToString()) //ACSII 32 is the white space { - (inline as Run).Text = string.Empty; + run.Text = string.Empty; } } } @@ -401,13 +398,13 @@ namespace WPinternals else if (BigEndianBytes.Length > Width) { Result = new byte[Width]; - System.Buffer.BlockCopy(BigEndianBytes, BigEndianBytes.Length - Width, Result, 0, Width); + Buffer.BlockCopy(BigEndianBytes, BigEndianBytes.Length - Width, Result, 0, Width); return Result; } else { Result = new byte[Width]; - System.Buffer.BlockCopy(BigEndianBytes, 0, Result, Width - BigEndianBytes.Length, BigEndianBytes.Length); + Buffer.BlockCopy(BigEndianBytes, 0, Result, Width - BigEndianBytes.Length, BigEndianBytes.Length); return Result; } } @@ -610,7 +607,7 @@ namespace WPinternals #endif } - if ((CommandLine.IsConsoleVisible) && ((Type == LogType.ConsoleOnly) || (Type == LogType.FileAndConsole))) + if (CommandLine.IsConsoleVisible && ((Type == LogType.ConsoleOnly) || (Type == LogType.FileAndConsole))) { Console.WriteLine(logMessage); } @@ -764,7 +761,7 @@ namespace WPinternals for (int i = 0; i < (HexString.Length >> 1); ++i) { - arr[i] = (byte)((GetHexVal(HexString[i << 1]) << 4) + (GetHexVal(HexString[(i << 1) + 1]))); + arr[i] = (byte)((GetHexVal(HexString[i << 1]) << 4) + GetHexVal(HexString[(i << 1) + 1])); } return arr; @@ -927,7 +924,7 @@ namespace WPinternals { if (proxy?.CheckAccess() == false) { - proxy.BeginInvoke(new Action(WeakEventHandlerManager.CallHandler), new object[] { sender, eventHandler }); + proxy.BeginInvoke(new Action(CallHandler), new object[] { sender, eventHandler }); } else { @@ -1133,12 +1130,12 @@ namespace WPinternals public bool CanExecute() { - return base.CanExecute(null); + return CanExecute(null); } public void Execute() { - base.Execute(null); + Execute(null); } } @@ -1809,8 +1806,8 @@ namespace WPinternals RT_ACCELERATOR = 9, RT_RCDATA = 10, RT_MESSAGETABLE = 11, - RT_GROUP_CURSOR = (RT_CURSOR + 11), - RT_GROUP_ICON = (RT_ICON + 11), + RT_GROUP_CURSOR = RT_CURSOR + 11, + RT_GROUP_ICON = RT_ICON + 11, RT_VERSION = 16, RT_DLGINCLUDE = 17, RT_PLUGPLAY = 19, @@ -1823,7 +1820,7 @@ namespace WPinternals RT_TOOLBAR = 241 }; - internal class PE + internal static class PE { internal static byte[] GetResource(byte[] PEfile, int[] Index) { @@ -1871,7 +1868,7 @@ namespace WPinternals if (ResourceID == (UInt32)Index[i]) { // Check high bit - if (((NextPointer & 0x80000000) == 0) != (i == (Index.Length - 1))) + if ((NextPointer & 0x80000000) == 0 != (i == (Index.Length - 1))) { throw new WPinternalsException("Bad resource path"); } @@ -1893,7 +1890,7 @@ namespace WPinternals internal static Version GetFileVersion(byte[] PEfile) { - byte[] version = PE.GetResource(PEfile, new int[] { (int)ResourceType.RT_VERSION, 1, 1033 }); + byte[] version = GetResource(PEfile, new int[] { (int)ResourceType.RT_VERSION, 1, 1033 }); // RT_VERSION format: // https://msdn.microsoft.com/en-us/library/windows/desktop/ms647001(v=vs.85).aspx @@ -1909,7 +1906,7 @@ namespace WPinternals internal static Version GetProductVersion(byte[] PEfile) { - byte[] version = PE.GetResource(PEfile, new int[] { (int)ResourceType.RT_VERSION, 1, 1033 }); + byte[] version = GetResource(PEfile, new int[] { (int)ResourceType.RT_VERSION, 1, 1033 }); // RT_VERSION format: // https://msdn.microsoft.com/en-us/library/windows/desktop/ms647001(v=vs.85).aspx @@ -2208,12 +2205,9 @@ namespace WPinternals return 1; } - if (Width.EndsWith("*")) + if (Width.EndsWith("*") && double.TryParse(Width[0..^1], out double perc)) { - if (double.TryParse(Width[0..^1], out double perc)) - { - return perc; - } + return perc; } return 1; } diff --git a/Models/ByteOperations.cs b/Models/ByteOperations.cs index 45d6f7b..a441a2a 100644 --- a/Models/ByteOperations.cs +++ b/Models/ByteOperations.cs @@ -48,7 +48,7 @@ namespace WPinternals Array.Clear(ByteArray, (int)Offset, (int)MaxBufferLength); } - byte[] TextBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(Text); + byte[] TextBytes = System.Text.Encoding.ASCII.GetBytes(Text); int WriteLength = TextBytes.Length; if (WriteLength > MaxBufferLength) { @@ -65,7 +65,7 @@ namespace WPinternals Array.Clear(ByteArray, (int)Offset, (int)MaxBufferLength); } - byte[] TextBytes = System.Text.UnicodeEncoding.Unicode.GetBytes(Text); + byte[] TextBytes = System.Text.Encoding.Unicode.GetBytes(Text); int WriteLength = TextBytes.Length; if (WriteLength > MaxBufferLength) { @@ -82,7 +82,7 @@ namespace WPinternals internal static void WriteUInt32(byte[] ByteArray, UInt32 Offset, UInt32 Value) { - System.Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 4); + Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 4); } internal static Int32 ReadInt32(byte[] ByteArray, UInt32 Offset) @@ -92,7 +92,7 @@ namespace WPinternals internal static void WriteInt32(byte[] ByteArray, UInt32 Offset, Int32 Value) { - System.Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 4); + Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 4); } internal static UInt16 ReadUInt16(byte[] ByteArray, UInt32 Offset) @@ -102,7 +102,7 @@ namespace WPinternals internal static void WriteUInt16(byte[] ByteArray, UInt32 Offset, UInt16 Value) { - System.Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 2); + Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 2); } internal static Int16 ReadInt16(byte[] ByteArray, UInt32 Offset) @@ -112,7 +112,7 @@ namespace WPinternals internal static void WriteInt16(byte[] ByteArray, UInt32 Offset, Int16 Value) { - System.Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 2); + Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 2); } internal static byte ReadUInt8(byte[] ByteArray, UInt32 Offset) @@ -132,7 +132,7 @@ namespace WPinternals internal static void WriteUInt24(byte[] ByteArray, UInt32 Offset, UInt32 Value) { - System.Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 3); + Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 3); } internal static UInt64 ReadUInt64(byte[] ByteArray, UInt32 Offset) @@ -142,7 +142,7 @@ namespace WPinternals internal static void WriteUInt64(byte[] ByteArray, UInt32 Offset, UInt64 Value) { - System.Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 8); + Buffer.BlockCopy(BitConverter.GetBytes(Value), 0, ByteArray, (int)Offset, 8); } internal static Guid ReadGuid(byte[] ByteArray, UInt32 Offset) @@ -241,12 +241,12 @@ namespace WPinternals internal static UInt32? FindAscii(byte[] SourceBuffer, string Pattern) { - return FindPattern(SourceBuffer, System.Text.ASCIIEncoding.ASCII.GetBytes(Pattern), null, null); + return FindPattern(SourceBuffer, System.Text.Encoding.ASCII.GetBytes(Pattern), null, null); } internal static UInt32? FindUnicode(byte[] SourceBuffer, string Pattern) { - return FindPattern(SourceBuffer, System.Text.UnicodeEncoding.Unicode.GetBytes(Pattern), null, null); + return FindPattern(SourceBuffer, System.Text.Encoding.Unicode.GetBytes(Pattern), null, null); } internal static UInt32? FindUint(byte[] SourceBuffer, UInt32 Pattern) @@ -296,7 +296,7 @@ namespace WPinternals if (OutPattern != null) { - System.Buffer.BlockCopy(SourceBuffer, (int)SearchPosition, OutPattern, 0, Pattern.Length); + Buffer.BlockCopy(SourceBuffer, (int)SearchPosition, OutPattern, 0, Pattern.Length); } break; @@ -394,11 +394,6 @@ namespace WPinternals } crc = (uint)(crc ^ (-1)); - if (crc < 0) - { - crc += (uint)4294967296; - } - return crc; } } diff --git a/Models/FFU.cs b/Models/FFU.cs index 0531f70..4305840 100644 --- a/Models/FFU.cs +++ b/Models/FFU.cs @@ -110,12 +110,9 @@ namespace WPinternals DiskAccessMethod = ByteOperations.ReadInt32(StoreHeader, (UInt32)(WriteDescriptorEntryOffset + 0x08 + (j * 0x08))); ChunkIndex = ByteOperations.ReadInt32(StoreHeader, (UInt32)(WriteDescriptorEntryOffset + 0x0C + (j * 0x08))); - if (DiskAccessMethod == 0) // 0 = From begin, 2 = From end. We ignore chunks at end of disk. These contain secondairy GPT. + if (DiskAccessMethod == 0 && (ChunkIndex + ChunkCount - 1) > HighestChunkIndex) // 0 = From begin, 2 = From end. We ignore chunks at end of disk. These contain secondairy GPT. { - if ((ChunkIndex + ChunkCount - 1) > HighestChunkIndex) - { - HighestChunkIndex = ChunkIndex + ChunkCount - 1; - } + HighestChunkIndex = ChunkIndex + ChunkCount - 1; } } WriteDescriptorEntryOffset += 8 + (LocationCount * 0x08); @@ -183,7 +180,7 @@ namespace WPinternals byte[] Signature = new byte[0x10]; FFUFile.Read(Signature, 0, 0x10); - Result = (ByteOperations.ReadAsciiString(Signature, 0x04, 0x0C) == "SignedImage "); + Result = ByteOperations.ReadAsciiString(Signature, 0x04, 0x0C) == "SignedImage "; FFUFile.Close(); @@ -214,12 +211,9 @@ namespace WPinternals { // https://social.msdn.microsoft.com/Forums/vstudio/en-US/2e67ca57-3556-4275-accd-58b7df30d424/unnecessary-filestreamseek-and-setting-filestreamposition-has-huge-effect-on-performance?forum=csharpgeneral - if (FFUFile != null) + if (FFUFile != null && FFUFile.Position != Position) { - if (FFUFile.Position != Position) - { - FFUFile.Seek(Position, SeekOrigin.Begin); - } + FFUFile.Seek(Position, SeekOrigin.Begin); } } @@ -239,7 +233,7 @@ namespace WPinternals { if ((Size % ChunkSize) > 0) { - return (UInt32)((Size / ChunkSize) * ChunkSize); + return (UInt32)(Size / ChunkSize * ChunkSize); } else { @@ -292,7 +286,7 @@ namespace WPinternals internal byte[] GetPartition(string Name) { - Partition Target = GPT.Partitions.Find(p => (string.Compare(p.Name, Name, true) == 0)); + Partition Target = GPT.Partitions.Find(p => string.Equals(p.Name, Name, StringComparison.CurrentCultureIgnoreCase)); if (Target == null) { throw new ArgumentOutOfRangeException(); @@ -318,7 +312,7 @@ namespace WPinternals private void WritePartition(string Name, string FilePath, Action ProgressUpdateCallback, ProgressUpdater UpdaterPerSector, bool Compress = false) { - Partition Target = GPT.Partitions.Find(p => (string.Compare(p.Name, Name, true) == 0)); + Partition Target = GPT.Partitions.Find(p => string.Equals(p.Name, Name, StringComparison.CurrentCultureIgnoreCase)); if (Target == null) { throw new ArgumentOutOfRangeException(); diff --git a/Models/GPT.cs b/Models/GPT.cs index b53ab92..ab04cf2 100644 --- a/Models/GPT.cs +++ b/Models/GPT.cs @@ -96,16 +96,16 @@ namespace WPinternals internal Partition GetPartition(string Name) { - return Partitions.Find(p => (string.Compare(p.Name, Name, true) == 0)); + return Partitions.Find(p => string.Equals(p.Name, Name, StringComparison.CurrentCultureIgnoreCase)); } // Magic! // SecureBoot hack for Bootloader Spec A starts here internal byte[] InsertHack() { - Partition HackPartition = Partitions.Find(p => (p.Name == "HACK")); - Partition SBL1 = Partitions.Find(p => (p.Name == "SBL1")); - Partition SBL2 = Partitions.Find(p => (p.Name == "SBL2")); + Partition HackPartition = Partitions.Find(p => p.Name == "HACK"); + Partition SBL1 = Partitions.Find(p => p.Name == "SBL1"); + Partition SBL2 = Partitions.Find(p => p.Name == "SBL2"); if ((SBL1 == null) || (SBL2 == null)) { @@ -140,9 +140,9 @@ namespace WPinternals internal byte[] RemoveHack() { - Partition HackPartition = Partitions.Find(p => (p.Name == "HACK")); - Partition SBL1 = Partitions.Find(p => (p.Name == "SBL1")); - Partition SBL2 = Partitions.Find(p => (p.Name == "SBL2")); + Partition HackPartition = Partitions.Find(p => p.Name == "HACK"); + Partition SBL1 = Partitions.Find(p => p.Name == "SBL1"); + Partition SBL2 = Partitions.Find(p => p.Name == "SBL2"); if ((SBL1 == null) || (SBL2 == null)) { @@ -227,7 +227,7 @@ namespace WPinternals { foreach (Partition NewPartition in GptToMerge.Partitions) { - ZipArchiveEntry Entry = Archive.Entries.FirstOrDefault(e => ((string.Compare(e.Name, NewPartition.Name, true) == 0) || (e.Name.StartsWith(NewPartition.Name + ".", true, System.Globalization.CultureInfo.GetCultureInfo("en-US"))))); + ZipArchiveEntry Entry = Archive.Entries.FirstOrDefault(e => string.Equals(e.Name, NewPartition.Name, StringComparison.CurrentCultureIgnoreCase) || e.Name.StartsWith(NewPartition.Name + ".", true, System.Globalization.CultureInfo.GetCultureInfo("en-US"))); if (Entry == null) { // There is a partition entry in the xml, but this partition is not present in the archive. @@ -342,7 +342,7 @@ namespace WPinternals Partition OldPartition = SortedPartitions.ElementAt(i); // Present in archive? - ZipArchiveEntry Entry = Archive.Entries.FirstOrDefault(e => ((string.Compare(e.Name, OldPartition.Name, true) == 0) || (e.Name.StartsWith(OldPartition.Name + ".", true, System.Globalization.CultureInfo.GetCultureInfo("en-US"))))); + ZipArchiveEntry Entry = Archive.Entries.FirstOrDefault(e => string.Equals(e.Name, OldPartition.Name, StringComparison.CurrentCultureIgnoreCase) || e.Name.StartsWith(OldPartition.Name + ".", true, System.Globalization.CultureInfo.GetCultureInfo("en-US"))); if (Entry != null) { // Not present in new GPT or present in GPT without FirstSector? @@ -378,7 +378,7 @@ namespace WPinternals foreach (Partition NewPartition in GptToMerge.Partitions) { // If the new partition is a dynamic partition, then skip it here. It will be added later. - if (DynamicPartitions.Select(p => p.Name).Any(n => string.Compare(n, NewPartition.Name, true) == 0)) + if (DynamicPartitions.Select(p => p.Name).Any(n => string.Equals(n, NewPartition.Name, StringComparison.CurrentCultureIgnoreCase))) { continue; } @@ -448,13 +448,10 @@ namespace WPinternals for (int i = this.Partitions.Count - 1; i >= 0; i--) { - if (this.Partitions[i] != CurrentPartition) + if (this.Partitions[i] != CurrentPartition && (CurrentPartition.FirstSector <= this.Partitions[i].LastSector) && (CurrentPartition.LastSector >= this.Partitions[i].FirstSector)) { - if ((CurrentPartition.FirstSector <= this.Partitions[i].LastSector) && (CurrentPartition.LastSector >= this.Partitions[i].FirstSector)) - { - this.Partitions.RemoveAt(i); - HasChanged = true; - } + this.Partitions.RemoveAt(i); + HasChanged = true; } } } @@ -465,7 +462,7 @@ namespace WPinternals // Check if the sizes of the partitions in the archive do not exceed the size of the partition, as listed in the GPT. foreach (Partition OldPartition in this.Partitions) { - ZipArchiveEntry Entry = Archive.Entries.FirstOrDefault(e => ((string.Compare(e.Name, OldPartition.Name, true) == 0) || (e.Name.StartsWith(OldPartition.Name + ".", true, System.Globalization.CultureInfo.GetCultureInfo("en-US"))))); + ZipArchiveEntry Entry = Archive.Entries.FirstOrDefault(e => string.Equals(e.Name, OldPartition.Name, StringComparison.CurrentCultureIgnoreCase) || e.Name.StartsWith(OldPartition.Name + ".", true, System.Globalization.CultureInfo.GetCultureInfo("en-US"))); if (Entry != null) { DecompressedStream DecompressedStream = new(Entry.Open()); @@ -517,7 +514,7 @@ namespace WPinternals NewPartition.FirstSector = FirstFreeSector; HasChanged = true; } - ZipArchiveEntry Entry = Archive.Entries.FirstOrDefault(e => ((string.Compare(e.Name, NewPartition.Name, true) == 0) || (e.Name.StartsWith(NewPartition.Name + ".", true, System.Globalization.CultureInfo.GetCultureInfo("en-US"))))); + ZipArchiveEntry Entry = Archive.Entries.FirstOrDefault(e => string.Equals(e.Name, NewPartition.Name, StringComparison.CurrentCultureIgnoreCase) || e.Name.StartsWith(NewPartition.Name + ".", true, System.Globalization.CultureInfo.GetCultureInfo("en-US"))); DecompressedStream DecompressedStream = new(Entry.Open()); ulong StreamLengthInSectors = (ulong)Entry.Length / 0x200; try diff --git a/Models/LZMA.cs b/Models/LZMA.cs index bf6423a..416b60c 100644 --- a/Models/LZMA.cs +++ b/Models/LZMA.cs @@ -246,15 +246,15 @@ namespace WPinternals BufferSize -= b.Length; Monitor.Pulse(BufferQueue); - BytesRead += (b.Length - BufferOffset); + BytesRead += b.Length - BufferOffset; BufferOffset = 0; } else { Array.Copy(b, BufferOffset, buffer, offset + BytesRead, count - BytesRead); - BufferOffset += (count - BytesRead); - BytesRead += (count - BytesRead); + BufferOffset += count - BytesRead; + BytesRead += count - BytesRead; } } else diff --git a/Models/MassStorage.cs b/Models/MassStorage.cs index 20c1206..d1d16f3 100644 --- a/Models/MassStorage.cs +++ b/Models/MassStorage.cs @@ -51,23 +51,23 @@ namespace WPinternals { foreach (ManagementObject drive in partition.GetRelated("Win32_DiskDrive")) { - if ((drive["PNPDeviceID"].ToString().Contains("VEN_QUALCOMM&PROD_MMC_STORAGE", StringComparison.CurrentCulture)) || - (drive["PNPDeviceID"].ToString().Contains("VEN_MSFT&PROD_PHONE_MMC_STOR", StringComparison.CurrentCulture))) + if (drive["PNPDeviceID"].ToString().Contains("VEN_QUALCOMM&PROD_MMC_STORAGE", StringComparison.CurrentCulture) || + drive["PNPDeviceID"].ToString().Contains("VEN_MSFT&PROD_PHONE_MMC_STOR", StringComparison.CurrentCulture)) { - Label = (logical["VolumeName"] == null ? "" : logical["VolumeName"].ToString()); - if ((Drive == null) || (string.Compare(Label, "MainOS", true) == 0)) // Always prefer the MainOS drive-mapping + Label = logical["VolumeName"] == null ? "" : logical["VolumeName"].ToString(); + if ((Drive == null) || string.Equals(Label, "MainOS", StringComparison.CurrentCultureIgnoreCase)) // Always prefer the MainOS drive-mapping { Drive = logical["Name"].ToString(); PhysicalDrive = drive["DeviceID"].ToString(); VolumeLabel = Label; } - if (string.Compare(Label, "MainOS", true) == 0) + if (string.Equals(Label, "MainOS", StringComparison.CurrentCultureIgnoreCase)) { break; } } } - if (string.Compare(Label, "MainOS", true) == 0) + if (string.Equals(Label, "MainOS", StringComparison.CurrentCultureIgnoreCase)) { break; } @@ -188,7 +188,7 @@ namespace WPinternals internal bool IsVolumeOpen() { - return (int)(hVolume) != -1; + return (int)hVolume != -1; } internal void CloseVolume() diff --git a/Models/NativeMethods.cs b/Models/NativeMethods.cs index d405b7e..7129ccb 100644 --- a/Models/NativeMethods.cs +++ b/Models/NativeMethods.cs @@ -212,12 +212,12 @@ namespace WPinternals internal const uint FILE_SHARE_DELETE = 0x00000004; internal const uint OPEN_EXISTING = 3; - internal const uint GENERIC_READ = (0x80000000); - internal const uint GENERIC_WRITE = (0x40000000); + internal const uint GENERIC_READ = 0x80000000; + internal const uint GENERIC_WRITE = 0x40000000; internal const uint FILE_FLAG_WRITE_THROUGH = 0x80000000; internal const uint FILE_FLAG_NO_BUFFERING = 0x20000000; - internal const uint FILE_READ_ATTRIBUTES = (0x0080); + internal const uint FILE_READ_ATTRIBUTES = 0x0080; internal const uint FILE_WRITE_ATTRIBUTES = 0x0100; internal const uint ERROR_INSUFFICIENT_BUFFER = 122; internal const uint FILE_BEGIN = 0; diff --git a/Models/NokiaFlashModel.cs b/Models/NokiaFlashModel.cs index 153e0d4..d58c947 100644 --- a/Models/NokiaFlashModel.cs +++ b/Models/NokiaFlashModel.cs @@ -33,6 +33,7 @@ namespace WPinternals ProtocolAsyncV3 = 16 } + [Flags] internal enum FlashOptions : byte { SkipWrite = 1, @@ -57,8 +58,8 @@ namespace WPinternals byte[] Request = new byte[0x0B]; const string Header = "NOKXFR"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Param), 0, Request, 7, Param.Length); + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Param), 0, Request, 7, Param.Length); byte[] Response = ExecuteRawMethod(Request); if ((Response == null) || (Response.Length < 0x10)) @@ -67,7 +68,7 @@ namespace WPinternals } byte[] Result = new byte[Response[0x10]]; - System.Buffer.BlockCopy(Response, 0x11, Result, 0, Response[0x10]); + Buffer.BlockCopy(Response, 0x11, Result, 0, Response[0x10]); return Result; } @@ -79,7 +80,7 @@ namespace WPinternals return null; } - return System.Text.ASCIIEncoding.ASCII.GetString(Bytes).Trim(new char[] { '\0' }); + return System.Text.Encoding.ASCII.GetString(Bytes).Trim(new char[] { '\0' }); } [Flags] @@ -195,12 +196,12 @@ namespace WPinternals byte[] AsskMask = new byte[0x10] { 1, 0, 16, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64 }; byte[] Request = new byte[0xAC]; const string Header = "NOKXFT"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); Request[7] = 1; - System.Buffer.BlockCopy(BigEndian.GetBytes(0x18, 4), 0, Request, 0x08, 4); // Subblocktype = 0x18 - System.Buffer.BlockCopy(BigEndian.GetBytes(0x9C, 4), 0, Request, 0x0C, 4); // Subblocklength = 0x9C - System.Buffer.BlockCopy(BigEndian.GetBytes(0x00, 4), 0, Request, 0x10, 4); // AsicIndex = 0x00 - System.Buffer.BlockCopy(AsskMask, 0, Request, 0x14, 0x10); + Buffer.BlockCopy(BigEndian.GetBytes(0x18, 4), 0, Request, 0x08, 4); // Subblocktype = 0x18 + Buffer.BlockCopy(BigEndian.GetBytes(0x9C, 4), 0, Request, 0x0C, 4); // Subblocklength = 0x9C + Buffer.BlockCopy(BigEndian.GetBytes(0x00, 4), 0, Request, 0x10, 4); // AsicIndex = 0x00 + Buffer.BlockCopy(AsskMask, 0, Request, 0x14, 0x10); byte[] TerminalResponse = ExecuteRawMethod(Request); if ((TerminalResponse?.Length > 0x20) && (BigEndian.ToUInt32(TerminalResponse, 0x14) == (TerminalResponse.Length - 0x18)) && (BitConverter.ToUInt32(TerminalResponse, 0x1C) == (TerminalResponse.Length - 0x20))) { @@ -219,14 +220,14 @@ namespace WPinternals byte[] Request = new byte[FfuHeader.Length + 0x20]; const string Header = "NOKXFS"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); - System.Buffer.BlockCopy(BigEndian.GetBytes(0x0001, 2), 0, Request, 0x06, 2); // Protocol version = 0x0001 + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(BigEndian.GetBytes(0x0001, 2), 0, Request, 0x06, 2); // Protocol version = 0x0001 Request[0x08] = 0; // Progress = 0% Request[0x0B] = 1; // Subblock count = 1 - System.Buffer.BlockCopy(BigEndian.GetBytes(0x0000000B, 4), 0, Request, 0x0C, 4); // Subblock type for header = 0x0B - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuHeader.Length + 0x0C, 4), 0, Request, 0x10, 4); // Subblock length = length of header + 0x0C - System.Buffer.BlockCopy(BigEndian.GetBytes(0x00000000, 4), 0, Request, 0x14, 4); // Header type = 0 - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuHeader.Length, 4), 0, Request, 0x18, 4); // Payload length = length of header + Buffer.BlockCopy(BigEndian.GetBytes(0x0000000B, 4), 0, Request, 0x0C, 4); // Subblock type for header = 0x0B + Buffer.BlockCopy(BigEndian.GetBytes(FfuHeader.Length + 0x0C, 4), 0, Request, 0x10, 4); // Subblock length = length of header + 0x0C + Buffer.BlockCopy(BigEndian.GetBytes(0x00000000, 4), 0, Request, 0x14, 4); // Header type = 0 + Buffer.BlockCopy(BigEndian.GetBytes(FfuHeader.Length, 4), 0, Request, 0x18, 4); // Payload length = length of header Request[0x1C] = Options; // Header options = 0 Buffer.BlockCopy(FfuHeader, 0, Request, 0x20, FfuHeader.Length); @@ -249,20 +250,20 @@ namespace WPinternals byte[] Request = new byte[FfuHeader.Length + 0x3C]; const string Header = "NOKXFS"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); - System.Buffer.BlockCopy(BigEndian.GetBytes((int)FfuProtocol.ProtocolSyncV2, 2), 0, Request, 0x06, 2); // Protocol version = 0x0001 + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(BigEndian.GetBytes((int)FfuProtocol.ProtocolSyncV2, 2), 0, Request, 0x06, 2); // Protocol version = 0x0001 Request[0x08] = 0; // Progress = 0% Request[0x0B] = 1; // Subblock count = 1 - System.Buffer.BlockCopy(BigEndian.GetBytes(0x00000021, 4), 0, Request, 0x0C, 4); // Subblock type for header v2 = 0x21 - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuHeader.Length + 0x28, 4), 0, Request, 0x10, 4); // Subblock starts at 0x14, payload starts at 0x3C. + Buffer.BlockCopy(BigEndian.GetBytes(0x00000021, 4), 0, Request, 0x0C, 4); // Subblock type for header v2 = 0x21 + Buffer.BlockCopy(BigEndian.GetBytes(FfuHeader.Length + 0x28, 4), 0, Request, 0x10, 4); // Subblock starts at 0x14, payload starts at 0x3C. - System.Buffer.BlockCopy(BigEndian.GetBytes(0x00000000, 4), 0, Request, 0x14, 4); // Header type = 0 - System.Buffer.BlockCopy(BigEndian.GetBytes(TotalHeaderLength, 4), 0, Request, 0x18, 4); // Payload length = length of header + Buffer.BlockCopy(BigEndian.GetBytes(0x00000000, 4), 0, Request, 0x14, 4); // Header type = 0 + Buffer.BlockCopy(BigEndian.GetBytes(TotalHeaderLength, 4), 0, Request, 0x18, 4); // Payload length = length of header Request[0x1C] = Options; // Header options = 0 - System.Buffer.BlockCopy(BigEndian.GetBytes(OffsetForThisPart, 4), 0, Request, 0x1D, 4); - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuHeader.Length, 4), 0, Request, 0x21, 4); + Buffer.BlockCopy(BigEndian.GetBytes(OffsetForThisPart, 4), 0, Request, 0x1D, 4); + Buffer.BlockCopy(BigEndian.GetBytes(FfuHeader.Length, 4), 0, Request, 0x21, 4); Request[0x25] = 0; // No Erase Buffer.BlockCopy(FfuHeader, 0, Request, 0x3C, FfuHeader.Length); @@ -290,15 +291,15 @@ namespace WPinternals byte[] Request = new byte[FfuChunk.Length + 0x1C]; const string Header = "NOKXFS"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); - System.Buffer.BlockCopy(BigEndian.GetBytes((int)FfuProtocol.ProtocolSyncV1, 2), 0, Request, 0x06, 2); // Protocol version = 0x0001 + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(BigEndian.GetBytes((int)FfuProtocol.ProtocolSyncV1, 2), 0, Request, 0x06, 2); // Protocol version = 0x0001 Request[0x08] = (byte)Progress; // Progress = 0% (0 - 100) Request[0x0B] = 1; // Subblock count = 1 - System.Buffer.BlockCopy(BigEndian.GetBytes(0x0000000C, 4), 0, Request, 0x0C, 4); // Subblock type for ChunkData = 0x0C - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length + 0x08, 4), 0, Request, 0x10, 4); // Subblock length = length of chunk + 0x08 + Buffer.BlockCopy(BigEndian.GetBytes(0x0000000C, 4), 0, Request, 0x0C, 4); // Subblock type for ChunkData = 0x0C + Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length + 0x08, 4), 0, Request, 0x10, 4); // Subblock length = length of chunk + 0x08 - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length, 4), 0, Request, 0x14, 4); // Payload length = length of chunk + Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length, 4), 0, Request, 0x14, 4); // Payload length = length of chunk Request[0x18] = Options; // Data options = 0 (1 = verify) Buffer.BlockCopy(FfuChunk, 0, Request, 0x1C, FfuChunk.Length); @@ -321,15 +322,15 @@ namespace WPinternals byte[] Request = new byte[FfuChunk.Length + 0x20]; const string Header = "NOKXFS"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); - System.Buffer.BlockCopy(BigEndian.GetBytes((int)FfuProtocol.ProtocolSyncV2, 2), 0, Request, 0x06, 2); // Protocol + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(BigEndian.GetBytes((int)FfuProtocol.ProtocolSyncV2, 2), 0, Request, 0x06, 2); // Protocol Request[0x08] = (byte)Progress; // Progress = 0% (0 - 100) Request[0x0B] = 1; // Subblock count = 1 - System.Buffer.BlockCopy(BigEndian.GetBytes(0x0000001B, 4), 0, Request, 0x0C, 4); // Subblock type for Payload v2 = 0x1B - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length + 0x0C, 4), 0, Request, 0x10, 4); // Subblock length = length of chunk + 0x08 + Buffer.BlockCopy(BigEndian.GetBytes(0x0000001B, 4), 0, Request, 0x0C, 4); // Subblock type for Payload v2 = 0x1B + Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length + 0x0C, 4), 0, Request, 0x10, 4); // Subblock length = length of chunk + 0x08 - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length, 4), 0, Request, 0x14, 4); // Payload length = length of chunk + Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length, 4), 0, Request, 0x14, 4); // Payload length = length of chunk Request[0x18] = Options; // Data options = 0 (1 = verify) Buffer.BlockCopy(FfuChunk, 0, Request, 0x20, FfuChunk.Length); @@ -352,18 +353,18 @@ namespace WPinternals byte[] Request = new byte[FfuChunk.Length + 0x20]; const string Header = "NOKXFS"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); - System.Buffer.BlockCopy(BigEndian.GetBytes((int)FfuProtocol.ProtocolAsyncV3, 2), 0, Request, 0x06, 2); // Protocol + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(BigEndian.GetBytes((int)FfuProtocol.ProtocolAsyncV3, 2), 0, Request, 0x06, 2); // Protocol Request[0x08] = (byte)Progress; // Progress = 0% (0 - 100) Request[0x0B] = 1; // Subblock count = 1 - System.Buffer.BlockCopy(BigEndian.GetBytes(0x0000001D, 4), 0, Request, 0x0C, 4); // Subblock type for Payload v2 = 0x1B - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length + 0x2C, 4), 0, Request, 0x10, 4); // Subblock length = length of chunk + 0x08 + Buffer.BlockCopy(BigEndian.GetBytes(0x0000001D, 4), 0, Request, 0x0C, 4); // Subblock type for Payload v2 = 0x1B + Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length + 0x2C, 4), 0, Request, 0x10, 4); // Subblock length = length of chunk + 0x08 - System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length, 4), 0, Request, 0x14, 4); // Payload length = length of chunk + Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length, 4), 0, Request, 0x14, 4); // Payload length = length of chunk Request[0x18] = Options; // Data options = 0 (1 = verify) - System.Buffer.BlockCopy(BigEndian.GetBytes(WriteDescriptorIndex, 4), 0, Request, 0x19, 4); // Payload length = length of chunk - System.Buffer.BlockCopy(BigEndian.GetBytes(CRC, 4), 0, Request, 0x1D, 4); // Payload length = length of chunk + Buffer.BlockCopy(BigEndian.GetBytes(WriteDescriptorIndex, 4), 0, Request, 0x19, 4); // Payload length = length of chunk + Buffer.BlockCopy(BigEndian.GetBytes(CRC, 4), 0, Request, 0x1D, 4); // Payload length = length of chunk Buffer.BlockCopy(FfuChunk, 0, Request, 0x40, FfuChunk.Length); @@ -387,11 +388,11 @@ namespace WPinternals { byte[] Request = new byte[84]; const string Header = "NOKXFB"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); Request[0x07] = 1; // Subblock count = 1 Request[0x08] = 6; // Subblock ID = 6 = Create Partition Backup to RAM - System.Buffer.BlockCopy(BigEndian.GetBytes(73, 2), 0, Request, 0x09, 2); // Subblock length = Length of data in subblock including fillers (subblock-ID-field and subblock-length-field are not counted for the subblock-length) - System.Text.UnicodeEncoding.Unicode.GetBytes(PartitionName); + Buffer.BlockCopy(BigEndian.GetBytes(73, 2), 0, Request, 0x09, 2); // Subblock length = Length of data in subblock including fillers (subblock-ID-field and subblock-length-field are not counted for the subblock-length) + System.Text.Encoding.Unicode.GetBytes(PartitionName); byte[] PartitionBytes = System.Text.Encoding.Unicode.GetBytes(PartitionName); Buffer.BlockCopy(PartitionBytes, 0, Request, 0x0C, PartitionBytes.Length); @@ -415,18 +416,18 @@ namespace WPinternals { byte[] Request = new byte[MmosPart.Length + 0x20]; const string Header = "NOKXFL"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); Request[0x07] = 1; // Subblock count = 1 - System.Buffer.BlockCopy(BigEndian.GetBytes(0x0000001E, 4), 0, Request, 0x08, 4); // Subblock ID = Load MMOS Binary = 0x1E - System.Buffer.BlockCopy(BigEndian.GetBytes(MmosPart.Length + 0x10, 4), 0, Request, 0x0C, 4); // Subblock length = Payload-length + 0x10 - System.Buffer.BlockCopy(BigEndian.GetBytes(TotalLength, 4), 0, Request, 0x10, 4); - System.Buffer.BlockCopy(BigEndian.GetBytes(Offset, 4), 0, Request, 0x14, 4); + Buffer.BlockCopy(BigEndian.GetBytes(0x0000001E, 4), 0, Request, 0x08, 4); // Subblock ID = Load MMOS Binary = 0x1E + Buffer.BlockCopy(BigEndian.GetBytes(MmosPart.Length + 0x10, 4), 0, Request, 0x0C, 4); // Subblock length = Payload-length + 0x10 + Buffer.BlockCopy(BigEndian.GetBytes(TotalLength, 4), 0, Request, 0x10, 4); + Buffer.BlockCopy(BigEndian.GetBytes(Offset, 4), 0, Request, 0x14, 4); if (SkipMmosSupportCheck) { Request[0x18] = 1; } - System.Buffer.BlockCopy(BigEndian.GetBytes(MmosPart.Length, 4), 0, Request, 0x1C, 4); + Buffer.BlockCopy(BigEndian.GetBytes(MmosPart.Length, 4), 0, Request, 0x1C, 4); Buffer.BlockCopy(MmosPart, 0, Request, 0x20, MmosPart.Length); byte[] Response = ExecuteRawMethod(Request); @@ -521,7 +522,7 @@ namespace WPinternals UInt64 CombinedFFUHeaderSize = FFU.HeaderSize; byte[] FfuHeader = new byte[CombinedFFUHeaderSize]; - using (FileStream FfuFile = new(FFU.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read)) + using (FileStream FfuFile = new(FFU.Path, FileMode.Open, FileAccess.Read)) { FfuFile.Read(FfuHeader, 0, (int)CombinedFFUHeaderSize); SendFfuHeaderV1(FfuHeader, Options); @@ -597,7 +598,7 @@ namespace WPinternals uint totalcounts = (uint)Math.Truncate((decimal)length / maximumbuffersize); - using (FileStream MMOSFile = new(MMOSPath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) + using (FileStream MMOSFile = new(MMOSPath, FileMode.Open, FileAccess.Read)) { for (int i = 1; i <= (uint)Math.Truncate((decimal)length / maximumbuffersize); i++) { @@ -633,10 +634,10 @@ namespace WPinternals byte[] Request = new byte[Data.Length + 0x40]; const string Header = "NOKF"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); Request[0x05] = 0; // Device type = 0 - System.Buffer.BlockCopy(BigEndian.GetBytes(StartSector, 4), 0, Request, 0x0B, 4); // Start sector - System.Buffer.BlockCopy(BigEndian.GetBytes(Data.Length / 0x200, 4), 0, Request, 0x0F, 4); // Sector count + Buffer.BlockCopy(BigEndian.GetBytes(StartSector, 4), 0, Request, 0x0B, 4); // Start sector + Buffer.BlockCopy(BigEndian.GetBytes(Data.Length / 0x200, 4), 0, Request, 0x0F, 4); // Sector count Request[0x13] = (byte)Progress; // Progress (0 - 100) Request[0x18] = 0; // Do Verify Request[0x19] = 0; // Is Test @@ -650,7 +651,7 @@ namespace WPinternals { byte[] Request = new byte[4]; const string Header = "NOKD"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); ExecuteRawMethod(Request); } @@ -658,7 +659,7 @@ namespace WPinternals { byte[] Request = new byte[4]; const string Header = "NOKZ"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); ExecuteRawMethod(Request); } @@ -690,7 +691,7 @@ namespace WPinternals PhoneInfo Info = ReadPhoneInfo(ExtendedInfo: false); FlashAppType OriginalAppType = Info.App; - bool Switch = ((Info.App != FlashAppType.BootManager) && Info.IsBootloaderSecure); + bool Switch = (Info.App != FlashAppType.BootManager) && Info.IsBootloaderSecure; if (Switch) { SwitchToBootManagerContext(); @@ -871,7 +872,7 @@ namespace WPinternals byte[] Request = new byte[0x50]; const string Header = "NOKXFP"; - System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); + Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); Request[0x06] = 1; // Protocol version must be 1 Request[0x07] = 0; // Device type = 0 @@ -950,7 +951,7 @@ namespace WPinternals Result.TransferSize = BigEndian.ToUInt32(Response, SubblockPayloadOffset); break; case 0x1F: - Result.MmosOverUsbSupported = (Response[SubblockPayloadOffset] == 1); + Result.MmosOverUsbSupported = Response[SubblockPayloadOffset] == 1; break; case 0x04: if (Result.App == FlashAppType.BootManager) @@ -975,17 +976,17 @@ namespace WPinternals Result.PlatformID = ByteOperations.ReadAsciiString(Response, (uint)SubblockPayloadOffset, SubblockLength).Trim(new char[] { ' ', '\0' }); break; case 0x0D: - Result.AsyncSupport = (Response[SubblockPayloadOffset + 1] == 1); + Result.AsyncSupport = Response[SubblockPayloadOffset + 1] == 1; break; case 0x0F: SubblockVersion = Response[SubblockPayloadOffset]; // 0x03 - Result.PlatformSecureBootEnabled = (Response[SubblockPayloadOffset + 0x01] == 0x01); - Result.SecureFfuEnabled = (Response[SubblockPayloadOffset + 0x02] == 0x01); - Result.JtagDisabled = (Response[SubblockPayloadOffset + 0x03] == 0x01); - Result.RdcPresent = (Response[SubblockPayloadOffset + 0x04] == 0x01); - Result.Authenticated = ((Response[SubblockPayloadOffset + 0x05] == 0x01) || (Response[SubblockPayloadOffset + 0x05] == 0x02)); - Result.UefiSecureBootEnabled = (Response[SubblockPayloadOffset + 0x06] == 0x01); - Result.SecondaryHardwareKeyPresent = (Response[SubblockPayloadOffset + 0x07] == 0x01); + Result.PlatformSecureBootEnabled = Response[SubblockPayloadOffset + 0x01] == 0x01; + Result.SecureFfuEnabled = Response[SubblockPayloadOffset + 0x02] == 0x01; + Result.JtagDisabled = Response[SubblockPayloadOffset + 0x03] == 0x01; + Result.RdcPresent = Response[SubblockPayloadOffset + 0x04] == 0x01; + Result.Authenticated = (Response[SubblockPayloadOffset + 0x05] == 0x01) || (Response[SubblockPayloadOffset + 0x05] == 0x02); + Result.UefiSecureBootEnabled = Response[SubblockPayloadOffset + 0x06] == 0x01; + Result.SecondaryHardwareKeyPresent = Response[SubblockPayloadOffset + 0x07] == 0x01; break; case 0x10: SubblockVersion = Response[SubblockPayloadOffset]; // 0x01 diff --git a/Models/NokiaPhoneModel.cs b/Models/NokiaPhoneModel.cs index a05c5da..ece07e3 100644 --- a/Models/NokiaPhoneModel.cs +++ b/Models/NokiaPhoneModel.cs @@ -76,7 +76,7 @@ namespace WPinternals Length = Device.InputPipe.Read(Buffer); } - JsonDocument ResultMessage = JsonDocument.Parse(System.Text.ASCIIEncoding.ASCII.GetString(Buffer, 0, Length)); + JsonDocument ResultMessage = JsonDocument.Parse(System.Text.Encoding.ASCII.GetString(Buffer, 0, Length)); try { @@ -298,7 +298,7 @@ namespace WPinternals { Length = Device.InputPipe.EndRead(AsyncResultRead); - JsonDocument ResultMessage = JsonDocument.Parse(System.Text.ASCIIEncoding.ASCII.GetString(Buffer, 0, Length)); + JsonDocument ResultMessage = JsonDocument.Parse(System.Text.Encoding.ASCII.GetString(Buffer, 0, Length)); JsonElement? ResultToken = ResultMessage.RootElement.GetProperty("result"); if ((ResultToken == null) || (ResultElement == null)) diff --git a/Models/PatchEngine.cs b/Models/PatchEngine.cs index d764594..407a995 100644 --- a/Models/PatchEngine.cs +++ b/Models/PatchEngine.cs @@ -120,7 +120,7 @@ namespace WPinternals LogFile.Log("Attempt patch: " + PatchDefinition); // Find a matching TargetVersion - PatchDefinition Definition = PatchDefinitions.Single(d => string.Compare(d.Name, PatchDefinition, true) == 0); + PatchDefinition Definition = PatchDefinitions.Single(d => string.Equals(d.Name, PatchDefinition, StringComparison.CurrentCultureIgnoreCase)); TargetVersion MatchedVersion = null; int VersionIndex = 0; foreach (TargetVersion CurrentVersion in Definition.TargetVersions) @@ -146,7 +146,7 @@ namespace WPinternals } // Lookup file - FilePatcher CurrentFile = LoadedFiles.SingleOrDefault(f => string.Compare(f.FilePath, TargetPath, true) == 0); + FilePatcher CurrentFile = LoadedFiles.SingleOrDefault(f => string.Equals(f.FilePath, TargetPath, StringComparison.CurrentCultureIgnoreCase)); if (CurrentFile == null) { CurrentFile = (TargetImage != null) && (!TargetPath.Contains(':')) @@ -196,7 +196,7 @@ namespace WPinternals foreach (TargetFile CurrentTargetFile in MatchedVersion.TargetFiles) { - FilePatcher CurrentFile = LoadedFiles.SingleOrDefault(f => string.Compare(f.FilePath, Path.Combine(TargetPath + "\\", CurrentTargetFile.Path), true) == 0); + FilePatcher CurrentFile = LoadedFiles.SingleOrDefault(f => string.Equals(f.FilePath, Path.Combine(TargetPath + "\\", CurrentTargetFile.Path), StringComparison.CurrentCultureIgnoreCase)); if (!StructuralComparisons.StructuralEqualityComparer.Equals(CurrentFile.Hash, CurrentTargetFile.HashPatched)) { @@ -242,7 +242,7 @@ namespace WPinternals try { // Find a matching TargetVersion - PatchDefinition Definition = PatchDefinitions.Single(d => string.Compare(d.Name, PatchDefinition, true) == 0); + PatchDefinition Definition = PatchDefinitions.Single(d => string.Equals(d.Name, PatchDefinition, StringComparison.CurrentCultureIgnoreCase)); TargetVersion MatchedVersion = null; foreach (TargetVersion CurrentVersion in Definition.TargetVersions) { @@ -266,7 +266,7 @@ namespace WPinternals } // Lookup file - FilePatcher CurrentFile = LoadedFiles.SingleOrDefault(f => string.Compare(f.FilePath, TargetPath, true) == 0); + FilePatcher CurrentFile = LoadedFiles.SingleOrDefault(f => string.Equals(f.FilePath, TargetPath, StringComparison.CurrentCultureIgnoreCase)); if (CurrentFile == null) { CurrentFile = new FilePatcher(TargetPath); @@ -306,7 +306,7 @@ namespace WPinternals { foreach (TargetFile CurrentTargetFile in MatchedVersion.TargetFiles) { - FilePatcher CurrentFile = LoadedFiles.SingleOrDefault(f => string.Compare(f.FilePath, Path.Combine(TargetPath, CurrentTargetFile.Path), true) == 0); + FilePatcher CurrentFile = LoadedFiles.SingleOrDefault(f => string.Equals(f.FilePath, Path.Combine(TargetPath, CurrentTargetFile.Path), StringComparison.CurrentCultureIgnoreCase)); if (!StructuralComparisons.StructuralEqualityComparer.Equals(CurrentFile.Hash, CurrentTargetFile.HashOriginal)) { diff --git a/Models/Privileges.cs b/Models/Privileges.cs index 1a1e125..3adc218 100644 --- a/Models/Privileges.cs +++ b/Models/Privileges.cs @@ -186,16 +186,13 @@ namespace WPinternals { lock (syncRoot) { - if (processHandle.IsInvalid) - { - if (!NativeMethods.OpenProcessToken( + if (processHandle.IsInvalid && !NativeMethods.OpenProcessToken( NativeMethods.GetCurrentProcess(), TokenAccessLevels.Duplicate, ref processHandle)) - { - cachingError = Marshal.GetLastWin32Error(); - success = false; - } + { + cachingError = Marshal.GetLastWin32Error(); + success = false; } } } @@ -237,15 +234,12 @@ namespace WPinternals } } - if (success) - { - if (!NativeMethods.SetThreadToken( + if (success && !NativeMethods.SetThreadToken( IntPtr.Zero, this.threadHandle)) - { - error = Marshal.GetLastWin32Error(); - success = false; - } + { + error = Marshal.GetLastWin32Error(); + success = false; } if (success) @@ -424,7 +418,7 @@ namespace WPinternals NativeMethods.TOKEN_PRIVILEGE newState = new(); newState.PrivilegeCount = 1; newState.Privilege.Luid = this.luid; - newState.Privilege.Attributes = (this.initialState ? NativeMethods.SE_PRIVILEGE_ENABLED : NativeMethods.SE_PRIVILEGE_DISABLED); + newState.Privilege.Attributes = this.initialState ? NativeMethods.SE_PRIVILEGE_ENABLED : NativeMethods.SE_PRIVILEGE_DISABLED; NativeMethods.TOKEN_PRIVILEGE previousState = new(); uint previousSize = 0; @@ -578,11 +572,11 @@ namespace WPinternals { // This is the initial state that revert will have to go back to - this.initialState = ((previousState.Privilege.Attributes & NativeMethods.SE_PRIVILEGE_ENABLED) != 0); + this.initialState = (previousState.Privilege.Attributes & NativeMethods.SE_PRIVILEGE_ENABLED) != 0; // Remember whether state has changed at all - this.stateWasChanged = (this.initialState != enable); + this.stateWasChanged = this.initialState != enable; // If we had to impersonate, or if the privilege state changed we'll need to revert @@ -630,13 +624,10 @@ namespace WPinternals this.initialState = false; this.needToRevert = false; - if (this.tlsContents != null) + if (this.tlsContents?.DecrementReferenceCount() == 0) { - if (this.tlsContents.DecrementReferenceCount() == 0) - { - this.tlsContents = null; - Thread.SetData(tlsSlot, null); - } + this.tlsContents = null; + Thread.SetData(tlsSlot, null); } } } diff --git a/Models/QualcommDownload.cs b/Models/QualcommDownload.cs index faf712a..86e78d5 100644 --- a/Models/QualcommDownload.cs +++ b/Models/QualcommDownload.cs @@ -60,7 +60,7 @@ namespace WPinternals CurrentLength = Remaining >= 0x100 ? 0x100 : (UInt32)Remaining; - CurrentLength = (UInt32)(Data.Read(Buffer, 7, (int)CurrentLength)); + CurrentLength = (UInt32)Data.Read(Buffer, 7, (int)CurrentLength); Serial.SendCommand(Buffer, new byte[] { 0x02 }); CurrentAddress += CurrentLength; diff --git a/Models/QualcommLoader.cs b/Models/QualcommLoader.cs index 0e25832..c73af49 100644 --- a/Models/QualcommLoader.cs +++ b/Models/QualcommLoader.cs @@ -55,7 +55,7 @@ namespace WPinternals // We expect the user to know what he is doing in such case and we will ignore checks if (!StructuralComparisons.StructuralEqualityComparer.Equals(RootKeyHash, new byte[RootKeyHash.Length])) { - if ((StructuralComparisons.StructuralEqualityComparer.Equals(Loader.RootKeyHash, RootKeyHash)) + if (StructuralComparisons.StructuralEqualityComparer.Equals(Loader.RootKeyHash, RootKeyHash) && (ByteOperations.FindUnicode(Loader.Binary, "QHSUSB_ARMPRG") != null)) // To detect that this is a loader, and not SBL1 or something. V1 loaders are QHSUSB_ARMPRG. V2 loaders are QHSUSB__BULK. Only V1 supported for now, because V2 only accepts signed payload. { Result.Add(Loader); diff --git a/Models/QualcommSahara.cs b/Models/QualcommSahara.cs index 9f1f0c3..71396e2 100644 --- a/Models/QualcommSahara.cs +++ b/Models/QualcommSahara.cs @@ -19,6 +19,11 @@ // DEALINGS IN THE SOFTWARE. using System; +using System.Collections; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; using System.Threading.Tasks; namespace WPinternals @@ -90,7 +95,7 @@ namespace WPinternals Serial.SendData(HelloResponse); Step = 3; - using System.IO.FileStream FileStream = new(Path, System.IO.FileMode.Open, System.IO.FileAccess.Read); + using FileStream FileStream = new(Path, FileMode.Open, FileAccess.Read); while (true) { Step = 4; @@ -116,7 +121,7 @@ namespace WPinternals if (FileStream.Position != Offset) { - FileStream.Seek(Offset, System.IO.SeekOrigin.Begin); + FileStream.Seek(Offset, SeekOrigin.Begin); } Step = 6; @@ -182,7 +187,7 @@ namespace WPinternals Serial.SendCommand(new byte[] { 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00 }, new byte[] { 0x08, 0x00, 0x00, 0x00 }); } - public bool ConnectToProgrammerInTestMode() + public bool ConnectToProgrammer(byte[] PacketFromPcToProgrammer) { // Behaviour of old firehose: // Takes about 20 ms to be started. @@ -198,12 +203,6 @@ namespace WPinternals // When sending succeeds, an answer should be incoming immediately to complete the handshake. // When an incoming Hello was received, the phone still expects to receive another Hello. - byte[] HelloPacketFromPcToProgrammer = new byte[0x20C]; - ByteOperations.WriteUInt32(HelloPacketFromPcToProgrammer, 0, 0x57503730); - ByteOperations.WriteUInt32(HelloPacketFromPcToProgrammer, 0x28, 0x57503730); - ByteOperations.WriteUInt32(HelloPacketFromPcToProgrammer, 0x208, 0x57503730); - ByteOperations.WriteUInt16(HelloPacketFromPcToProgrammer, 0x48, 0x4445); - int HelloSendCount = 0; bool HandshakeCompleted = false; string Incoming; @@ -214,7 +213,7 @@ namespace WPinternals try { LogFile.Log("Send Hello to programmer (" + HelloSendCount.ToString() + ")", LogType.FileOnly); - Serial.SendData(HelloPacketFromPcToProgrammer); + Serial.SendData(PacketFromPcToProgrammer); LogFile.Log("Hello packet accepted", LogType.FileOnly); } catch @@ -225,29 +224,50 @@ namespace WPinternals try { Serial.SetTimeOut(500); - Incoming = System.Text.Encoding.ASCII.GetString(Serial.GetResponse(null)); + Incoming = Encoding.ASCII.GetString(Serial.GetResponse(null)); LogFile.Log("In: " + Incoming, LogType.FileOnly); Serial.SetTimeOut(200); if (Incoming.Contains("Chip serial num")) { - Incoming = System.Text.Encoding.ASCII.GetString(Serial.GetResponse(null)); + Incoming = Encoding.ASCII.GetString(Serial.GetResponse(null)); LogFile.Log("In: " + Incoming, LogType.FileOnly); LogFile.Log("Incoming Hello-packets received", LogType.FileOnly); } while (Incoming.IndexOf("response value") < 0) { - Incoming = System.Text.Encoding.ASCII.GetString(Serial.GetResponse(null)); + Incoming = Encoding.ASCII.GetString(Serial.GetResponse(null)); LogFile.Log("In: " + Incoming, LogType.FileOnly); } LogFile.Log("Incoming Hello-response received", LogType.FileOnly); - HandshakeCompleted = true; + + if (!Incoming.Contains("Failed to authenticate Digital Signature.")) + { + HandshakeCompleted = true; + } + else + { + LogFile.Log("Programmer failed to authenticate Digital Signature", LogType.FileOnly); + } } catch { } } while (!HandshakeCompleted && (HelloSendCount < 6)); + return HandshakeCompleted; + } + + public bool ConnectToProgrammerInTestMode() + { + byte[] HelloPacketFromPcToProgrammer = new byte[0x20C]; + ByteOperations.WriteUInt32(HelloPacketFromPcToProgrammer, 0, 0x57503730); + ByteOperations.WriteUInt32(HelloPacketFromPcToProgrammer, 0x28, 0x57503730); + ByteOperations.WriteUInt32(HelloPacketFromPcToProgrammer, 0x208, 0x57503730); + ByteOperations.WriteUInt16(HelloPacketFromPcToProgrammer, 0x48, 0x4445); + + bool HandshakeCompleted = ConnectToProgrammer(HelloPacketFromPcToProgrammer); + if (HandshakeCompleted) { LogFile.Log("Handshake completed with programmer in testmode", LogType.FileOnly); @@ -279,12 +299,12 @@ namespace WPinternals LogFile.Log("Rebooting phone", LogType.FileAndConsole); const string Command03 = ""; LogFile.Log("Out: " + Command03, LogType.FileOnly); - Serial.SendData(System.Text.Encoding.ASCII.GetBytes(Command03)); + Serial.SendData(Encoding.ASCII.GetBytes(Command03)); string Incoming; do { - Incoming = System.Text.Encoding.ASCII.GetString(Serial.GetResponse(null)); + Incoming = Encoding.ASCII.GetString(Serial.GetResponse(null)); LogFile.Log("In: " + Incoming, LogType.FileOnly); } while (Incoming.IndexOf("response value") < 0); @@ -343,5 +363,238 @@ namespace WPinternals } LogFile.Log("Programmer being launched on phone", LogType.FileOnly); } + + public async Task SendEdPayload(string ProgrammerPath, string PayloadPath) + { + // First, let's read the Emergency Download payload header and verify its validity + FileStream PayloadStream = File.OpenRead(PayloadPath); + + byte[] ValidReferencePayloadHeader = new byte[] { 0x45, 0x6D, 0x65, 0x72, 0x67, 0x65, 0x6E, 0x63, 0x79, 0x20, 0x50, 0x61, 0x79, 0x6C, 0x6F, 0x61, 0x64 }; + + byte[] PayloadHeader = new byte[17]; + PayloadStream.Read(PayloadHeader, 0, 17); + + bool IsValidEdPayloadImage = StructuralComparisons.StructuralEqualityComparer.Equals(PayloadHeader, ValidReferencePayloadHeader); + if (!IsValidEdPayloadImage) + { + return false; + } + + // Now let's read the information block + PayloadStream.Seek(0x64, SeekOrigin.Begin); + byte[] PayloadInformationBlock = new byte[0x64]; + + PayloadStream.Read(PayloadInformationBlock, 0, 0x64); + string buildtime = Encoding.ASCII.GetString(PayloadInformationBlock).Trim('\0'); + + PayloadStream.Read(PayloadInformationBlock, 0, 0x64); + string builddate = Encoding.ASCII.GetString(PayloadInformationBlock).Trim('\0'); + + PayloadStream.Read(PayloadInformationBlock, 0, 0x64); + string version = Encoding.ASCII.GetString(PayloadInformationBlock).Trim('\0'); + + PayloadInformationBlock = new byte[0x670]; + PayloadStream.Read(PayloadInformationBlock, 0, 0x670); + string Info = Encoding.ASCII.GetString(PayloadInformationBlock).Trim('\0'); + + // Print some information about the payload + LogFile.Log("Emerency flasher version 0.1", LogType.FileAndConsole); + LogFile.Log("Programmer information:", LogType.FileAndConsole); + LogFile.Log("Build time: " + buildtime, LogType.FileAndConsole); + LogFile.Log("Build date: " + builddate, LogType.FileAndConsole); + LogFile.Log("Version: " + version, LogType.FileAndConsole); + LogFile.Log("Info: " + Info, LogType.FileAndConsole); + + // Send the emergency programmer to the phone + bool SendImageResult = await Task.Run(() => SendImage(ProgrammerPath)); + if (!SendImageResult) + { + return false; + } + + // Start the emergency programmer on the phone + await Task.Run(() => StartProgrammer()); + + // Wait a few seconds before sending commands + LogFile.Log("Waiting...", LogType.FileAndConsole); + Thread.Sleep(2000); + LogFile.Log("Waiting...OK", LogType.FileAndConsole); + + bool Terminated = false; + bool Connected = false; + bool ProgrammerRawMode = false; + + string Incoming; + + while (!Terminated) + { + PayloadInformationBlock = new byte[0x200]; + PayloadStream.Read(PayloadInformationBlock, 0, 0x200); + string ProgrammerCommand = Encoding.ASCII.GetString(PayloadInformationBlock.Skip(0xC).ToArray()).Trim('\0'); + + LogFile.Log(ProgrammerCommand, LogType.FileAndConsole); + + byte[] PacketFromPcToProgrammer = Array.Empty(); + byte[] temp = new byte[0x200]; + + while (true) + { + if (PayloadStream.Position == PayloadStream.Length) + { + Terminated = true; + break; + } + + PayloadStream.Read(temp, 0, 0x200); + + if (temp[12] == 77 && temp[13] == 83 && temp[14] == 71 && temp[15] == 95) + { + PayloadStream.Seek(-0x200, SeekOrigin.Current); + break; + } + + PacketFromPcToProgrammer = PacketFromPcToProgrammer.Concat(temp).ToArray(); + } + + bool ExpectingReplyFromProgrammer = false; + + if (ProgrammerCommand.Contains("XML")) + { + string Outgoing = Encoding.ASCII.GetString(PacketFromPcToProgrammer).Trim('\0'); + PacketFromPcToProgrammer = Encoding.ASCII.GetBytes(Outgoing); + LogFile.Log("Out: " + Outgoing, LogType.FileAndConsole); + } + + if (!ProgrammerCommand.Contains("RAW_DATA") && !ProgrammerRawMode) + { + ExpectingReplyFromProgrammer = true; + } + + if (ProgrammerCommand.Contains("LAST") && ProgrammerRawMode) + { + ExpectingReplyFromProgrammer = true; + } + + if (ProgrammerCommand.Contains("DATA_ALL") && ProgrammerRawMode) + { + ExpectingReplyFromProgrammer = true; + } + + if (ProgrammerCommand.Contains("RAW_DATA") && !ProgrammerRawMode) + { + LogFile.Log("Phone is not in raw mode ON, leaving...", LogType.FileAndConsole); + + // Workaround for problem + // SerialPort is sometimes not disposed correctly when the device is already removed. + // So explicitly dispose here + Serial.Close(); + + LogFile.Log("Phone has been emergency flashed unsuccessfully!", LogType.FileAndConsole); + PayloadStream.Dispose(); + + return false; + } + + if (!ProgrammerCommand.Contains("RAW_DATA") && ProgrammerRawMode) + { + LogFile.Log("Phone is not in raw mode ON, leaving...", LogType.FileAndConsole); + + // Workaround for problem + // SerialPort is sometimes not disposed correctly when the device is already removed. + // So explicitly dispose here + Serial.Close(); + + LogFile.Log("Phone has been emergency flashed unsuccessfully!", LogType.FileAndConsole); + PayloadStream.Dispose(); + + return false; + } + + if (Connected) + { + Serial.SendData(PacketFromPcToProgrammer); + } + + if (ExpectingReplyFromProgrammer) + { + if (!Connected) + { + Connected = ConnectToProgrammer(PacketFromPcToProgrammer); + + if (Connected) + { + LogFile.Log("Handshake completed with programmer in validated image programming (VIP) mode", LogType.FileAndConsole); + } + else + { + LogFile.Log("Handshake with programmer failed", LogType.FileAndConsole); + } + + if (!Connected) + { + LogFile.Log("Phone programmer is now ignoring us, leaving...", LogType.FileAndConsole); + + // Workaround for problem + // SerialPort is sometimes not disposed correctly when the device is already removed. + // So explicitly dispose here + Serial.Close(); + + LogFile.Log("Phone has been emergency flashed unsuccessfully!", LogType.FileAndConsole); + PayloadStream.Dispose(); + + return false; + } + } + else + { + do + { + Serial.SetTimeOut(500); + Incoming = Encoding.ASCII.GetString(Serial.GetResponse(null)); + Serial.SetTimeOut(200); + LogFile.Log("In: " + Incoming, LogType.FileAndConsole); + } + while (Incoming.IndexOf("response value") < 0); + + if (Incoming.Contains("rawmode=\"false\"")) + { + ProgrammerRawMode = false; + LogFile.Log("Raw mode: OFF", LogType.FileAndConsole); + } + + if (Incoming.Contains("rawmode=\"true\"")) + { + ProgrammerRawMode = true; + LogFile.Log("Raw mode: ON", LogType.FileAndConsole); + } + + if (!Incoming.Contains("ACK")) + { + LogFile.Log("Phone programmer is now ignoring us, leaving...", LogType.FileAndConsole); + + // Workaround for problem + // SerialPort is sometimes not disposed correctly when the device is already removed. + // So explicitly dispose here + Serial.Close(); + + LogFile.Log("Phone has been emergency flashed unsuccessfully!", LogType.FileAndConsole); + PayloadStream.Dispose(); + + return false; + } + } + } + } + + // Workaround for problem + // SerialPort is sometimes not disposed correctly when the device is already removed. + // So explicitly dispose here + Serial.Close(); + + LogFile.Log("Phone has been emergency flashed successfully!", LogType.FileAndConsole); + PayloadStream.Dispose(); + + return true; + } } } diff --git a/Models/QualcommSerial.cs b/Models/QualcommSerial.cs index 9a75eb0..a81c1c4 100644 --- a/Models/QualcommSerial.cs +++ b/Models/QualcommSerial.cs @@ -39,7 +39,7 @@ namespace WPinternals CRC16 = new CRC16(0x1189, 0xFFFF, 0xFFFF); string[] DevicePathElements = DevicePath.Split(new char[] { '#' }); - if (string.Compare(DevicePathElements[3], "{86E0D1E0-8089-11D0-9CE4-08003E301F73}", true) == 0) + if (string.Equals(DevicePathElements[3], "{86E0D1E0-8089-11D0-9CE4-08003E301F73}", StringComparison.CurrentCultureIgnoreCase)) { string PortName = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\" + DevicePathElements[1] + @"\" + DevicePathElements[2] + @"\Device Parameters", "PortName", null); if (PortName != null) @@ -316,9 +316,9 @@ namespace WPinternals } } - public class IncompleteMessageException : Exception { }; - public class BadMessageException : Exception { }; - public class BadConnectionException : Exception { }; + public class IncompleteMessageException : Exception { public IncompleteMessageException() { } public IncompleteMessageException(string message) : base(message) { } public IncompleteMessageException(string message, Exception innerException) : base(message, innerException) { } } + public class BadMessageException : Exception { public BadMessageException() { } public BadMessageException(string message) : base(message) { } public BadMessageException(string message, Exception innerException) : base(message, innerException) { } } + public class BadConnectionException : Exception { public BadConnectionException() { } public BadConnectionException(string message) : base(message) { } public BadConnectionException(string message, Exception innerException) : base(message, innerException) { } } public class CRC16 { diff --git a/Models/UEFI.cs b/Models/UEFI.cs index d01d8cb..1b05a70 100644 --- a/Models/UEFI.cs +++ b/Models/UEFI.cs @@ -237,7 +237,7 @@ namespace WPinternals Type = ByteOperations.ReadUInt8(DecompressedImage, DecompressedFileHeaderOffset + 0x12) }; byte[] FileGuidBytes = new byte[0x10]; - System.Buffer.BlockCopy(DecompressedImage, (int)DecompressedFileHeaderOffset + 0x00, FileGuidBytes, 0, 0x10); + Buffer.BlockCopy(DecompressedImage, (int)DecompressedFileHeaderOffset + 0x00, FileGuidBytes, 0, 0x10); CurrentEFI.Guid = new Guid(FileGuidBytes); // Parse sections of the EFI @@ -286,7 +286,7 @@ namespace WPinternals internal byte[] GetFile(string Name) { - EFI File = EFIs.Find(f => (string.Compare(Name, f.Name, true) == 0) || (string.Compare(Name, f.Guid.ToString(), true) == 0)); + EFI File = EFIs.Find(f => string.Equals(Name, f.Name, StringComparison.CurrentCultureIgnoreCase) || string.Equals(Name, f.Guid.ToString(), StringComparison.CurrentCultureIgnoreCase)); if (File == null) { return null; @@ -300,7 +300,7 @@ namespace WPinternals internal byte[] GetFile(Guid Guid) { - EFI File = EFIs.Find(f => (Guid == f.Guid)); + EFI File = EFIs.Find(f => Guid == f.Guid); if (File == null) { return null; @@ -314,7 +314,7 @@ namespace WPinternals internal void ReplaceFile(string Name, byte[] Binary) { - EFI File = EFIs.Find(f => (string.Compare(Name, f.Name, true) == 0) || (string.Compare(Name, f.Guid.ToString(), true) == 0)); + EFI File = EFIs.Find(f => string.Equals(Name, f.Name, StringComparison.CurrentCultureIgnoreCase) || string.Equals(Name, f.Guid.ToString(), StringComparison.CurrentCultureIgnoreCase)); if (File == null) { throw new ArgumentOutOfRangeException(); @@ -515,7 +515,7 @@ namespace WPinternals { UInt16 VolumeHeaderSize = ByteOperations.ReadUInt16(Image, Offset + 0x30); byte[] Header = new byte[VolumeHeaderSize]; - System.Buffer.BlockCopy(Image, (int)Offset, Header, 0, VolumeHeaderSize); + Buffer.BlockCopy(Image, (int)Offset, Header, 0, VolumeHeaderSize); ByteOperations.WriteUInt16(Header, 0x32, 0); // Clear checksum UInt16 CurrentChecksum = ByteOperations.ReadUInt16(Image, Offset + 0x32); UInt16 NewChecksum = ByteOperations.CalculateChecksum16(Header, 0, VolumeHeaderSize); @@ -553,7 +553,7 @@ namespace WPinternals UInt32 FileSize = ByteOperations.ReadUInt24(Image, Offset + 0x14); byte[] Header = new byte[FileHeaderSize - 1]; - System.Buffer.BlockCopy(Image, (int)Offset, Header, 0, FileHeaderSize - 1); + Buffer.BlockCopy(Image, (int)Offset, Header, 0, FileHeaderSize - 1); ByteOperations.WriteUInt16(Header, 0x10, 0); // Clear checksum byte CurrentHeaderChecksum = ByteOperations.ReadUInt8(Image, Offset + 0x10); byte CalculatedHeaderChecksum = ByteOperations.CalculateChecksum8(Header, 0, (UInt32)FileHeaderSize - 1); diff --git a/ViewModels/BackupTargetSelectionViewModel.cs b/ViewModels/BackupTargetSelectionViewModel.cs index 198baa3..80842d1 100644 --- a/ViewModels/BackupTargetSelectionViewModel.cs +++ b/ViewModels/BackupTargetSelectionViewModel.cs @@ -187,7 +187,7 @@ namespace WPinternals { get { - return _BackupArchiveCommand ??= new DelegateCommand(() => BackupArchiveCallback(ArchivePath), () => ((ArchivePath != null) && (PhoneNotifier.CurrentInterface != null))); + return _BackupArchiveCommand ??= new DelegateCommand(() => BackupArchiveCallback(ArchivePath), () => (ArchivePath != null) && (PhoneNotifier.CurrentInterface != null)); } } @@ -196,7 +196,7 @@ namespace WPinternals { get { - return _BackupCommand ??= new DelegateCommand(() => BackupCallback(EFIESPPath, MainOSPath, DataPath), () => (((EFIESPPath != null) || (MainOSPath != null) || (DataPath != null)) && (PhoneNotifier.CurrentInterface != null))); + return _BackupCommand ??= new DelegateCommand(() => BackupCallback(EFIESPPath, MainOSPath, DataPath), () => ((EFIESPPath != null) || (MainOSPath != null) || (DataPath != null)) && (PhoneNotifier.CurrentInterface != null)); } } @@ -205,7 +205,7 @@ namespace WPinternals { get { - return _BackupArchiveProvisioningCommand ??= new DelegateCommand(() => BackupArchiveProvisioningCallback(ArchiveProvisioningPath), () => ((ArchiveProvisioningPath != null) && (PhoneNotifier.CurrentInterface != null))); + return _BackupArchiveProvisioningCommand ??= new DelegateCommand(() => BackupArchiveProvisioningCallback(ArchiveProvisioningPath), () => (ArchiveProvisioningPath != null) && (PhoneNotifier.CurrentInterface != null)); } } @@ -228,7 +228,7 @@ namespace WPinternals { IsPhoneDisconnected = PhoneNotifier.CurrentInterface == null; IsPhoneInMassStorage = PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_MassStorage; - IsPhoneInOtherMode = (!IsPhoneDisconnected && !IsPhoneInMassStorage); + IsPhoneInOtherMode = !IsPhoneDisconnected && !IsPhoneInMassStorage; BackupCommand.RaiseCanExecuteChanged(); BackupArchiveCommand.RaiseCanExecuteChanged(); BackupArchiveProvisioningCommand.RaiseCanExecuteChanged(); diff --git a/ViewModels/BackupViewModel.cs b/ViewModels/BackupViewModel.cs index cc3f482..fd61073 100644 --- a/ViewModels/BackupViewModel.cs +++ b/ViewModels/BackupViewModel.cs @@ -434,36 +434,33 @@ namespace WPinternals foreach (string PartitionName in ProvisioningPartitions) { - if (GPT.Partitions.Any(p => p.Name == PartitionName)) + if (GPT.Partitions.Any(p => p.Name == PartitionName) && Result) { - if (Result) + try { - try + Entry = Archive.CreateEntry(PartitionName + ".bin", CompressionLevel.Optimal); + EntryStream = Entry.Open(); + i++; + Busy.Message = "Create backup of partition " + PartitionName + " (" + i.ToString() + "/" + PartitionCount.ToString() + ")"; + if (PartitionName == "UEFI_BS_NV" && GPT.Partitions.Any(p => p.Name == "BACKUP_BS_NV")) { - Entry = Archive.CreateEntry(PartitionName + ".bin", CompressionLevel.Optimal); - EntryStream = Entry.Open(); - i++; - Busy.Message = "Create backup of partition " + PartitionName + " (" + i.ToString() + "/" + PartitionCount.ToString() + ")"; - if (PartitionName == "UEFI_BS_NV" && GPT.Partitions.Any(p => p.Name == "BACKUP_BS_NV")) - { - Phone.BackupPartition("BACKUP_BS_NV", EntryStream, Updater); - } - else - { - Phone.BackupPartition(PartitionName, EntryStream, Updater); - } + Phone.BackupPartition("BACKUP_BS_NV", EntryStream, Updater); } - catch (Exception Ex) + else { - LogFile.LogException(Ex); - Result = false; - } - finally - { - EntryStream?.Close(); - EntryStream = null; + Phone.BackupPartition(PartitionName, EntryStream, Updater); } } + catch (Exception Ex) + { + LogFile.LogException(Ex); + Result = false; + } + finally + { + EntryStream?.Close(); + EntryStream = null; + } } } } diff --git a/ViewModels/DownloadsViewModel.cs b/ViewModels/DownloadsViewModel.cs index b9a44e2..5875097 100644 --- a/ViewModels/DownloadsViewModel.cs +++ b/ViewModels/DownloadsViewModel.cs @@ -65,7 +65,7 @@ namespace WPinternals if (result == true) { FFUPath = dlg.FileName; - string FFUFile = System.IO.Path.GetFileName(FFUPath); + string FFUFile = Path.GetFileName(FFUPath); try { @@ -134,7 +134,7 @@ namespace WPinternals internal static long GetFileLengthFromURL(string URL) { long Length = 0; - HttpWebRequest req = (HttpWebRequest)System.Net.HttpWebRequest.Create(URL); + HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL); req.Method = "HEAD"; req.ServicePoint.ConnectionLimit = 10; using (WebResponse resp = req.GetResponse()) @@ -146,7 +146,7 @@ namespace WPinternals internal static string GetFileNameFromURL(string URL) { - string FileName = System.IO.Path.GetFileName(URL); + string FileName = Path.GetFileName(URL); int End = FileName.IndexOf('?'); if (End >= 0) { @@ -541,14 +541,14 @@ namespace WPinternals if (URLCollection == null) { Files = new string[1]; - Files[0] = System.IO.Path.Combine(Folder, DownloadsViewModel.GetFileNameFromURL(URL)); + Files[0] = Path.Combine(Folder, DownloadsViewModel.GetFileNameFromURL(URL)); } else { Files = new string[URLCollection.Length]; for (int i = 0; i < URLCollection.Length; i++) { - Files[i] = System.IO.Path.Combine(Folder, DownloadsViewModel.GetFileNameFromURL(URLCollection[i])); + Files[i] = Path.Combine(Folder, DownloadsViewModel.GetFileNameFromURL(URLCollection[i])); } } @@ -811,7 +811,7 @@ namespace WPinternals public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - return System.IO.Path.GetFileNameWithoutExtension((string)value); + return Path.GetFileNameWithoutExtension((string)value); } public object ConvertBack(object value, Type targetType, diff --git a/ViewModels/DumpRomTargetSelectionViewModel.cs b/ViewModels/DumpRomTargetSelectionViewModel.cs index 62a924a..467db78 100644 --- a/ViewModels/DumpRomTargetSelectionViewModel.cs +++ b/ViewModels/DumpRomTargetSelectionViewModel.cs @@ -216,7 +216,7 @@ namespace WPinternals { get { - return _DumpCommand ??= new DelegateCommand(() => DumpCallback(FFUPath, EFIESPPath, CompressEFIESP, MainOSPath, CompressMainOS, DataPath, CompressData), () => ((FFUPath != null) && ((EFIESPPath != null) || (MainOSPath != null) || (DataPath != null)))); + return _DumpCommand ??= new DelegateCommand(() => DumpCallback(FFUPath, EFIESPPath, CompressEFIESP, MainOSPath, CompressMainOS, DataPath, CompressData), () => (FFUPath != null) && ((EFIESPPath != null) || (MainOSPath != null) || (DataPath != null))); } } diff --git a/ViewModels/LumiaFlashRomSourceSelectionViewModel.cs b/ViewModels/LumiaFlashRomSourceSelectionViewModel.cs index 268f056..65d49f9 100644 --- a/ViewModels/LumiaFlashRomSourceSelectionViewModel.cs +++ b/ViewModels/LumiaFlashRomSourceSelectionViewModel.cs @@ -212,7 +212,7 @@ namespace WPinternals { get { - return _FlashPartitionsCommand ??= new DelegateCommand(() => FlashPartitionsCallback(EFIESPPath, MainOSPath, DataPath), () => (((EFIESPPath != null) || (MainOSPath != null) || (DataPath != null)) && (PhoneNotifier.CurrentInterface != null))); + return _FlashPartitionsCommand ??= new DelegateCommand(() => FlashPartitionsCallback(EFIESPPath, MainOSPath, DataPath), () => ((EFIESPPath != null) || (MainOSPath != null) || (DataPath != null)) && (PhoneNotifier.CurrentInterface != null)); } } @@ -221,7 +221,7 @@ namespace WPinternals { get { - return _FlashFFUCommand ??= new DelegateCommand(() => FlashFFUCallback(FFUPath), () => ((FFUPath != null) && (PhoneNotifier.CurrentInterface != null))); + return _FlashFFUCommand ??= new DelegateCommand(() => FlashFFUCallback(FFUPath), () => (FFUPath != null) && (PhoneNotifier.CurrentInterface != null)); } } @@ -230,7 +230,7 @@ namespace WPinternals { get { - return _FlashMMOSCommand ??= new DelegateCommand(() => FlashMMOSCallback(MMOSPath), () => ((MMOSPath != null) && (PhoneNotifier.CurrentInterface != null))); + return _FlashMMOSCommand ??= new DelegateCommand(() => FlashMMOSCallback(MMOSPath), () => (MMOSPath != null) && (PhoneNotifier.CurrentInterface != null)); } } @@ -239,7 +239,7 @@ namespace WPinternals { get { - return _FlashArchiveCommand ??= new DelegateCommand(() => FlashArchiveCallback(ArchivePath), () => ((ArchivePath != null) && (PhoneNotifier.CurrentInterface != null))); + return _FlashArchiveCommand ??= new DelegateCommand(() => FlashArchiveCallback(ArchivePath), () => (ArchivePath != null) && (PhoneNotifier.CurrentInterface != null)); } } @@ -269,7 +269,7 @@ namespace WPinternals { IsPhoneDisconnected = PhoneNotifier.CurrentInterface == null; IsPhoneInFlashMode = PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_Flash; - IsPhoneInOtherMode = (!IsPhoneDisconnected && !IsPhoneInFlashMode); + IsPhoneInOtherMode = !IsPhoneDisconnected && !IsPhoneInFlashMode; FlashPartitionsCommand.RaiseCanExecuteChanged(); FlashArchiveCommand.RaiseCanExecuteChanged(); FlashFFUCommand.RaiseCanExecuteChanged(); diff --git a/ViewModels/LumiaFlashRomViewModel.cs b/ViewModels/LumiaFlashRomViewModel.cs index 86aec67..788cbfd 100644 --- a/ViewModels/LumiaFlashRomViewModel.cs +++ b/ViewModels/LumiaFlashRomViewModel.cs @@ -116,7 +116,7 @@ namespace WPinternals ulong StreamLengthInSectors = (ulong)Stream.Length / 0x200; TotalSizeSectors += StreamLengthInSectors; PartitionCount++; - Partition Partition = GPT.Partitions.Find(p => string.Compare(p.Name, "EFIESP", true) == 0); + Partition Partition = GPT.Partitions.Find(p => string.Equals(p.Name, "EFIESP", StringComparison.CurrentCultureIgnoreCase)); if (StreamLengthInSectors > Partition.SizeInSectors) { LogFile.Log("Flash failed! Size of partition 'EFIESP' is too big."); @@ -131,7 +131,7 @@ namespace WPinternals ulong StreamLengthInSectors = (ulong)Stream.Length / 0x200; TotalSizeSectors += StreamLengthInSectors; PartitionCount++; - Partition Partition = GPT.Partitions.Find(p => string.Compare(p.Name, "MainOS", true) == 0); + Partition Partition = GPT.Partitions.Find(p => string.Equals(p.Name, "MainOS", StringComparison.CurrentCultureIgnoreCase)); MainOSOldSectorCount = Partition.SizeInSectors; MainOSNewSectorCount = StreamLengthInSectors; FirstMainOSSector = Partition.FirstSector; @@ -143,7 +143,7 @@ namespace WPinternals ulong StreamLengthInSectors = (ulong)Stream.Length / 0x200; TotalSizeSectors += StreamLengthInSectors; PartitionCount++; - Partition Partition = GPT.Partitions.Find(p => string.Compare(p.Name, "Data", true) == 0); + Partition Partition = GPT.Partitions.Find(p => string.Equals(p.Name, "Data", StringComparison.CurrentCultureIgnoreCase)); DataOldSectorCount = Partition.SizeInSectors; DataNewSectorCount = StreamLengthInSectors; } @@ -162,8 +162,8 @@ namespace WPinternals if ((MainOSNewSectorCount + DataNewSectorCount) <= OSSpace) { // MainOS and Data partitions need to be re-aligned! - Partition MainOSPartition = GPT.Partitions.Single(p => string.Compare(p.Name, "MainOS", true) == 0); - Partition DataPartition = GPT.Partitions.Single(p => string.Compare(p.Name, "Data", true) == 0); + Partition MainOSPartition = GPT.Partitions.Single(p => string.Equals(p.Name, "MainOS", StringComparison.CurrentCultureIgnoreCase)); + Partition DataPartition = GPT.Partitions.Single(p => string.Equals(p.Name, "Data", StringComparison.CurrentCultureIgnoreCase)); MainOSPartition.LastSector = MainOSPartition.FirstSector + MainOSNewSectorCount - 1; DataPartition.FirstSector = MainOSPartition.LastSector + 1; DataPartition.LastSector = DataPartition.FirstSector + DataNewSectorCount - 1; @@ -327,14 +327,14 @@ namespace WPinternals // First determine if we need a new GPT! if (!Entry.FullName.Contains("/")) // No subfolders { - string PartitionName = System.IO.Path.GetFileNameWithoutExtension(Entry.Name); + string PartitionName = Path.GetFileNameWithoutExtension(Entry.Name); int P = PartitionName.IndexOf('.'); if (P >= 0) { PartitionName = PartitionName.Substring(0, P); // Example: Data.bin.gz -> Data } - Partition Partition = GPT.Partitions.Find(p => string.Compare(p.Name, PartitionName, true) == 0); + Partition Partition = GPT.Partitions.Find(p => string.Equals(p.Name, PartitionName, StringComparison.CurrentCultureIgnoreCase)); if (Partition != null) { DecompressedStream DecompressedStream = new(Entry.Open()); @@ -348,13 +348,13 @@ namespace WPinternals TotalSizeSectors += StreamLengthInSectors; PartitionCount++; - if (string.Compare(PartitionName, "MainOS", true) == 0) + if (string.Equals(PartitionName, "MainOS", StringComparison.CurrentCultureIgnoreCase)) { MainOSOldSectorCount = Partition.SizeInSectors; MainOSNewSectorCount = StreamLengthInSectors; FirstMainOSSector = Partition.FirstSector; } - else if (string.Compare(PartitionName, "Data", true) == 0) + else if (string.Equals(PartitionName, "Data", StringComparison.CurrentCultureIgnoreCase)) { DataOldSectorCount = Partition.SizeInSectors; DataNewSectorCount = StreamLengthInSectors; @@ -377,8 +377,8 @@ namespace WPinternals if ((MainOSNewSectorCount + DataNewSectorCount) <= OSSpace) { // MainOS and Data partitions need to be re-aligned! - Partition MainOSPartition = GPT.Partitions.Single(p => string.Compare(p.Name, "MainOS", true) == 0); - Partition DataPartition = GPT.Partitions.Single(p => string.Compare(p.Name, "Data", true) == 0); + Partition MainOSPartition = GPT.Partitions.Single(p => string.Equals(p.Name, "MainOS", StringComparison.CurrentCultureIgnoreCase)); + Partition DataPartition = GPT.Partitions.Single(p => string.Equals(p.Name, "Data", StringComparison.CurrentCultureIgnoreCase)); MainOSPartition.LastSector = MainOSPartition.FirstSector + MainOSNewSectorCount - 1; DataPartition.FirstSector = MainOSPartition.LastSector + 1; DataPartition.LastSector = DataPartition.FirstSector + DataNewSectorCount - 1; @@ -429,7 +429,7 @@ namespace WPinternals PartitionName = PartitionName.Substring(0, Pos); } - Partition Partition = GPT.Partitions.Find(p => string.Compare(p.Name, PartitionName, true) == 0); + Partition Partition = GPT.Partitions.Find(p => string.Equals(p.Name, PartitionName, StringComparison.CurrentCultureIgnoreCase)); if (Partition != null) { Stream DecompressedStream = new DecompressedStream(Entry.Open()); diff --git a/ViewModels/LumiaUnlockBootViewModel.cs b/ViewModels/LumiaUnlockBootViewModel.cs index e12f679..464c5eb 100644 --- a/ViewModels/LumiaUnlockBootViewModel.cs +++ b/ViewModels/LumiaUnlockBootViewModel.cs @@ -140,7 +140,7 @@ namespace WPinternals UefiSecurityStatusResponse SecurityStatus = ((NokiaFlashModel)PhoneNotifier.CurrentModel).ReadSecurityStatus(); if (SecurityStatus != null) { - IsBootLoaderUnlocked = (SecurityStatus.AuthenticationStatus || SecurityStatus.RdcStatus || !SecurityStatus.SecureFfuEfuseStatus); + IsBootLoaderUnlocked = SecurityStatus.AuthenticationStatus || SecurityStatus.RdcStatus || !SecurityStatus.SecureFfuEfuseStatus; } TestPos = 2; @@ -210,16 +210,16 @@ namespace WPinternals } else { - const bool AlreadyUnlocked = false; + bool AlreadyUnlocked = false; if (DoUnlock) { NokiaFlashModel FlashModel = (NokiaFlashModel)PhoneNotifier.CurrentModel; GPT GPT = FlashModel.ReadGPT(); if ((GPT.GetPartition("IS_UNLOCKED") != null) || (GPT.GetPartition("BACKUP_EFIESP") != null)) { - ExitMessage("Phone is already unlocked", null); - return; - //AlreadyUnlocked = true; + //ExitMessage("Phone is already unlocked", null); + //return; + AlreadyUnlocked = true; } } @@ -281,7 +281,7 @@ namespace WPinternals { FFU ProfileFFU = null; - List FFUs = App.Config.FFURepository.Where(e => (Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists())).ToList(); + List FFUs = App.Config.FFURepository.Where(e => Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists()).ToList(); ProfileFFU = FFUs.Count > 0 ? new FFU(FFUs[0].Path) : throw new WPinternalsException("Profile FFU missing", "No profile FFU has been found in the repository for your device. You can add a profile FFU within the download section of the tool or by using the command line."); @@ -608,7 +608,7 @@ namespace WPinternals this.SwitchToDownload = SwitchToDownload; this.IsBootLoaderUnlocked = IsBootLoaderUnlocked; OkCommand = new DelegateCommand(() => Result(FFUPath, LoadersPath, SBL3Path, ProfileFFUPath, EDEPath, IsSupportedFfuNeeded ? SupportedFFUPath : null, false), - () => ((!TargetHasNewFlashProtocol && (!IsSupportedFfuNeeded || (IsSupportedFfuValid && (SupportedFFUPath != null)))) || ((ProfileFFUPath != null) && (!IsSupportedFfuNeeded || (IsSupportedFfuValid && (SupportedFFUPath != null)))))); + () => (!TargetHasNewFlashProtocol && (!IsSupportedFfuNeeded || (IsSupportedFfuValid && (SupportedFFUPath != null)))) || ((ProfileFFUPath != null) && (!IsSupportedFfuNeeded || (IsSupportedFfuValid && (SupportedFFUPath != null))))); FixCommand = new DelegateCommand(() => Result(null, null, null, null, null, null, true)); CancelCommand = new DelegateCommand(Abort); this.TargetHasNewFlashProtocol = TargetHasNewFlashProtocol; @@ -660,7 +660,7 @@ namespace WPinternals } catch { } - List FFUs = App.Config.FFURepository.Where(e => (PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists())).ToList(); + List FFUs = App.Config.FFURepository.Where(e => PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists()).ToList(); if (FFUs.Count > 0) { IsProfileFfuValid = true; @@ -859,7 +859,7 @@ namespace WPinternals { if (!TargetHasNewFlashProtocol) { - if (App.Config.FFURepository.Any(e => ((e.Path == SupportedFFUPath) && (App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V1.1-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion))))) + if (App.Config.FFURepository.Any(e => (e.Path == SupportedFFUPath) && App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V1.1-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion))) { IsSupportedFfuValid = true; } @@ -871,7 +871,7 @@ namespace WPinternals } else { - if (App.Config.FFURepository.Any(e => ((e.Path == SupportedFFUPath) && (App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion))))) + if (App.Config.FFURepository.Any(e => (e.Path == SupportedFFUPath) && App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion))) { IsSupportedFfuValid = true; } diff --git a/ViewModels/LumiaUnlockBootloaderViewModel.cs b/ViewModels/LumiaUnlockBootloaderViewModel.cs index f54ad88..63b9fab 100644 --- a/ViewModels/LumiaUnlockBootloaderViewModel.cs +++ b/ViewModels/LumiaUnlockBootloaderViewModel.cs @@ -18,6 +18,8 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +//#define DUMPPARTITIONS + using System; using System.Collections; using System.Collections.Generic; @@ -27,7 +29,7 @@ using System.Threading.Tasks; namespace WPinternals { - internal class LumiaUnlockBootloaderViewModel + internal static class LumiaUnlockBootloaderViewModel { // TODO: Add logging private static void PerformSoftBrick(PhoneNotifierViewModel Notifier, FFU FFU) @@ -37,7 +39,7 @@ namespace WPinternals // Send FFU headers UInt64 CombinedFFUHeaderSize = FFU.HeaderSize; byte[] FfuHeader = new byte[CombinedFFUHeaderSize]; - FileStream FfuFile = new(FFU.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read); + FileStream FfuFile = new(FFU.Path, FileMode.Open, FileAccess.Read); FfuFile.Read(FfuHeader, 0, (int)CombinedFFUHeaderSize); FfuFile.Close(); @@ -166,7 +168,7 @@ namespace WPinternals ExitSuccess("Bootloader restored successfully!"); } - await LumiaUnlockBootloaderViewModel.LumiaRelockUEFI(Notifier, FFUPath, DoResetFirst, SetWorkingStatus, UpdateWorkingStatus, tmpExitSuccess, tmpExitFailure); + await LumiaRelockUEFI(Notifier, FFUPath, DoResetFirst, SetWorkingStatus, UpdateWorkingStatus, tmpExitSuccess, tmpExitFailure); } internal static async Task LumiaV2UnlockUEFI(PhoneNotifierViewModel Notifier, string ProfileFFUPath, string EDEPath, string SupportedFFUPath, SetWorkingStatus SetWorkingStatus = null, UpdateWorkingStatus UpdateWorkingStatus = null, ExitSuccess ExitSuccess = null, ExitFailure ExitFailure = null, bool ReUnlockDevice = false) @@ -232,7 +234,7 @@ namespace WPinternals ExitSuccess("Bootloader unlocked successfully!", null); } - await LumiaUnlockBootloaderViewModel.LumiaUnlockUEFI(Notifier, ProfileFFUPath, EDEPath, SupportedFFUPath, SetWorkingStatus, UpdateWorkingStatus, tmpExitSuccess, tmpExitFailure, ReUnlockDevice: ReUnlockDevice); + await LumiaUnlockUEFI(Notifier, ProfileFFUPath, EDEPath, SupportedFFUPath, SetWorkingStatus, UpdateWorkingStatus, tmpExitSuccess, tmpExitFailure, ReUnlockDevice: ReUnlockDevice); } // Magic! @@ -270,7 +272,7 @@ namespace WPinternals { if (Notifier.CurrentModel is NokiaFlashModel) { - await LumiaUnlockBootloaderViewModel.LumiaRelockUEFI(Notifier, FFUPath, true, SetWorkingStatus, UpdateWorkingStatus, null, (string Message, string SubMessage) => + await LumiaRelockUEFI(Notifier, FFUPath, true, SetWorkingStatus, UpdateWorkingStatus, null, (string Message, string SubMessage) => { ExitFailure(Message, SubMessage); LogFile.EndAction("RelockBootloader"); @@ -296,15 +298,11 @@ namespace WPinternals throw new ArgumentNullException("FFU path is missing"); } - if (Notifier.CurrentInterface == PhoneInterfaces.Qualcomm_Download) + if (Notifier.CurrentInterface == PhoneInterfaces.Qualcomm_Download && string.IsNullOrEmpty(LoadersPath)) { - if (string.IsNullOrEmpty(LoadersPath)) - { - throw new Exception("Error: Path for Loaders is mandatory."); - } + throw new Exception("Error: Path for Loaders is mandatory."); } - const bool DumpPartitions = false; string DumpFilePrefix = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\") + DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss") + " - "; bool IsBootLoaderUnlocked = false; @@ -333,11 +331,10 @@ namespace WPinternals } UefiSecurityStatusResponse SecurityStatus = ((NokiaFlashModel)Notifier.CurrentModel).ReadSecurityStatus(); - IsBootLoaderUnlocked = (SecurityStatus.AuthenticationStatus || SecurityStatus.RdcStatus || !SecurityStatus.SecureFfuEfuseStatus); + IsBootLoaderUnlocked = SecurityStatus.AuthenticationStatus || SecurityStatus.RdcStatus || !SecurityStatus.SecureFfuEfuseStatus; } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "01.bin", FFU.GetSectors(0, 34)); // Original GPT @@ -347,7 +344,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif GPT NewGPT = null; if (Notifier.CurrentModel is NokiaFlashModel) @@ -405,8 +402,7 @@ namespace WPinternals GPT = NewGPT.Rebuild(); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "02.bin", GPT); // Patched GPT @@ -416,7 +412,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif SBL1 SBL1 = null; try @@ -429,8 +425,7 @@ namespace WPinternals throw new Exception("Error: Parsing SBL1 failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "03.bin", SBL1.Binary); // Original SBL1 @@ -440,7 +435,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif byte[] RootKeyHash = null; if (Notifier.CurrentInterface == PhoneInterfaces.Qualcomm_Download) @@ -489,8 +484,7 @@ namespace WPinternals throw new Exception("Error: Parsing SBL2 failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "05.bin", SBL2Partition.Binary); // Original SBL2 @@ -500,7 +494,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif byte[] SBL2 = SBL2Partition.Binary; @@ -516,8 +510,7 @@ namespace WPinternals throw new Exception("Error: Parsing SBL3 from FFU failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "07.bin", SBL3Partition.Binary); // Original SBL3 @@ -527,7 +520,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif byte[] SBL3 = SBL3Partition.Binary; @@ -542,8 +535,7 @@ namespace WPinternals throw new Exception("Error: Parsing UEFI failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "09.bin", UEFIPartition.Binary); // Original UEFI @@ -553,7 +545,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif byte[] UEFI = UEFIPartition.Binary; @@ -834,7 +826,6 @@ namespace WPinternals throw new ArgumentNullException("FFU path is missing"); } - const bool DumpPartitions = false; string DumpFilePrefix = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\") + DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss") + " - "; bool IsBootLoaderUnlocked = false; @@ -863,15 +854,12 @@ namespace WPinternals } UefiSecurityStatusResponse SecurityStatus = ((NokiaFlashModel)Notifier.CurrentModel).ReadSecurityStatus(); - IsBootLoaderUnlocked = (SecurityStatus.AuthenticationStatus || SecurityStatus.RdcStatus || !SecurityStatus.SecureFfuEfuseStatus); + IsBootLoaderUnlocked = SecurityStatus.AuthenticationStatus || SecurityStatus.RdcStatus || !SecurityStatus.SecureFfuEfuseStatus; } - if (!IsBootLoaderUnlocked) + if (!IsBootLoaderUnlocked && string.IsNullOrEmpty(LoadersPath)) { - if (string.IsNullOrEmpty(LoadersPath)) - { - throw new Exception("Error: Path for Loaders is mandatory."); - } + throw new Exception("Error: Path for Loaders is mandatory."); } FFU SupportedFFU = null; @@ -900,8 +888,7 @@ namespace WPinternals } } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "01.bin", FFU.GetSectors(0, 34)); // Original GPT @@ -911,7 +898,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif GPT NewGPT = null; if (Notifier.CurrentModel is NokiaFlashModel) @@ -980,8 +967,7 @@ namespace WPinternals } } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "02.bin", GPT); // Patched GPT @@ -991,7 +977,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif SBL1 SBL1 = null; try @@ -1004,8 +990,7 @@ namespace WPinternals throw new Exception("Error: Parsing SBL1 failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "03.bin", SBL1.Binary); // Original SBL1 @@ -1015,7 +1000,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif byte[] RootKeyHash = null; if (Notifier.CurrentInterface == PhoneInterfaces.Qualcomm_Download) @@ -1064,8 +1049,7 @@ namespace WPinternals throw new Exception("Error: Parsing SBL2 failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "05.bin", SBL2Partition.Binary); // Original SBL2 @@ -1075,7 +1059,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif byte[] SBL2; try @@ -1088,8 +1072,7 @@ namespace WPinternals throw new Exception("Error: Patching SBL2 failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "06.bin", SBL2Partition.Binary); // Patched SBL2 @@ -1099,7 +1082,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif byte[] ExtraSector = null; try @@ -1114,8 +1097,7 @@ namespace WPinternals throw new Exception("Error: Code generation failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "04.bin", ExtraSector); // Extra sector @@ -1125,7 +1107,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif SBL3 SBL3Partition; SBL3 OriginalSBL3; @@ -1165,8 +1147,7 @@ namespace WPinternals LogFile.Log("Taking selected SBL3"); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "07.bin", SBL3Partition.Binary); // Original SBL3 @@ -1176,7 +1157,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif byte[] SBL3; try @@ -1189,8 +1170,7 @@ namespace WPinternals throw new Exception("Error: Patching SBL3 failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "08.bin", SBL3Partition.Binary); // Patched SBL3 @@ -1200,7 +1180,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif UEFI UEFIPartition = null; try @@ -1213,8 +1193,7 @@ namespace WPinternals throw new Exception("Error: Parsing UEFI failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "09.bin", UEFIPartition.Binary); // Original UEFI @@ -1224,7 +1203,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif byte[] UEFI; try @@ -1237,8 +1216,7 @@ namespace WPinternals throw new Exception("Error: Patching UEFI failed."); } - if (DumpPartitions) - { +#if DUMPPARTITIONS try { File.WriteAllBytes(DumpFilePrefix + "0A.bin", UEFIPartition.Binary); // Patched UEFI @@ -1248,7 +1226,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Writing binary for logging failed."); } - } +#endif List PossibleLoaders = null; if (!IsBootLoaderUnlocked || Notifier.CurrentInterface == PhoneInterfaces.Qualcomm_Download) @@ -1431,7 +1409,7 @@ namespace WPinternals throw new WPinternalsException("Phone is in an unexpected mode.", "The phone should have been detected in flash, download or emergency flash mode. Instead it has been detected in " + Notifier.CurrentInterface.ToString() + " mode."); } - await LumiaUnlockBootloaderViewModel.LumiaUnlockUEFI(Notifier, FFUPath, LoadersPath, SupportedFFUPath, SetWorkingStatus, UpdateWorkingStatus, null, (string Message, string SubMessage) => + await LumiaUnlockUEFI(Notifier, FFUPath, LoadersPath, SupportedFFUPath, SetWorkingStatus, UpdateWorkingStatus, null, (string Message, string SubMessage) => { ExitFailure(Message, SubMessage); LogFile.EndAction("UnlockBootloader"); @@ -1494,7 +1472,7 @@ namespace WPinternals PhoneInfo Info = FlashModel.ReadPhoneInfo(ExtendedInfo: false); FlashAppType OriginalAppType = Info.App; - bool Switch = ((Info.App != FlashAppType.BootManager) && Info.IsBootloaderSecure); + bool Switch = (Info.App != FlashAppType.BootManager) && Info.IsBootloaderSecure; if (Switch) { FlashModel.SwitchToBootManagerContext(); @@ -1684,13 +1662,13 @@ namespace WPinternals // The second check should be more than enough in any case, if we find a header named MSDOS5.0 right in the middle of EFIESP, // there's not many cases other than us splitting the partition in half to get this here. // - if ((ByteOperations.ReadAsciiString(EFIESP, (UInt32)(EFIESP.Length / 2) + 3, 8)) == "MSDOS5.0") + if (ByteOperations.ReadAsciiString(EFIESP, (UInt32)(EFIESP.Length / 2) + 3, 8) == "MSDOS5.0") { EFIESPBackup = new byte[EfiespSizeInSectors * 0x200 / 2]; Buffer.BlockCopy(EFIESP, (Int32)EfiespSizeInSectors * 0x200 / 2, EFIESPBackup, 0, (Int32)EfiespSizeInSectors * 0x200 / 2); } - if (ByteOperations.ReadUInt16(EFIESP, 0xE) == LumiaUnlockBootloaderViewModel.LumiaGetFirstEFIESPSectorCount(GPT, new FFU(FFUPath), IsSpecB)) + if (ByteOperations.ReadUInt16(EFIESP, 0xE) == LumiaGetFirstEFIESPSectorCount(GPT, new FFU(FFUPath), IsSpecB)) { UndoEFIESPPadding = true; } @@ -1744,7 +1722,7 @@ namespace WPinternals if (UndoEFIESPPadding) { - FlashParts = LumiaUnlockBootloaderViewModel.LumiaGenerateUndoEFIESPFlashPayload(GPT, new FFU(FFUPath), IsSpecB); + FlashParts = LumiaGenerateUndoEFIESPFlashPayload(GPT, new FFU(FFUPath), IsSpecB); } FlashPart Part; @@ -1821,7 +1799,7 @@ namespace WPinternals WPinternalsStatus LastStatus = WPinternalsStatus.Undefined; ulong? MaxProgressValue = null; - await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, FFUPath, false, false, FlashParts, DoResetFirst, ClearFlashingStatusAtEnd: !NvCleared, + await LumiaFlashParts(Notifier, FFUPath, false, false, FlashParts, DoResetFirst, ClearFlashingStatusAtEnd: !NvCleared, SetWorkingStatus: (m, s, v, a, st) => { if (SetWorkingStatus != null) @@ -1881,7 +1859,7 @@ namespace WPinternals if (Notifier.CurrentInterface == PhoneInterfaces.Lumia_Flash) { - await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, FFUPath, false, false, null, DoResetFirst, ClearFlashingStatusAtEnd: true, ShowProgress: false); + await LumiaFlashParts(Notifier, FFUPath, false, false, null, DoResetFirst, ClearFlashingStatusAtEnd: true, ShowProgress: false); } } @@ -1939,12 +1917,9 @@ namespace WPinternals FFU ProfileFFU = new(ProfileFFUPath); - if (Info.IsBootloaderSecure) + if (Info.IsBootloaderSecure && !Info.PlatformID.StartsWith(ProfileFFU.PlatformID, StringComparison.OrdinalIgnoreCase)) { - if (!Info.PlatformID.StartsWith(ProfileFFU.PlatformID, StringComparison.OrdinalIgnoreCase)) - { - throw new ArgumentNullException("Profile FFU has wrong Platform ID for connected phone"); - } + throw new ArgumentNullException("Profile FFU has wrong Platform ID for connected phone"); } string Patch = "SecureBootHack-V1.1-EFIESP"; @@ -1977,7 +1952,7 @@ namespace WPinternals SetWorkingStatus("Assembling data for unlock", null, null); byte[] UnlockedEFIESP = ProfileFFU.GetPartition("EFIESP"); - LumiaUnlockBootloaderViewModel.LumiaPatchEFIESP(SupportedFFU, UnlockedEFIESP, IsSpecB); + LumiaPatchEFIESP(SupportedFFU, UnlockedEFIESP, IsSpecB); byte[] GPTChunk = GetGptChunk(FlashModel, (UInt32)ProfileFFU.ChunkSize); byte[] GPTChunkBackup = new byte[GPTChunk.Length]; @@ -2050,7 +2025,7 @@ namespace WPinternals _part.ProgressText = "Enabling Test Signing..."; } - await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, false, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); + await LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, false, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); if ((Notifier.CurrentInterface != PhoneInterfaces.Lumia_Bootloader) && (Notifier.CurrentInterface != PhoneInterfaces.Lumia_Flash)) { @@ -2080,7 +2055,7 @@ namespace WPinternals ShouldApplyOldEFIESPMethod = false; } - Parts = ShouldApplyOldEFIESPMethod ? new List() : LumiaUnlockBootloaderViewModel.LumiaGenerateEFIESPFlashPayload(UnlockedEFIESP, GPT, ProfileFFU, IsSpecB); + Parts = ShouldApplyOldEFIESPMethod ? new List() : LumiaGenerateEFIESPFlashPayload(UnlockedEFIESP, GPT, ProfileFFU, IsSpecB); Part = null; UInt32 OriginalEfiespSizeInSectors = (UInt32)GPT.GetPartition("EFIESP").SizeInSectors; @@ -2216,7 +2191,7 @@ namespace WPinternals _part.ProgressText = IsSpecB ? "Flashing unlocked bootloader (part 1)..." : "Flashing unlocked bootloader (part 2)..."; } - await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, true, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); + await LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, true, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); if ((Notifier.CurrentInterface != PhoneInterfaces.Lumia_Bootloader) && (Notifier.CurrentInterface != PhoneInterfaces.Lumia_Flash)) { @@ -2284,7 +2259,7 @@ namespace WPinternals }; Parts.Add(Part); - await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, false, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); + await LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, false, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); // An old NV backup was restored and it possibly contained the IsFlashing flag. // Can't clear it immeadiately, so we need another flash. @@ -2295,7 +2270,7 @@ namespace WPinternals if ((Notifier.CurrentInterface == PhoneInterfaces.Lumia_Bootloader) || (Notifier.CurrentInterface == PhoneInterfaces.Lumia_Flash)) { - await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, null, true, true, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); + await LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, null, true, true, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); } if (IsPhoneInBadMassStorageMode) @@ -2327,7 +2302,7 @@ namespace WPinternals try { - LumiaUnlockBootloaderViewModel.LumiaPatchEFIESP(SupportedFFU, BackupUnlockedEFIESP, IsSpecB); + LumiaPatchEFIESP(SupportedFFU, BackupUnlockedEFIESP, IsSpecB); } catch (Exception ex) { @@ -2341,7 +2316,7 @@ namespace WPinternals BackupUnlockedEFIESP = new byte[UnlockedEFIESP.Length]; Buffer.BlockCopy(BackupEFIESP, 0, BackupUnlockedEFIESP, 0, UnlockedEFIESP.Length); - LumiaUnlockBootloaderViewModel.LumiaPatchEFIESP(SupportedFFU, BackupUnlockedEFIESP, IsSpecB); + LumiaPatchEFIESP(SupportedFFU, BackupUnlockedEFIESP, IsSpecB); } SetWorkingStatus("Boot optimization...", null, null); @@ -2476,12 +2451,12 @@ namespace WPinternals _part.ProgressText = "Flashing unlocked bootloader (part 2)..."; } - await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, true, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); + await LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, true, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); } else { ulong FirstSector = GPT.GetPartition("EFIESP").FirstSector; - ulong SectorCount = LumiaUnlockBootloaderViewModel.LumiaGetFirstEFIESPSectorCount(GPT, ProfileFFU, IsSpecB); + ulong SectorCount = LumiaGetFirstEFIESPSectorCount(GPT, ProfileFFU, IsSpecB); byte[] BackupEFIESPAllocation = MassStorage.ReadSectors(FirstSector, SectorCount); // The backed up buffer includes our changed header done previously to have two EFIESPs in a single partition @@ -2493,7 +2468,7 @@ namespace WPinternals LogFile.Log("Unlocking backup partition", LogType.FileAndConsole); SetWorkingStatus("Unlocking backup partition", null, null); - LumiaUnlockBootloaderViewModel.LumiaPatchEFIESP(SupportedFFU, UnlockedEFIESP, IsSpecB); + LumiaPatchEFIESP(SupportedFFU, UnlockedEFIESP, IsSpecB); SetWorkingStatus("Boot optimization...", null, null); @@ -2528,14 +2503,14 @@ namespace WPinternals } ((NokiaFlashModel)Notifier.CurrentModel).SwitchToFlashAppContext(); - Parts = LumiaUnlockBootloaderViewModel.LumiaGenerateEFIESPFlashPayload(UnlockedEFIESP, GPT, ProfileFFU, IsSpecB); + Parts = LumiaGenerateEFIESPFlashPayload(UnlockedEFIESP, GPT, ProfileFFU, IsSpecB); foreach (FlashPart _part in Parts) { _part.ProgressText = IsSpecB ? "Flashing unlocked bootloader (part 2)..." : "Flashing unlocked bootloader (part 3)..."; } - await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, true, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); + await LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, true, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); if (!IsSpecB) { diff --git a/ViewModels/LumiaUnlockRootTargetSelectionViewModel.cs b/ViewModels/LumiaUnlockRootTargetSelectionViewModel.cs index d43e2b4..7a351c4 100644 --- a/ViewModels/LumiaUnlockRootTargetSelectionViewModel.cs +++ b/ViewModels/LumiaUnlockRootTargetSelectionViewModel.cs @@ -159,7 +159,7 @@ namespace WPinternals { get { - return _UnlockImageCommand ??= new DelegateCommand(() => UnlockImageCallback(EFIESPMountPoint, MainOSMountPoint), () => ((EFIESPMountPoint != null) || (MainOSMountPoint != null))); + return _UnlockImageCommand ??= new DelegateCommand(() => UnlockImageCallback(EFIESPMountPoint, MainOSMountPoint), () => (EFIESPMountPoint != null) || (MainOSMountPoint != null)); } } @@ -182,7 +182,7 @@ namespace WPinternals { IsPhoneDisconnected = PhoneNotifier.CurrentInterface == null; IsPhoneInMassStorage = PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_MassStorage; - IsPhoneInOtherMode = (!IsPhoneDisconnected && !IsPhoneInMassStorage); + IsPhoneInOtherMode = !IsPhoneDisconnected && !IsPhoneInMassStorage; UnlockPhoneCommand.RaiseCanExecuteChanged(); UnlockImageCommand.RaiseCanExecuteChanged(); } diff --git a/ViewModels/LumiaUnlockRootViewModel.cs b/ViewModels/LumiaUnlockRootViewModel.cs index 9590917..6f3eaa7 100644 --- a/ViewModels/LumiaUnlockRootViewModel.cs +++ b/ViewModels/LumiaUnlockRootViewModel.cs @@ -266,10 +266,10 @@ namespace WPinternals Partition Partition = GPT.GetPartition("UEFI"); byte[] UefiBuffer = Phone.ReadSectors(Partition.FirstSector, Partition.LastSector - Partition.FirstSector + 1); UEFI UEFI = new(UefiBuffer); - string BootMgrName = UEFI.EFIs.First(efi => ((efi.Name != null) && ((efi.Name.Contains("BootMgrApp")) || (efi.Name.Contains("FlashApp"))))).Name; + string BootMgrName = UEFI.EFIs.First(efi => (efi.Name != null) && (efi.Name.Contains("BootMgrApp") || efi.Name.Contains("FlashApp"))).Name; byte[] BootMgr = UEFI.GetFile(BootMgrName); // "Header V2" - Result = (ByteOperations.FindAscii(BootMgr, "Header V2") != null); + Result = ByteOperations.FindAscii(BootMgr, "Header V2") != null; Phone.CloseVolume(); return Result; } diff --git a/ViewModels/LumiaV2UnlockBootViewModel.cs b/ViewModels/LumiaV2UnlockBootViewModel.cs index 98c4eac..50fd8bb 100644 --- a/ViewModels/LumiaV2UnlockBootViewModel.cs +++ b/ViewModels/LumiaV2UnlockBootViewModel.cs @@ -57,7 +57,7 @@ namespace WPinternals { LogFile.Log("Find Flashing Profile", LogType.FileAndConsole); - NokiaFlashModel FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + NokiaFlashModel FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); PhoneInfo Info; if (DoResetFirst) @@ -125,7 +125,7 @@ namespace WPinternals LogFile.Log("Command: Enable testsigning", LogType.FileAndConsole); PhoneNotifierViewModel Notifier = new(); UIContext.Send(s => Notifier.Start(), null); - NokiaFlashModel FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + NokiaFlashModel FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); List Parts = new(); FlashPart Part; @@ -197,7 +197,7 @@ namespace WPinternals }); Parts.Add(Part); - await LumiaV2UnlockBootViewModel.LumiaV2CustomFlash(Notifier, FFUPath, false, false, Parts, DoResetFirst, ClearFlashingStatusAtEnd: false); + await LumiaV2CustomFlash(Notifier, FFUPath, false, false, Parts, DoResetFirst, ClearFlashingStatusAtEnd: false); Notifier.Stop(); } @@ -228,7 +228,7 @@ namespace WPinternals return ((MassStorage)Notifier.CurrentModel).Drive; } - NokiaFlashModel FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + NokiaFlashModel FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); if (DoResetFirst) { // The phone will be reset before flashing, so we have the opportunity to get some more info from the phone @@ -262,7 +262,7 @@ namespace WPinternals LogFile.Log("Command: Clear NV", LogType.FileAndConsole); PhoneNotifierViewModel Notifier = new(); UIContext.Send(s => Notifier.Start(), null); - NokiaFlashModel FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + NokiaFlashModel FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); List Parts = new(); // Use GetGptChunk() here instead of ReadGPT(), because ReadGPT() skips the first sector. @@ -338,7 +338,7 @@ namespace WPinternals PhoneNotifierViewModel Notifier = new(); UIContext.Send(s => Notifier.Start(), null); - NokiaFlashModel FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + NokiaFlashModel FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); PhoneInfo Info = FlashModel.ReadPhoneInfo(); @@ -359,10 +359,10 @@ namespace WPinternals bool GPTChanged = false; List Parts = new(); FlashPart Part; - if (string.Compare(PartitionName, "EFIESP", true) == 0) + if (string.Equals(PartitionName, "EFIESP", StringComparison.CurrentCultureIgnoreCase)) { byte[] EfiespBinary = File.ReadAllBytes(PartitionPath); - IsUnlocked = ((ByteOperations.ReadUInt32(EfiespBinary, 0x20) == (EfiespBinary.Length / 0x200 / 2)) && (ByteOperations.ReadAsciiString(EfiespBinary, (UInt32)(EfiespBinary.Length / 2) + 3, 8)) == "MSDOS5.0"); + IsUnlocked = (ByteOperations.ReadUInt32(EfiespBinary, 0x20) == (EfiespBinary.Length / 0x200 / 2)) && ByteOperations.ReadAsciiString(EfiespBinary, (UInt32)(EfiespBinary.Length / 2) + 3, 8) == "MSDOS5.0"; if (IsUnlocked) { @@ -417,7 +417,7 @@ namespace WPinternals Stream = Stream }; Parts.Add(Part); - await LumiaV2CustomFlash(Notifier, FFUPath, false, false, Parts, DoResetFirst, string.Compare(PartitionName, "UEFI_BS_NV", true) != 0); + await LumiaV2CustomFlash(Notifier, FFUPath, false, false, Parts, DoResetFirst, !string.Equals(PartitionName, "UEFI_BS_NV", StringComparison.CurrentCultureIgnoreCase)); } Notifier.Stop(); } @@ -447,11 +447,11 @@ namespace WPinternals PhoneNotifierViewModel Notifier = new(); UIContext.Send(s => Notifier.Start(), null); - NokiaFlashModel FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash)); + NokiaFlashModel FlashModel = (NokiaFlashModel)await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); PhoneInfo Info = FlashModel.ReadPhoneInfo(); - byte[] Data = System.IO.File.ReadAllBytes(DataPath); + byte[] Data = File.ReadAllBytes(DataPath); await LumiaV2CustomFlash(Notifier, FFUPath, false, false, (UInt32)StartSector, Data, DoResetFirst); Notifier.Stop(); @@ -573,7 +573,7 @@ namespace WPinternals if (FFUPath == null) { // Try to find an FFU from the repository for which there is also a known flashing profile - FFUs = App.Config.FFURepository.Where(e => (Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists())).ToList(); + FFUs = App.Config.FFURepository.Where(e => Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists()).ToList(); foreach (FFUEntry CurrentEntry in FFUs) { Profile = App.Config.GetProfile(Info.PlatformID, Info.Firmware, CurrentEntry.FirmwareVersion); @@ -620,17 +620,14 @@ namespace WPinternals throw new ArgumentException("Streams must be seekable"); } - if (((Part.StartSector * 0x200) % FFU.ChunkSize) != 0) + if ((Part.StartSector * 0x200 % FFU.ChunkSize) != 0) { throw new ArgumentException("Invalid StartSector alignment"); } - if (CheckSectorAlignment) + if (CheckSectorAlignment && (Part.Stream.Length % FFU.ChunkSize) != 0) { - if ((Part.Stream.Length % FFU.ChunkSize) != 0) - { - throw new ArgumentException("Invalid Data length"); - } + throw new ArgumentException("Invalid Data length"); } } } @@ -646,7 +643,7 @@ namespace WPinternals } UEFI UEFI = new(FFU.GetPartition("UEFI")); - string BootMgrName = UEFI.EFIs.First(efi => (efi.Name?.Contains("BootMgrApp") == true)).Name; + string BootMgrName = UEFI.EFIs.First(efi => efi.Name?.Contains("BootMgrApp") == true).Name; UInt32 EstimatedSizeOfMemGap = (UInt32)UEFI.GetFile(BootMgrName).Length; byte Options = 0; if (SkipWrite) @@ -995,7 +992,7 @@ namespace WPinternals Model.SendFfuHeaderV2(CurrentGapFill, 0, PartialHeader, Options); // Fill memory gap -> This will fail on phones with Flash Protocol v1.x !! On Lumia 640 this will hang on receiving the response when EndAsyncFlash was not called. } - using (FileStream FfuFile = new(FFU.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read)) + using (FileStream FfuFile = new(FFU.Path, FileMode.Open, FileAccess.Read)) { // On every flashing phase we need to send the full header again to reset all the counters. FfuFile.Read(FfuHeader, 0, (int)CombinedFFUHeaderSize); @@ -1059,7 +1056,7 @@ namespace WPinternals else { // From start of hash-table skip the first hashes for Image- and StoreHeaders. - HashTableSize = (UInt32)(((FFU.ImageHeader.Length + FFU.StoreHeader.Length) / FFU.ChunkSize) * 0x20); + HashTableSize = (UInt32)((FFU.ImageHeader.Length + FFU.StoreHeader.Length) / FFU.ChunkSize * 0x20); NewHashOffset += HashTableSize; } @@ -1615,7 +1612,7 @@ namespace WPinternals PartialHeader = new byte[UefiMemorySim.PageSize]; Model.SendFfuHeaderV2(CurrentGapFill, 0, PartialHeader, Options); // Fill memory gap } - using (FileStream FfuFile = new(FFU.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read)) + using (FileStream FfuFile = new(FFU.Path, FileMode.Open, FileAccess.Read)) { // On every flashing phase we need to send the full header again, because this triggers ffu_import_invalidate(), which is necessary to reset all the counters. FfuFile.Read(FfuHeader, 0, (int)CombinedFFUHeaderSize); @@ -1920,7 +1917,7 @@ namespace WPinternals internal static string GetProgrammerPath(byte[] RKH, string Type) { - IEnumerable RKHEntries = App.Config.EmergencyRepository.Where(e => (StructuralComparisons.StructuralEqualityComparer.Equals(e.RKH, RKH) && e.ProgrammerExists())); + IEnumerable RKHEntries = App.Config.EmergencyRepository.Where(e => StructuralComparisons.StructuralEqualityComparer.Equals(e.RKH, RKH) && e.ProgrammerExists()); if (RKHEntries.Any()) { if (RKHEntries.Count() == 1) @@ -1929,7 +1926,7 @@ namespace WPinternals } else { - EmergencyFileEntry RKHEntry = RKHEntries.FirstOrDefault(e => string.Compare(e.Type, Type, false) == 0); + EmergencyFileEntry RKHEntry = RKHEntries.FirstOrDefault(e => string.Equals(e.Type, Type, StringComparison.CurrentCulture)); if (RKHEntry != null) { return RKHEntry.ProgrammerPath; @@ -1942,7 +1939,7 @@ namespace WPinternals } else { - EmergencyFileEntry TypeEntry = App.Config.EmergencyRepository.Find(e => ((string.Compare(e.Type, Type, false) == 0) && e.ProgrammerExists())); + EmergencyFileEntry TypeEntry = App.Config.EmergencyRepository.Find(e => string.Equals(e.Type, Type, StringComparison.CurrentCulture) && e.ProgrammerExists()); if (TypeEntry != null) { return TypeEntry.ProgrammerPath; @@ -2036,7 +2033,7 @@ namespace WPinternals PartitionName = PartitionName.Substring(0, Pos); } - Partition Partition = GPT.Partitions.Find(p => string.Compare(p.Name, PartitionName, true) == 0); + Partition Partition = GPT.Partitions.Find(p => string.Equals(p.Name, PartitionName, StringComparison.CurrentCultureIgnoreCase)); if (Partition != null) { using DecompressedStream DecompressedStream = new(Entry.Open()); @@ -2050,13 +2047,13 @@ namespace WPinternals TotalSizeSectors += StreamLengthInSectors; PartitionCount++; - if (string.Compare(PartitionName, "MainOS", true) == 0) + if (string.Equals(PartitionName, "MainOS", StringComparison.CurrentCultureIgnoreCase)) { MainOSOldSectorCount = Partition.SizeInSectors; MainOSNewSectorCount = StreamLengthInSectors; FirstMainOSSector = Partition.FirstSector; } - else if (string.Compare(PartitionName, "Data", true) == 0) + else if (string.Equals(PartitionName, "Data", StringComparison.CurrentCultureIgnoreCase)) { DataOldSectorCount = Partition.SizeInSectors; DataNewSectorCount = StreamLengthInSectors; @@ -2067,12 +2064,12 @@ namespace WPinternals ExitFailure("Flash failed!", "Size of partition '" + PartitionName + "' is too big."); return; } - else if (string.Compare(PartitionName, "EFIESP", true) == 0) + else if (string.Equals(PartitionName, "EFIESP", StringComparison.CurrentCultureIgnoreCase)) { ulong EfiespLength = StreamLengthInSectors * 0x200; byte[] EfiespBinary = new byte[EfiespLength]; DecompressedStream.Read(EfiespBinary, 0, (int)EfiespLength); - IsUnlocked = ((ByteOperations.ReadUInt32(EfiespBinary, 0x20) == (EfiespBinary.Length / 0x200 / 2)) && (ByteOperations.ReadAsciiString(EfiespBinary, (UInt32)(EfiespBinary.Length / 2) + 3, 8)) == "MSDOS5.0"); + IsUnlocked = (ByteOperations.ReadUInt32(EfiespBinary, 0x20) == (EfiespBinary.Length / 0x200 / 2)) && ByteOperations.ReadAsciiString(EfiespBinary, (UInt32)(EfiespBinary.Length / 2) + 3, 8) == "MSDOS5.0"; if (IsUnlocked) { Partition IsUnlockedFlag = GPT.GetPartition("IS_UNLOCKED"); @@ -2115,8 +2112,8 @@ namespace WPinternals if ((MainOSNewSectorCount + DataNewSectorCount) <= OSSpace) { // MainOS and Data partitions need to be re-aligned! - Partition MainOSPartition = GPT.Partitions.Single(p => string.Compare(p.Name, "MainOS", true) == 0); - Partition DataPartition = GPT.Partitions.Single(p => string.Compare(p.Name, "Data", true) == 0); + Partition MainOSPartition = GPT.Partitions.Single(p => string.Equals(p.Name, "MainOS", StringComparison.CurrentCultureIgnoreCase)); + Partition DataPartition = GPT.Partitions.Single(p => string.Equals(p.Name, "Data", StringComparison.CurrentCultureIgnoreCase)); MainOSPartition.LastSector = MainOSPartition.FirstSector + MainOSNewSectorCount - 1; DataPartition.FirstSector = MainOSPartition.LastSector + 1; if ((DataPartition.FirstSector % 0x100) > 0) @@ -2252,7 +2249,7 @@ namespace WPinternals PartitionName = PartitionName.Substring(0, Pos); } - Target = GPT.Partitions.Find(p => string.Compare(p.Name, PartitionName, true) == 0); + Target = GPT.Partitions.Find(p => string.Equals(p.Name, PartitionName, StringComparison.CurrentCultureIgnoreCase)); if (Target != null) { Part = new FlashPart @@ -2269,7 +2266,7 @@ namespace WPinternals Parts = Parts.OrderBy(p => p.StartSector).ToList(); int Count = 1; - Parts.Where(p => (p.ProgressText?.StartsWith("Flashing partition ") == true)).ToList().ForEach((p) => + Parts.Where(p => p.ProgressText?.StartsWith("Flashing partition ") == true).ToList().ForEach((p) => { p.ProgressText += " (" + Count.ToString() + "/" + PartitionCount.ToString() + ")"; Count++; @@ -2411,7 +2408,7 @@ namespace WPinternals PartitionCount++; byte[] EfiespBinary = File.ReadAllBytes(EFIESPPath); - IsUnlocked = ((ByteOperations.ReadUInt32(EfiespBinary, 0x20) == (EfiespBinary.Length / 0x200 / 2)) && (ByteOperations.ReadAsciiString(EfiespBinary, (UInt32)(EfiespBinary.Length / 2) + 3, 8)) == "MSDOS5.0"); + IsUnlocked = (ByteOperations.ReadUInt32(EfiespBinary, 0x20) == (EfiespBinary.Length / 0x200 / 2)) && ByteOperations.ReadAsciiString(EfiespBinary, (UInt32)(EfiespBinary.Length / 2) + 3, 8) == "MSDOS5.0"; if (IsUnlocked) { Partition IsUnlockedFlag = GPT.GetPartition("IS_UNLOCKED"); @@ -2474,8 +2471,8 @@ namespace WPinternals if ((MainOSNewSectorCount + DataNewSectorCount) <= OSSpace) { // MainOS and Data partitions need to be re-aligned! - Partition MainOSPartition = GPT.Partitions.Single(p => string.Compare(p.Name, "MainOS", true) == 0); - Partition DataPartition = GPT.Partitions.Single(p => string.Compare(p.Name, "Data", true) == 0); + Partition MainOSPartition = GPT.Partitions.Single(p => string.Equals(p.Name, "MainOS", StringComparison.CurrentCultureIgnoreCase)); + Partition DataPartition = GPT.Partitions.Single(p => string.Equals(p.Name, "Data", StringComparison.CurrentCultureIgnoreCase)); MainOSPartition.LastSector = MainOSPartition.FirstSector + MainOSNewSectorCount - 1; DataPartition.FirstSector = MainOSPartition.LastSector + 1; if ((DataPartition.FirstSector % 0x100) > 0) @@ -2598,7 +2595,7 @@ namespace WPinternals int Count = 0; - Target = GPT.Partitions.Find(p => string.Compare(p.Name, "EFIESP", true) == 0); + Target = GPT.Partitions.Find(p => string.Equals(p.Name, "EFIESP", StringComparison.CurrentCultureIgnoreCase)); if ((EFIESPPath != null) && (Target != null)) { Count++; @@ -2612,7 +2609,7 @@ namespace WPinternals LogFile.Log("Partition name=EFIESP, startsector=0x" + Target.FirstSector.ToString("X8") + ", sectorcount = 0x" + (Part.Stream.Length / 0x200).ToString("X8"), LogType.FileOnly); } - Target = GPT.Partitions.Find(p => string.Compare(p.Name, "MainOS", true) == 0); + Target = GPT.Partitions.Find(p => string.Equals(p.Name, "MainOS", StringComparison.CurrentCultureIgnoreCase)); if ((MainOSPath != null) && (Target != null)) { Count++; @@ -2626,7 +2623,7 @@ namespace WPinternals LogFile.Log("Partition name=MainOS, startsector=0x" + Target.FirstSector.ToString("X8") + ", sectorcount = 0x" + (Part.Stream.Length / 0x200).ToString("X8"), LogType.FileOnly); } - Target = GPT.Partitions.Find(p => string.Compare(p.Name, "Data", true) == 0); + Target = GPT.Partitions.Find(p => string.Equals(p.Name, "Data", StringComparison.CurrentCultureIgnoreCase)); if ((DataPath != null) && (Target != null)) { Count++; diff --git a/ViewModels/LumiaV3FlashRomViewModel.cs b/ViewModels/LumiaV3FlashRomViewModel.cs index 36cdf02..aea3e4f 100644 --- a/ViewModels/LumiaV3FlashRomViewModel.cs +++ b/ViewModels/LumiaV3FlashRomViewModel.cs @@ -64,7 +64,7 @@ namespace WPinternals public UInt32 HashTableSize; } - internal class ManifestIni + internal static class ManifestIni { internal static string BuildUpManifest(FullFlash fullFlash, Store store) { @@ -178,17 +178,14 @@ namespace WPinternals throw new ArgumentException("Streams must be seekable"); } - if (((Part.StartSector * 0x200) % chunkSize) != 0) + if ((Part.StartSector * 0x200 % chunkSize) != 0) { throw new ArgumentException("Invalid StartSector alignment"); } - if (CheckSectorAlignment) + if (CheckSectorAlignment && (Part.Stream.Length % chunkSize) != 0) { - if ((Part.Stream.Length % chunkSize) != 0) - { - throw new ArgumentException("Invalid Data length"); - } + throw new ArgumentException("Invalid Data length"); } } } @@ -247,7 +244,7 @@ namespace WPinternals //Logging.Log("Generating image manifest..."); string manifest = ManifestIni.BuildUpManifest(ffimage, simage);//, partitions); - byte[] TextBytes = System.Text.Encoding.ASCII.GetBytes(manifest); + byte[] TextBytes = Encoding.ASCII.GetBytes(manifest); image.ManifestLength = (UInt32)TextBytes.Length; diff --git a/ViewModels/MainViewModel.cs b/ViewModels/MainViewModel.cs index 556f5c9..7218c3f 100644 --- a/ViewModels/MainViewModel.cs +++ b/ViewModels/MainViewModel.cs @@ -127,7 +127,7 @@ namespace WPinternals Registry.CurrentUser.OpenSubKey("Software", true).CreateSubKey("WPInternals"); } - if ((Registration.IsPrerelease) && (Registry.CurrentUser.OpenSubKey("Software\\WPInternals").GetValue("NdaAccepted") == null)) + if (Registration.IsPrerelease && (Registry.CurrentUser.OpenSubKey("Software\\WPInternals").GetValue("NdaAccepted") == null)) { this.ContextViewModel = new DisclaimerAndNdaViewModel(Disclaimer_Accepted); } @@ -135,7 +135,7 @@ namespace WPinternals { this.ContextViewModel = new DisclaimerViewModel(Disclaimer_Accepted); } - else if ((Registration.IsPrerelease) && !Registration.IsRegistered()) + else if (Registration.IsPrerelease && !Registration.IsRegistered()) { ContextViewModel = new RegistrationViewModel(Registration_Completed, Registration_Failed); } @@ -149,7 +149,7 @@ namespace WPinternals { ContextViewModel = null; - if ((Registration.IsPrerelease) && !Registration.IsRegistered()) + if (Registration.IsPrerelease && !Registration.IsRegistered()) { ContextViewModel = new RegistrationViewModel(Registration_Completed, Registration_Failed); } diff --git a/ViewModels/NokiaFlashViewModel.cs b/ViewModels/NokiaFlashViewModel.cs index 24aa9ee..da1681c 100644 --- a/ViewModels/NokiaFlashViewModel.cs +++ b/ViewModels/NokiaFlashViewModel.cs @@ -198,7 +198,7 @@ namespace WPinternals } eMMC = Manufacturer == null ? MemSizeDouble.ToString() + " GB" : Manufacturer + " " + MemSizeDouble.ToString() + " GB"; - SamsungWarningVisible = (MID == 0x0015); + SamsungWarningVisible = MID == 0x0015; } else { diff --git a/ViewModels/NokiaNormalViewModel.cs b/ViewModels/NokiaNormalViewModel.cs index bc94d45..0d40b3e 100644 --- a/ViewModels/NokiaNormalViewModel.cs +++ b/ViewModels/NokiaNormalViewModel.cs @@ -82,7 +82,7 @@ namespace WPinternals bool? ProductionDone = CurrentModel.ExecuteJsonMethodAsBoolean("ReadProductionDoneState", "ProductionDone"); IsBootloaderSecurityEnabled = ProductionDone == null ? CurrentModel.ExecuteJsonMethodAsString("GetSecurityMode", "SecMode").Contains("Restricted", StringComparison.OrdinalIgnoreCase) - : (CurrentModel.ExecuteJsonMethodAsString("GetSecurityMode", "SecMode").Contains("Restricted", StringComparison.OrdinalIgnoreCase)) && (bool)CurrentModel.ExecuteJsonMethodAsBoolean("ReadProductionDoneState", "ProductionDone"); + : CurrentModel.ExecuteJsonMethodAsString("GetSecurityMode", "SecMode").Contains("Restricted", StringComparison.OrdinalIgnoreCase) && (bool)CurrentModel.ExecuteJsonMethodAsBoolean("ReadProductionDoneState", "ProductionDone"); LogFile.Log("Bootloader Security: " + ((bool)IsBootloaderSecurityEnabled ? "Enabled" : "Disabled")); IsSimLocked = CurrentModel.ExecuteJsonMethodAsBoolean("ReadSimlockActive", "SimLockActive"); diff --git a/ViewModels/PhoneNotifierViewModel.cs b/ViewModels/PhoneNotifierViewModel.cs index fefce02..cdf3c97 100644 --- a/ViewModels/PhoneNotifierViewModel.cs +++ b/ViewModels/PhoneNotifierViewModel.cs @@ -162,12 +162,12 @@ namespace WPinternals { try { - if ((e.DevicePath.Contains("VID_0421&", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_045E&", StringComparison.OrdinalIgnoreCase))) + if (e.DevicePath.Contains("VID_0421&", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_045E&", StringComparison.OrdinalIgnoreCase)) { - if ((e.DevicePath.Contains("&PID_0660&MI_04", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("&PID_0713&MI_04", StringComparison.OrdinalIgnoreCase)) || // for Spec B - (e.DevicePath.Contains("&PID_0A01&MI_04", StringComparison.OrdinalIgnoreCase))) // for Spec B (650) + if (e.DevicePath.Contains("&PID_0660&MI_04", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("&PID_0713&MI_04", StringComparison.OrdinalIgnoreCase) || // for Spec B + e.DevicePath.Contains("&PID_0A01&MI_04", StringComparison.OrdinalIgnoreCase)) // for Spec B (650) { CurrentInterface = PhoneInterfaces.Lumia_Label; CurrentModel = new NokiaPhoneModel(e.DevicePath); @@ -177,9 +177,9 @@ namespace WPinternals LogFile.Log("Mode: Label", LogType.FileAndConsole); NewDeviceArrived(new ArrivalEventArgs((PhoneInterfaces)CurrentInterface, CurrentModel)); } - else if ((e.DevicePath.Contains("&PID_0661", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("&PID_06FC", StringComparison.OrdinalIgnoreCase)) || // VID_0421&PID_06FC is for Lumia 930 - (e.DevicePath.Contains("&PID_0A00", StringComparison.OrdinalIgnoreCase))) // vid_045e & pid_0a00 & mi_03 = Lumia 950 XL normal mode + else if (e.DevicePath.Contains("&PID_0661", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("&PID_06FC", StringComparison.OrdinalIgnoreCase) || // VID_0421&PID_06FC is for Lumia 930 + e.DevicePath.Contains("&PID_0A00", StringComparison.OrdinalIgnoreCase)) // vid_045e & pid_0a00 & mi_03 = Lumia 950 XL normal mode { if (((USBNotifier)sender).Guid == OldCombiInterfaceGuid) { @@ -229,10 +229,10 @@ namespace WPinternals NewDeviceArrived(new ArrivalEventArgs((PhoneInterfaces)CurrentInterface, CurrentModel)); } } - else if ((e.DevicePath.Contains("&PID_066E", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("&PID_0714", StringComparison.OrdinalIgnoreCase)) || // VID_0421&PID_0714 is for Lumia 930 - (e.DevicePath.Contains("&PID_0A02", StringComparison.OrdinalIgnoreCase)) || // VID_045E&PID_0A02 is for Lumia 950 - (e.DevicePath.Contains("&PID_05EE", StringComparison.OrdinalIgnoreCase))) // VID_0421&PID_05EE is for early RX100 + else if (e.DevicePath.Contains("&PID_066E", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("&PID_0714", StringComparison.OrdinalIgnoreCase) || // VID_0421&PID_0714 is for Lumia 930 + e.DevicePath.Contains("&PID_0A02", StringComparison.OrdinalIgnoreCase) || // VID_045E&PID_0A02 is for Lumia 950 + e.DevicePath.Contains("&PID_05EE", StringComparison.OrdinalIgnoreCase)) // VID_0421&PID_05EE is for early RX100 { CurrentModel = new NokiaFlashModel(e.DevicePath); ((NokiaFlashModel)CurrentModel).InterfaceChanged += InterfaceChanged; @@ -284,9 +284,9 @@ namespace WPinternals } } } - else if ((e.DevicePath.Contains("DISK&VEN_QUALCOMM&PROD_MMC_STORAGE", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("DISK&VEN_MSFT&PROD_PHONE_MMC_STOR", StringComparison.OrdinalIgnoreCase)) || - ((e.DevicePath.Length == @"\\.\E:".Length) && (e.DevicePath.StartsWith(@"\\.\")) && (e.DevicePath.EndsWith(":")))) + else if (e.DevicePath.Contains("DISK&VEN_QUALCOMM&PROD_MMC_STORAGE", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("DISK&VEN_MSFT&PROD_PHONE_MMC_STOR", StringComparison.OrdinalIgnoreCase) || + ((e.DevicePath.Length == @"\\.\E:".Length) && e.DevicePath.StartsWith(@"\\.\") && e.DevicePath.EndsWith(":"))) { #if DEBUG LogFile.Log("Mass storage arrived: " + e.DevicePath, LogType.FileOnly); @@ -335,7 +335,7 @@ namespace WPinternals { if (e.DevicePath.Contains("&PID_9008", StringComparison.OrdinalIgnoreCase)) { - USBDeviceInfo DeviceInfo = Array.Find(USBDevice.GetDevices(((USBNotifier)sender).Guid), (d) => string.Compare(d.DevicePath, e.DevicePath, true) == 0); + USBDeviceInfo DeviceInfo = Array.Find(USBDevice.GetDevices(((USBNotifier)sender).Guid), (d) => string.Equals(d.DevicePath, e.DevicePath, StringComparison.CurrentCultureIgnoreCase)); if ((DeviceInfo.BusName == "QHSUSB_DLOAD") || (DeviceInfo.BusName == "QHSUSB__BULK") || ((DeviceInfo.BusName?.Length == 0) && (LastInterface != PhoneInterfaces.Qualcomm_Download))) // TODO: Separate for Sahara! { @@ -424,19 +424,19 @@ namespace WPinternals } if ( - (e.DevicePath.Contains("VID_0421&PID_0660&MI_04", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_0421&PID_0713&MI_04", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_045E&PID_0A01&MI_04", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_0421&PID_0661", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_0421&PID_06FC", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_0421&PID_066E", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_0421&PID_0714", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_0421&PID_05EE", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_045E&PID_0A00", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_045E&PID_0A02", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("VID_05C6&PID_9008", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("DISK&VEN_QUALCOMM&PROD_MMC_STORAGE", StringComparison.OrdinalIgnoreCase)) || - (e.DevicePath.Contains("DISK&VEN_MSFT&PROD_PHONE_MMC_STOR", StringComparison.OrdinalIgnoreCase)) + e.DevicePath.Contains("VID_0421&PID_0660&MI_04", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_0421&PID_0713&MI_04", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_045E&PID_0A01&MI_04", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_0421&PID_0661", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_0421&PID_06FC", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_0421&PID_066E", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_0421&PID_0714", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_0421&PID_05EE", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_045E&PID_0A00", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_045E&PID_0A02", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("VID_05C6&PID_9008", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("DISK&VEN_QUALCOMM&PROD_MMC_STORAGE", StringComparison.OrdinalIgnoreCase) || + e.DevicePath.Contains("DISK&VEN_MSFT&PROD_PHONE_MMC_STOR", StringComparison.OrdinalIgnoreCase) ) { if (CurrentInterface != null) diff --git a/ViewModels/RestoreSourceSelectionViewModel.cs b/ViewModels/RestoreSourceSelectionViewModel.cs index 6a6599b..f10278d 100644 --- a/ViewModels/RestoreSourceSelectionViewModel.cs +++ b/ViewModels/RestoreSourceSelectionViewModel.cs @@ -153,7 +153,7 @@ namespace WPinternals { get { - return _RestoreCommand ??= new DelegateCommand(() => RestoreCallback(EFIESPPath, MainOSPath, DataPath), () => (((EFIESPPath != null) || (MainOSPath != null) || (DataPath != null)) && (PhoneNotifier.CurrentInterface != null))); + return _RestoreCommand ??= new DelegateCommand(() => RestoreCallback(EFIESPPath, MainOSPath, DataPath), () => ((EFIESPPath != null) || (MainOSPath != null) || (DataPath != null)) && (PhoneNotifier.CurrentInterface != null)); } } @@ -176,7 +176,7 @@ namespace WPinternals { IsPhoneDisconnected = PhoneNotifier.CurrentInterface == null; IsPhoneInFlashMode = PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_Flash; - IsPhoneInOtherMode = (!IsPhoneDisconnected && !IsPhoneInFlashMode); + IsPhoneInOtherMode = !IsPhoneDisconnected && !IsPhoneInFlashMode; RestoreCommand.RaiseCanExecuteChanged(); } diff --git a/ViewModels/SwitchModeViewModel.cs b/ViewModels/SwitchModeViewModel.cs index 5fd844a..14f5627 100644 --- a/ViewModels/SwitchModeViewModel.cs +++ b/ViewModels/SwitchModeViewModel.cs @@ -659,15 +659,15 @@ namespace WPinternals } } - bool IsOldLumia = (Info.FlashAppProtocolVersionMajor < 2); - bool IsNewLumia = (Info.FlashAppProtocolVersionMajor >= 2); + bool IsOldLumia = Info.FlashAppProtocolVersionMajor < 2; + bool IsNewLumia = Info.FlashAppProtocolVersionMajor >= 2; bool IsUnlockedNew = false; if (IsNewLumia) { GPT GPT = FlashModel.ReadGPT(); - IsUnlockedNew = ((GPT.GetPartition("IS_UNLOCKED") != null) || (GPT.GetPartition("BACKUP_EFIESP") != null) || (GPT.GetPartition("BACKUP_BS_NV") != null)); + IsUnlockedNew = (GPT.GetPartition("IS_UNLOCKED") != null) || (GPT.GetPartition("BACKUP_EFIESP") != null) || (GPT.GetPartition("BACKUP_BS_NV") != null); } - bool IsOriginalEngineeringLumia = (!Info.IsBootloaderSecure && !IsUnlockedNew); + bool IsOriginalEngineeringLumia = !Info.IsBootloaderSecure && !IsUnlockedNew; if (IsOldLumia || IsOriginalEngineeringLumia) { diff --git a/Views/BackupView.xaml.cs b/Views/BackupView.xaml.cs index 69a4216..5709393 100644 --- a/Views/BackupView.xaml.cs +++ b/Views/BackupView.xaml.cs @@ -36,12 +36,9 @@ namespace WPinternals private void HandleHyperlinkClick(object sender, RoutedEventArgs args) { - if (args.Source is Hyperlink link) + if (args.Source is Hyperlink link && link.NavigateUri.ToString() == "UnlockBoot") { - if (link.NavigateUri.ToString() == "UnlockBoot") - { - ((BackupTargetSelectionViewModel)DataContext).SwitchToUnlockBoot(); - } + ((BackupTargetSelectionViewModel)DataContext).SwitchToUnlockBoot(); } } diff --git a/Views/Empty.xaml.cs b/Views/Empty.xaml.cs index 614a72d..fbdb9e5 100644 --- a/Views/Empty.xaml.cs +++ b/Views/Empty.xaml.cs @@ -66,7 +66,7 @@ namespace WPinternals obj = VisualTreeHelper.GetParent(obj); } - PhoneNotifier = ((MainViewModel)(((MainWindow)obj).DataContext)).PhoneNotifier; + PhoneNotifier = ((MainViewModel)((MainWindow)obj).DataContext).PhoneNotifier; PhoneNotifier.NewDeviceArrived += PhoneNotifier_NewDeviceArrived; } @@ -117,14 +117,11 @@ namespace WPinternals { App.InterruptBoot = (bool)e.NewValue; - if ((bool)e.NewValue) + if ((bool)e.NewValue && PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_Bootloader) { - if (PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_Bootloader) - { - App.InterruptBoot = false; - LogFile.Log("Found Lumia BootMgr and user forced to interrupt the boot process. Force to Flash-mode."); - Task.Run(() => SwitchModeViewModel.SwitchTo(PhoneNotifier, PhoneInterfaces.Lumia_Flash)); - } + App.InterruptBoot = false; + LogFile.Log("Found Lumia BootMgr and user forced to interrupt the boot process. Force to Flash-mode."); + Task.Run(() => SwitchModeViewModel.SwitchTo(PhoneNotifier, PhoneInterfaces.Lumia_Flash)); } } diff --git a/Views/LumiaUndoRootTargetSelectionView.xaml.cs b/Views/LumiaUndoRootTargetSelectionView.xaml.cs index a870410..ec8d4e9 100644 --- a/Views/LumiaUndoRootTargetSelectionView.xaml.cs +++ b/Views/LumiaUndoRootTargetSelectionView.xaml.cs @@ -36,12 +36,9 @@ namespace WPinternals private void HandleHyperlinkClick(object sender, RoutedEventArgs args) { - if (args.Source is Hyperlink link) + if (args.Source is Hyperlink link && link.NavigateUri.ToString() == "UnlockBoot") { - if (link.NavigateUri.ToString() == "UnlockBoot") - { - ((LumiaUndoRootTargetSelectionViewModel)DataContext).SwitchToUnlockBoot(); - } + ((LumiaUndoRootTargetSelectionViewModel)DataContext).SwitchToUnlockBoot(); } } diff --git a/Views/MainWindow.xaml.cs b/Views/MainWindow.xaml.cs index a24bc57..2479212 100644 --- a/Views/MainWindow.xaml.cs +++ b/Views/MainWindow.xaml.cs @@ -32,7 +32,7 @@ namespace WPinternals { InitializeComponent(); - Visibility = System.Windows.Visibility.Collapsed; + Visibility = Visibility.Collapsed; } protected override void OnSourceInitialized(EventArgs e) diff --git a/Views/StartupWindow.xaml.cs b/Views/StartupWindow.xaml.cs index af2bd0f..93af0de 100644 --- a/Views/StartupWindow.xaml.cs +++ b/Views/StartupWindow.xaml.cs @@ -37,7 +37,7 @@ namespace WPinternals protected override async void OnSourceInitialized(EventArgs e) { - Visibility = System.Windows.Visibility.Hidden; + Visibility = Visibility.Hidden; bool NeedLicenseAgrement = false; if (Registry.CurrentUser.OpenSubKey("Software\\WPInternals") == null) @@ -45,7 +45,7 @@ namespace WPinternals Registry.CurrentUser.OpenSubKey("Software", true).CreateSubKey("WPInternals"); } - if ((Registration.IsPrerelease) && (Registry.CurrentUser.OpenSubKey("Software\\WPInternals").GetValue("NdaAccepted") == null)) + if (Registration.IsPrerelease && (Registry.CurrentUser.OpenSubKey("Software\\WPInternals").GetValue("NdaAccepted") == null)) { NeedLicenseAgrement = true; } diff --git a/WPinternals.csproj b/WPinternals.csproj index 3bb0c78..6b73279 100644 --- a/WPinternals.csproj +++ b/WPinternals.csproj @@ -25,13 +25,13 @@ true - 1701;1702;CA1416 + 1701;1702;CA1416;RCS1090;RCS1163 true true Heathcliff74.snk - 1701;1702;CA1416 + 1701;1702;CA1416;RCS1090;RCS1163 WPinternals.ico diff --git a/WPinternalsConfig.cs b/WPinternalsConfig.cs index 30c3da9..1ac33fb 100644 --- a/WPinternalsConfig.cs +++ b/WPinternalsConfig.cs @@ -60,7 +60,7 @@ namespace WPinternals bool Result = false; if (App.Config.RegistrationName != null) { - Result = (CalcRegKey() == App.Config.RegistrationKey); + Result = CalcRegKey() == App.Config.RegistrationKey; } return Result; } @@ -80,7 +80,7 @@ namespace WPinternals byte[] KeyBytes = System.Text.Encoding.UTF8.GetBytes(KeyBase); SHA1Managed sha = new(); byte[] Key = sha.ComputeHash(KeyBytes); - return System.Convert.ToBase64String(Key); + return Convert.ToBase64String(Key); } } @@ -88,8 +88,6 @@ namespace WPinternals { internal static WPinternalsConfig ReadConfig() { - WPinternalsConfig Result; - string FilePath = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\WPInternals.config"); if (File.Exists(FilePath)) { @@ -149,7 +147,7 @@ namespace WPinternals internal FlashProfile GetProfile(string PlatformID, string PhoneFirmware, string FfuFirmware = null) { - return FlashProfiles.Find(p => ((string.Compare(p.PlatformID, PlatformID, true) == 0) && (string.Compare(p.PhoneFirmware, PhoneFirmware, true) == 0) && ((FfuFirmware == null) || (string.Compare(p.FfuFirmware, FfuFirmware, true) == 0)))); + return FlashProfiles.Find(p => string.Equals(p.PlatformID, PlatformID, StringComparison.CurrentCultureIgnoreCase) && string.Equals(p.PhoneFirmware, PhoneFirmware, StringComparison.CurrentCultureIgnoreCase) && ((FfuFirmware == null) || string.Equals(p.FfuFirmware, FfuFirmware, StringComparison.CurrentCultureIgnoreCase))); } public List FlashProfiles = new(); @@ -169,7 +167,7 @@ namespace WPinternals internal void AddFfuToRepository(string FFUPath, string PlatformID, string FirmwareVersion, string OSVersion) { - FFUEntry Entry = FFURepository.Find(e => ((e.PlatformID == PlatformID) && (e.FirmwareVersion == FirmwareVersion) && (string.Compare(e.Path, FFUPath, true) == 0))); + FFUEntry Entry = FFURepository.Find(e => (e.PlatformID == PlatformID) && (e.FirmwareVersion == FirmwareVersion) && string.Equals(e.Path, FFUPath, StringComparison.CurrentCultureIgnoreCase)); if (Entry == null) { LogFile.Log("Adding FFU to repository: " + FFUPath, LogType.FileAndConsole); @@ -203,7 +201,7 @@ namespace WPinternals internal void RemoveFfuFromRepository(string FFUPath) { int Count = 0; - FFURepository.Where(e => (string.Compare(e.Path, FFUPath, true) == 0)).ToList().ForEach(e => + FFURepository.Where(e => string.Equals(e.Path, FFUPath, StringComparison.CurrentCultureIgnoreCase)).ToList().ForEach(e => { Count++; FFURepository.Remove(e); @@ -225,8 +223,8 @@ namespace WPinternals internal void AddEmergencyToRepository(string Type, string ProgrammerPath, string PayloadPath) { - EmergencyFileEntry Entry = EmergencyRepository.Find(e => ((e.Type == Type) && (string.Compare(e.ProgrammerPath, ProgrammerPath, true) == 0))); - if ((Entry != null) && (PayloadPath != null) && (string.Compare(Entry.PayloadPath, PayloadPath, true) != 0)) + EmergencyFileEntry Entry = EmergencyRepository.Find(e => (e.Type == Type) && string.Equals(e.ProgrammerPath, ProgrammerPath, StringComparison.CurrentCultureIgnoreCase)); + if ((Entry != null) && (PayloadPath != null) && (!string.Equals(Entry.PayloadPath, PayloadPath, StringComparison.CurrentCultureIgnoreCase))) { LogFile.Log("Updating emergency payload path in repository: " + PayloadPath, LogType.FileAndConsole); Entry.PayloadPath = PayloadPath; @@ -259,7 +257,7 @@ namespace WPinternals internal void RemoveEmergencyFromRepository(string ProgrammerPath) { int Count = 0; - EmergencyRepository.Where(e => (string.Compare(e.ProgrammerPath, ProgrammerPath, true) == 0)).ToList().ForEach(e => + EmergencyRepository.Where(e => string.Equals(e.ProgrammerPath, ProgrammerPath, StringComparison.CurrentCultureIgnoreCase)).ToList().ForEach(e => { Count++; EmergencyRepository.Remove(e); @@ -318,11 +316,11 @@ namespace WPinternals ValueBuffer[9] |= 2; } - return System.Convert.ToBase64String(ValueBuffer); + return Convert.ToBase64String(ValueBuffer); } set { - byte[] ValueBuffer = System.Convert.FromBase64String(value); + byte[] ValueBuffer = Convert.FromBase64String(value); byte Version = ValueBuffer[0]; FillSize = ByteOperations.ReadUInt32(ValueBuffer, 1); HeaderSize = ByteOperations.ReadUInt32(ValueBuffer, 5); diff --git a/WinUSBNet/API/APIException.cs b/WinUSBNet/API/APIException.cs index b9d0e67..707d7b7 100644 --- a/WinUSBNet/API/APIException.cs +++ b/WinUSBNet/API/APIException.cs @@ -25,9 +25,13 @@ namespace MadWizard.WinUSBNet.API { } + public APIException() : base() + { + } + public static APIException Win32(string message) { - return APIException.Win32(message, Marshal.GetLastWin32Error()); + return Win32(message, Marshal.GetLastWin32Error()); // TEST!! // int ErrorCode = Marshal.GetLastWin32Error(); diff --git a/WinUSBNet/API/DeviceManagement.cs b/WinUSBNet/API/DeviceManagement.cs index d1b9fe9..62433fc 100644 --- a/WinUSBNet/API/DeviceManagement.cs +++ b/WinUSBNet/API/DeviceManagement.cs @@ -45,7 +45,7 @@ namespace MadWizard.WinUSBNet.API // in the strucutre that are not part of dbch_name and dividing by 2 because there are // 2 bytes per character. - stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2); + stringSize = Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2); // The dbcc_name parameter of devBroadcastDeviceInterface contains the device name. // Trim dbcc_name to match the size of the String. @@ -87,12 +87,9 @@ namespace MadWizard.WinUSBNet.API private static byte[] GetProperty(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, SPDRP property, out int regType) { - if (!SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, property, IntPtr.Zero, IntPtr.Zero, 0, out uint requiredSize)) + if (!SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref deviceInfoData, property, IntPtr.Zero, IntPtr.Zero, 0, out uint requiredSize) && Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) { - if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) - { - throw APIException.Win32("Failed to get buffer size for device registry property."); - } + throw APIException.Win32("Failed to get buffer size for device registry property."); } byte[] buffer = new byte[requiredSize]; @@ -116,12 +113,9 @@ namespace MadWizard.WinUSBNet.API // Heathcliff74 private static byte[] GetProperty(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, DEVPROPKEY property, out uint propertyType) { - if (!SetupDiGetDeviceProperty(deviceInfoSet, ref deviceInfoData, ref property, out propertyType, null, 0, out int requiredSize, 0)) + if (!SetupDiGetDeviceProperty(deviceInfoSet, ref deviceInfoData, ref property, out propertyType, null, 0, out int requiredSize, 0) && Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) { - if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) - { - throw APIException.Win32("Failed to get buffer size for device registry property."); - } + throw APIException.Win32("Failed to get buffer size for device registry property."); } byte[] buffer = new byte[requiredSize]; @@ -261,12 +255,9 @@ namespace MadWizard.WinUSBNet.API ref bufferSize, IntPtr.Zero); - if (!success) + if (!success && Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) { - if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) - { - throw APIException.Win32("Failed to get interface details buffer size."); - } + throw APIException.Win32("Failed to get interface details buffer size."); } IntPtr detailDataBuffer = IntPtr.Zero; @@ -372,7 +363,7 @@ namespace MadWizard.WinUSBNet.API public static void StopDeviceDeviceNotifications(IntPtr deviceNotificationHandle) { - if (!DeviceManagement.UnregisterDeviceNotification(deviceNotificationHandle)) + if (!UnregisterDeviceNotification(deviceNotificationHandle)) { throw APIException.Win32("Failed to unregister device notification"); } diff --git a/WinUSBNet/DeviceNotifyHook.cs b/WinUSBNet/DeviceNotifyHook.cs index fcb6467..4eaeb92 100644 --- a/WinUSBNet/DeviceNotifyHook.cs +++ b/WinUSBNet/DeviceNotifyHook.cs @@ -177,7 +177,7 @@ namespace MadWizard.WinUSBNet if (Application.Current != null) { - if (Application.Current.Dispatcher.Thread.ManagedThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId) + if (Application.Current.Dispatcher.Thread.ManagedThreadId == Environment.CurrentManagedThreadId) { RemoveHookAction(); } diff --git a/WinUSBNet/USBDevice.cs b/WinUSBNet/USBDevice.cs index eca544a..4b553e8 100644 --- a/WinUSBNet/USBDevice.cs +++ b/WinUSBNet/USBDevice.cs @@ -804,7 +804,7 @@ namespace MadWizard.WinUSBNet /// no device with the given GUID could be found null is returned. public static USBDevice GetSingleDevice(string guidString) { - return USBDevice.GetSingleDevice(new Guid(guidString)); + return GetSingleDevice(new Guid(guidString)); } private static USBDeviceDescriptor GetDeviceDescriptor(string devicePath) diff --git a/WinUSBNet/USBException.cs b/WinUSBNet/USBException.cs index d22d441..2c9002b 100644 --- a/WinUSBNet/USBException.cs +++ b/WinUSBNet/USBException.cs @@ -34,5 +34,9 @@ namespace MadWizard.WinUSBNet : base(message, innerException) { } + + public USBException() : base() + { + } } } diff --git a/WinUSBNet/USBInterface.cs b/WinUSBNet/USBInterface.cs index c9c9e5b..32ade90 100644 --- a/WinUSBNet/USBInterface.cs +++ b/WinUSBNet/USBInterface.cs @@ -90,10 +90,12 @@ namespace MadWizard.WinUSBNet get; } + /// /// Zero based interface index in WinUSB. /// Note that this is not necessarily the same as the interface *number* /// from the interface descriptor. There might be interfaces within the /// USB device that do not use WinUSB, these are not counted for index. + /// internal int InterfaceIndex { get;