diff --git a/7zip/Common/CRC.cs b/7zip/Common/CRC.cs
index fe51f6c..668b491 100644
--- a/7zip/Common/CRC.cs
+++ b/7zip/Common/CRC.cs
@@ -2,7 +2,7 @@
namespace SevenZip
{
- class CRC
+ internal class CRC
{
public static readonly uint[] Table;
@@ -14,42 +14,51 @@ namespace SevenZip
{
uint r = i;
for (int j = 0; j < 8; j++)
+ {
if ((r & 1) != 0)
+ {
r = (r >> 1) ^ kPoly;
+ }
else
+ {
r >>= 1;
+ }
+ }
+
Table[i] = r;
}
}
- uint _value = 0xFFFFFFFF;
+ private uint _value = 0xFFFFFFFF;
public void Init() { _value = 0xFFFFFFFF; }
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);
+ }
}
public uint GetDigest() { return _value ^ 0xFFFFFFFF; }
- static uint CalculateDigest(byte[] data, uint offset, uint size)
+ private static uint CalculateDigest(byte[] data, uint offset, uint size)
{
- CRC crc = new CRC();
+ CRC crc = new();
// crc.Init();
crc.Update(data, offset, size);
return crc.GetDigest();
}
- static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size)
+ private static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size)
{
- return (CalculateDigest(data, offset, size) == digest);
+ return CalculateDigest(data, offset, size) == digest;
}
}
}
diff --git a/7zip/Common/CommandLineParser.cs b/7zip/Common/CommandLineParser.cs
index 8c82ed8..c1134fe 100644
--- a/7zip/Common/CommandLineParser.cs
+++ b/7zip/Common/CommandLineParser.cs
@@ -47,7 +47,7 @@ namespace SevenZip.CommandLineParser
{
public bool ThereIs;
public bool WithMinus;
- public ArrayList PostStrings = new ArrayList();
+ public ArrayList PostStrings = new();
public int PostCharIndex;
public SwitchResult()
{
@@ -57,28 +57,39 @@ namespace SevenZip.CommandLineParser
public class Parser
{
- public ArrayList NonSwitchStrings = new ArrayList();
- SwitchResult[] _switches;
+ public ArrayList NonSwitchStrings = new();
+ private readonly SwitchResult[] _switches;
public Parser(int numSwitches)
{
_switches = new SwitchResult[numSwitches];
for (int i = 0; i < numSwitches; i++)
+ {
_switches[i] = new SwitchResult();
+ }
}
- bool ParseString(string srcString, SwitchForm[] switchForms)
+ private bool ParseString(string srcString, SwitchForm[] switchForms)
{
int len = srcString.Length;
if (len == 0)
+ {
return false;
+ }
+
int pos = 0;
if (!IsItSwitchChar(srcString[pos]))
+ {
return false;
+ }
+
while (pos < len)
{
if (IsItSwitchChar(srcString[pos]))
+ {
pos++;
+ }
+
const int kNoLen = -1;
int matchedSwitchIndex = 0;
int maxLen = kNoLen;
@@ -86,7 +97,10 @@ namespace SevenZip.CommandLineParser
{
int switchLen = switchForms[switchIndex].IDString.Length;
if (switchLen <= maxLen || pos + switchLen > len)
+ {
continue;
+ }
+
if (String.Compare(switchForms[switchIndex].IDString, 0,
srcString, pos, switchLen, true) == 0)
{
@@ -95,11 +109,17 @@ namespace SevenZip.CommandLineParser
}
}
if (maxLen == kNoLen)
+ {
throw new Exception("maxLen == kNoLen");
+ }
+
SwitchResult matchedSwitch = _switches[matchedSwitchIndex];
SwitchForm switchForm = switchForms[matchedSwitchIndex];
if ((!switchForm.Multi) && matchedSwitch.ThereIs)
+ {
throw new Exception("switch must be single");
+ }
+
matchedSwitch.ThereIs = true;
pos += maxLen;
int tailSize = len - pos;
@@ -109,28 +129,39 @@ namespace SevenZip.CommandLineParser
case SwitchType.PostMinus:
{
if (tailSize == 0)
+ {
matchedSwitch.WithMinus = false;
+ }
else
{
matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus);
if (matchedSwitch.WithMinus)
+ {
pos++;
+ }
}
break;
}
case SwitchType.PostChar:
{
if (tailSize < switchForm.MinLen)
+ {
throw new Exception("switch is not full");
+ }
+
string charSet = switchForm.PostCharSet;
const int kEmptyCharValue = -1;
if (tailSize == 0)
+ {
matchedSwitch.PostCharIndex = kEmptyCharValue;
+ }
else
{
int index = charSet.IndexOf(srcString[pos]);
if (index < 0)
+ {
matchedSwitch.PostCharIndex = kEmptyCharValue;
+ }
else
{
matchedSwitch.PostCharIndex = index;
@@ -144,10 +175,13 @@ namespace SevenZip.CommandLineParser
{
int minLen = switchForm.MinLen;
if (tailSize < minLen)
+ {
throw new Exception("switch is not full");
+ }
+
if (type == SwitchType.UnLimitedPostString)
{
- matchedSwitch.PostStrings.Add(srcString.Substring(pos));
+ matchedSwitch.PostStrings.Add(srcString[pos..]);
return true;
}
String stringSwitch = srcString.Substring(pos, minLen);
@@ -156,7 +190,10 @@ namespace SevenZip.CommandLineParser
{
char c = srcString[pos];
if (IsItSwitchChar(c))
+ {
break;
+ }
+
stringSwitch += c;
}
matchedSwitch.PostStrings.Add(stringSwitch);
@@ -165,7 +202,6 @@ namespace SevenZip.CommandLineParser
}
}
return true;
-
}
public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings)
@@ -176,13 +212,19 @@ namespace SevenZip.CommandLineParser
{
string s = commandStrings[i];
if (stopSwitch)
+ {
NonSwitchStrings.Add(s);
+ }
else
if (s == kStopSwitchParsing)
+ {
stopSwitch = true;
+ }
else
if (!ParseString(s, switchForms))
+ {
NonSwitchStrings.Add(s);
+ }
}
}
@@ -198,7 +240,7 @@ namespace SevenZip.CommandLineParser
{
if (commandString.IndexOf(id) == 0)
{
- postString = commandString.Substring(id.Length);
+ postString = commandString[id.Length..];
return i;
}
}
@@ -213,7 +255,7 @@ namespace SevenZip.CommandLineParser
return -1;
}
- static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms,
+ private static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms,
string commandString, ArrayList indices)
{
indices.Clear();
@@ -230,28 +272,37 @@ namespace SevenZip.CommandLineParser
if (newIndex >= 0)
{
if (currentIndex >= 0)
+ {
return false;
+ }
+
if (commandString.IndexOf(c, newIndex + 1) >= 0)
+ {
return false;
+ }
+
currentIndex = j;
numUsedChars++;
}
}
if (currentIndex == -1 && !charsSet.EmptyAllowed)
+ {
return false;
+ }
+
indices.Add(currentIndex);
}
- return (numUsedChars == commandString.Length);
+ return numUsedChars == commandString.Length;
}
- const char kSwitchID1 = '-';
- const char kSwitchID2 = '/';
+ private const char kSwitchID1 = '-';
+ private const char kSwitchID2 = '/';
- const char kSwitchMinus = '-';
- const string kStopSwitchParsing = "--";
+ private const char kSwitchMinus = '-';
+ private const string kStopSwitchParsing = "--";
- static bool IsItSwitchChar(char c)
+ private static bool IsItSwitchChar(char c)
{
- return (c == kSwitchID1 || c == kSwitchID2);
+ return c == kSwitchID1 || c == kSwitchID2;
}
}
@@ -266,7 +317,7 @@ namespace SevenZip.CommandLineParser
}
}
- class CommandSubCharsSet
+ internal class CommandSubCharsSet
{
public string Chars = "";
public bool EmptyAllowed = false;
diff --git a/7zip/Common/InBuffer.cs b/7zip/Common/InBuffer.cs
index 773f0a6..2c56d2e 100644
--- a/7zip/Common/InBuffer.cs
+++ b/7zip/Common/InBuffer.cs
@@ -4,13 +4,13 @@ namespace SevenZip.Buffer
{
public class InBuffer
{
- byte[] m_Buffer;
- uint m_Pos;
- uint m_Limit;
- uint m_BufferSize;
- System.IO.Stream m_Stream;
- bool m_StreamWasExhausted;
- ulong m_ProcessedSize;
+ private readonly byte[] m_Buffer;
+ private uint m_Pos;
+ private uint m_Limit;
+ private readonly uint m_BufferSize;
+ private System.IO.Stream m_Stream;
+ private bool m_StreamWasExhausted;
+ private ulong m_ProcessedSize;
public InBuffer(uint bufferSize)
{
@@ -30,16 +30,18 @@ namespace SevenZip.Buffer
public bool ReadBlock()
{
if (m_StreamWasExhausted)
+ {
return false;
+ }
+
m_ProcessedSize += m_Pos;
int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize);
m_Pos = 0;
m_Limit = (uint)aNumProcessedBytes;
m_StreamWasExhausted = (aNumProcessedBytes == 0);
- return (!m_StreamWasExhausted);
+ return !m_StreamWasExhausted;
}
-
public void ReleaseStream()
{
// m_Stream.Close();
@@ -49,8 +51,13 @@ namespace SevenZip.Buffer
public bool ReadByte(byte b) // check it
{
if (m_Pos >= m_Limit)
+ {
if (!ReadBlock())
+ {
return false;
+ }
+ }
+
b = m_Buffer[m_Pos++];
return true;
}
@@ -59,8 +66,13 @@ namespace SevenZip.Buffer
{
// return (byte)m_Stream.ReadByte();
if (m_Pos >= m_Limit)
+ {
if (!ReadBlock())
+ {
return 0xFF;
+ }
+ }
+
return m_Buffer[m_Pos++];
}
diff --git a/7zip/Common/OutBuffer.cs b/7zip/Common/OutBuffer.cs
index a4378ea..a9657df 100644
--- a/7zip/Common/OutBuffer.cs
+++ b/7zip/Common/OutBuffer.cs
@@ -4,11 +4,11 @@ namespace SevenZip.Buffer
{
public class OutBuffer
{
- byte[] m_Buffer;
- uint m_Pos;
- uint m_BufferSize;
- System.IO.Stream m_Stream;
- ulong m_ProcessedSize;
+ private readonly byte[] m_Buffer;
+ private uint m_Pos;
+ private readonly uint m_BufferSize;
+ private System.IO.Stream m_Stream;
+ private ulong m_ProcessedSize;
public OutBuffer(uint bufferSize)
{
@@ -31,13 +31,18 @@ namespace SevenZip.Buffer
{
m_Buffer[m_Pos++] = b;
if (m_Pos >= m_BufferSize)
+ {
FlushData();
+ }
}
public void FlushData()
{
if (m_Pos == 0)
+ {
return;
+ }
+
m_Stream.Write(m_Buffer, 0, (int)m_Pos);
m_Pos = 0;
}
diff --git a/7zip/Compress/LZ/IMatchFinder.cs b/7zip/Compress/LZ/IMatchFinder.cs
index d484fe8..e0ebbd8 100644
--- a/7zip/Compress/LZ/IMatchFinder.cs
+++ b/7zip/Compress/LZ/IMatchFinder.cs
@@ -4,7 +4,7 @@ using System;
namespace SevenZip.Compression.LZ
{
- interface IInWindowStream
+ internal interface IInWindowStream
{
void SetStream(System.IO.Stream inStream);
void Init();
@@ -14,7 +14,7 @@ namespace SevenZip.Compression.LZ
UInt32 GetNumAvailableBytes();
}
- interface IMatchFinder : IInWindowStream
+ internal interface IMatchFinder : IInWindowStream
{
void Create(UInt32 historySize, UInt32 keepAddBufferBefore,
UInt32 matchMaxLen, UInt32 keepAddBufferAfter);
diff --git a/7zip/Compress/LZ/LzBinTree.cs b/7zip/Compress/LZ/LzBinTree.cs
index dfc09a6..93dfd0e 100644
--- a/7zip/Compress/LZ/LzBinTree.cs
+++ b/7zip/Compress/LZ/LzBinTree.cs
@@ -6,30 +6,30 @@ namespace SevenZip.Compression.LZ
{
public class BinTree : InWindow, IMatchFinder
{
- UInt32 _cyclicBufferPos;
- UInt32 _cyclicBufferSize = 0;
- UInt32 _matchMaxLen;
+ private UInt32 _cyclicBufferPos;
+ private UInt32 _cyclicBufferSize = 0;
+ private UInt32 _matchMaxLen;
- UInt32[] _son;
- UInt32[] _hash;
+ private UInt32[] _son;
+ private UInt32[] _hash;
- UInt32 _cutValue = 0xFF;
- UInt32 _hashMask;
- UInt32 _hashSizeSum = 0;
+ private UInt32 _cutValue = 0xFF;
+ private UInt32 _hashMask;
+ private UInt32 _hashSizeSum = 0;
- bool HASH_ARRAY = true;
+ private bool HASH_ARRAY = true;
- const UInt32 kHash2Size = 1 << 10;
- const UInt32 kHash3Size = 1 << 16;
- const UInt32 kBT2HashSize = 1 << 16;
- const UInt32 kStartMaxLen = 1;
- const UInt32 kHash3Offset = kHash2Size;
- const UInt32 kEmptyHashValue = 0;
- const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1;
+ private const UInt32 kHash2Size = 1 << 10;
+ private const UInt32 kHash3Size = 1 << 16;
+ private const UInt32 kBT2HashSize = 1 << 16;
+ private const UInt32 kStartMaxLen = 1;
+ private const UInt32 kHash3Offset = kHash2Size;
+ private const UInt32 kEmptyHashValue = 0;
+ private const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1;
- UInt32 kNumHashDirectBytes = 0;
- UInt32 kMinMatchCheck = 4;
- UInt32 kFixHashSize = kHash2Size + kHash3Size;
+ private UInt32 kNumHashDirectBytes = 0;
+ private UInt32 kMinMatchCheck = 4;
+ private UInt32 kFixHashSize = kHash2Size + kHash3Size;
public void SetType(int numHashBytes)
{
@@ -55,7 +55,10 @@ namespace SevenZip.Compression.LZ
{
base.Init();
for (UInt32 i = 0; i < _hashSizeSum; i++)
+ {
_hash[i] = kEmptyHashValue;
+ }
+
_cyclicBufferPos = 0;
ReduceOffsets(-1);
}
@@ -63,10 +66,15 @@ namespace SevenZip.Compression.LZ
public new void MovePos()
{
if (++_cyclicBufferPos >= _cyclicBufferSize)
+ {
_cyclicBufferPos = 0;
+ }
+
base.MovePos();
if (_pos == kMaxValForNormalize)
+ {
Normalize();
+ }
}
public new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); }
@@ -80,11 +88,14 @@ namespace SevenZip.Compression.LZ
UInt32 matchMaxLen, UInt32 keepAddBufferAfter)
{
if (historySize > kMaxValForNormalize - 256)
+ {
throw new Exception();
+ }
+
_cutValue = 16 + (matchMaxLen >> 1);
- UInt32 windowReservSize = (historySize + keepAddBufferBefore +
- matchMaxLen + keepAddBufferAfter) / 2 + 256;
+ UInt32 windowReservSize = ((historySize + keepAddBufferBefore +
+ matchMaxLen + keepAddBufferAfter) / 2) + 256;
base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize);
@@ -92,7 +103,9 @@ namespace SevenZip.Compression.LZ
UInt32 cyclicBufferSize = historySize + 1;
if (_cyclicBufferSize != cyclicBufferSize)
+ {
_son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2];
+ }
UInt32 hs = kBT2HashSize;
@@ -106,20 +119,27 @@ namespace SevenZip.Compression.LZ
hs >>= 1;
hs |= 0xFFFF;
if (hs > (1 << 24))
+ {
hs >>= 1;
+ }
+
_hashMask = hs;
hs++;
hs += kFixHashSize;
}
if (hs != _hashSizeSum)
+ {
_hash = new UInt32[_hashSizeSum = hs];
+ }
}
public UInt32 GetMatches(UInt32[] distances)
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
+ {
lenLimit = _matchMaxLen;
+ }
else
{
lenLimit = _streamPos - _pos;
@@ -145,7 +165,9 @@ namespace SevenZip.Compression.LZ
hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask;
}
else
+ {
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
+ }
UInt32 curMatch = _hash[kFixHashSize + hashValue];
if (HASH_ARRAY)
@@ -155,20 +177,29 @@ namespace SevenZip.Compression.LZ
_hash[hash2Value] = _pos;
_hash[kHash3Offset + hash3Value] = _pos;
if (curMatch2 > matchMinPos)
+ {
if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur])
{
distances[offset++] = maxLen = 2;
distances[offset++] = _pos - curMatch2 - 1;
}
+ }
+
if (curMatch3 > matchMinPos)
+ {
if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur])
{
if (curMatch3 == curMatch2)
+ {
offset -= 2;
+ }
+
distances[offset++] = maxLen = 3;
distances[offset++] = _pos - curMatch3 - 1;
curMatch2 = curMatch3;
}
+ }
+
if (offset != 0 && curMatch2 == curMatch)
{
offset -= 2;
@@ -216,8 +247,13 @@ namespace SevenZip.Compression.LZ
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
+ {
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
+ {
break;
+ }
+ }
+
if (maxLen < len)
{
distances[offset++] = maxLen = len;
@@ -255,7 +291,9 @@ namespace SevenZip.Compression.LZ
{
UInt32 lenLimit;
if (_pos + _matchMaxLen <= _streamPos)
+ {
lenLimit = _matchMaxLen;
+ }
else
{
lenLimit = _streamPos - _pos;
@@ -282,7 +320,9 @@ namespace SevenZip.Compression.LZ
hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask;
}
else
+ {
hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8);
+ }
UInt32 curMatch = _hash[kFixHashSize + hashValue];
_hash[kFixHashSize + hashValue] = _pos;
@@ -312,8 +352,13 @@ namespace SevenZip.Compression.LZ
if (_bufferBase[pby1 + len] == _bufferBase[cur + len])
{
while (++len != lenLimit)
+ {
if (_bufferBase[pby1 + len] != _bufferBase[cur + len])
+ {
break;
+ }
+ }
+
if (len == lenLimit)
{
_son[ptr1] = _son[cyclicPos];
@@ -341,20 +386,25 @@ namespace SevenZip.Compression.LZ
while (--num != 0);
}
- void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue)
+ private void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue)
{
for (UInt32 i = 0; i < numItems; i++)
{
UInt32 value = items[i];
if (value <= subValue)
+ {
value = kEmptyHashValue;
+ }
else
+ {
value -= subValue;
+ }
+
items[i] = value;
}
}
- void Normalize()
+ private void Normalize()
{
UInt32 subValue = _pos - _cyclicBufferSize;
NormalizeLinks(_son, _cyclicBufferSize * 2, subValue);
diff --git a/7zip/Compress/LZ/LzInWindow.cs b/7zip/Compress/LZ/LzInWindow.cs
index e444c9c..6b18168 100644
--- a/7zip/Compress/LZ/LzInWindow.cs
+++ b/7zip/Compress/LZ/LzInWindow.cs
@@ -7,62 +7,77 @@ namespace SevenZip.Compression.LZ
public class InWindow
{
public Byte[] _bufferBase = null; // pointer to buffer with data
- System.IO.Stream _stream;
- UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done
- bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream
+ private System.IO.Stream _stream;
+ private UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done
+ private bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream
- UInt32 _pointerToLastSafePosition;
+ private UInt32 _pointerToLastSafePosition;
public UInt32 _bufferOffset;
public UInt32 _blockSize; // Size of Allocated memory block
public UInt32 _pos; // offset (from _buffer) of curent byte
- UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos
- UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos
+ private UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos
+ private UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos
public UInt32 _streamPos; // offset (from _buffer) of first not read byte from Stream
public void MoveBlock()
{
- UInt32 offset = (UInt32)(_bufferOffset) + _pos - _keepSizeBefore;
+ UInt32 offset = _bufferOffset + _pos - _keepSizeBefore;
// we need one additional byte, since MovePos moves on 1 byte.
if (offset > 0)
+ {
offset--;
+ }
- UInt32 numBytes = (UInt32)(_bufferOffset) + _streamPos - offset;
+ UInt32 numBytes = _bufferOffset + _streamPos - offset;
// check negative offset ????
for (UInt32 i = 0; i < numBytes; i++)
+ {
_bufferBase[i] = _bufferBase[offset + i];
+ }
+
_bufferOffset -= offset;
}
public virtual void ReadBlock()
{
if (_streamEndWasReached)
+ {
return;
+ }
+
while (true)
{
int size = (int)((0 - _bufferOffset) + _blockSize - _streamPos);
if (size == 0)
+ {
return;
+ }
+
int numReadBytes = _stream.Read(_bufferBase, (int)(_bufferOffset + _streamPos), size);
if (numReadBytes == 0)
{
_posLimit = _streamPos;
UInt32 pointerToPostion = _bufferOffset + _posLimit;
if (pointerToPostion > _pointerToLastSafePosition)
- _posLimit = (UInt32)(_pointerToLastSafePosition - _bufferOffset);
+ {
+ _posLimit = _pointerToLastSafePosition - _bufferOffset;
+ }
_streamEndWasReached = true;
return;
}
_streamPos += (UInt32)numReadBytes;
if (_streamPos >= _pos + _keepSizeAfter)
+ {
_posLimit = _streamPos - _keepSizeAfter;
+ }
}
}
- void Free() { _bufferBase = null; }
+ private void Free() { _bufferBase = null; }
public void Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv)
{
@@ -97,7 +112,10 @@ namespace SevenZip.Compression.LZ
{
UInt32 pointerToPostion = _bufferOffset + _pos;
if (pointerToPostion > _pointerToLastSafePosition)
+ {
MoveBlock();
+ }
+
ReadBlock();
}
}
@@ -108,14 +126,22 @@ namespace SevenZip.Compression.LZ
public UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit)
{
if (_streamEndWasReached)
- if ((_pos + index) + limit > _streamPos)
+ {
+ if (_pos + index + limit > _streamPos)
+ {
limit = _streamPos - (UInt32)(_pos + index);
+ }
+ }
+
distance++;
// Byte *pby = _buffer + (size_t)_pos + index;
UInt32 pby = _bufferOffset + _pos + (UInt32)index;
UInt32 i;
- for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++) ;
+ for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++)
+ {
+ }
+
return i;
}
diff --git a/7zip/Compress/LZ/LzOutWindow.cs b/7zip/Compress/LZ/LzOutWindow.cs
index 23e3b67..24bbd49 100644
--- a/7zip/Compress/LZ/LzOutWindow.cs
+++ b/7zip/Compress/LZ/LzOutWindow.cs
@@ -4,11 +4,11 @@ namespace SevenZip.Compression.LZ
{
public class OutWindow
{
- byte[] _buffer = null;
- uint _pos;
- uint _windowSize = 0;
- uint _streamPos;
- System.IO.Stream _stream;
+ private byte[] _buffer = null;
+ private uint _pos;
+ private uint _windowSize = 0;
+ private uint _streamPos;
+ private System.IO.Stream _stream;
public uint TrainSize = 0;
@@ -47,15 +47,23 @@ namespace SevenZip.Compression.LZ
{
uint curSize = _windowSize - _pos;
if (size < curSize)
+ {
curSize = size;
+ }
+
int numReadBytes = stream.Read(_buffer, (int)_pos, (int)curSize);
if (numReadBytes == 0)
+ {
return false;
+ }
+
size -= (uint)numReadBytes;
_pos += (uint)numReadBytes;
_streamPos += (uint)numReadBytes;
if (_pos == _windowSize)
+ {
_streamPos = _pos = 0;
+ }
}
return true;
}
@@ -70,10 +78,16 @@ namespace SevenZip.Compression.LZ
{
uint size = _pos - _streamPos;
if (size == 0)
+ {
return;
+ }
+
_stream.Write(_buffer, (int)_streamPos, (int)size);
if (_pos >= _windowSize)
+ {
_pos = 0;
+ }
+
_streamPos = _pos;
}
@@ -81,14 +95,22 @@ namespace SevenZip.Compression.LZ
{
uint pos = _pos - distance - 1;
if (pos >= _windowSize)
+ {
pos += _windowSize;
+ }
+
for (; len > 0; len--)
{
if (pos >= _windowSize)
+ {
pos = 0;
+ }
+
_buffer[_pos++] = _buffer[pos++];
if (_pos >= _windowSize)
+ {
Flush();
+ }
}
}
@@ -96,14 +118,19 @@ namespace SevenZip.Compression.LZ
{
_buffer[_pos++] = b;
if (_pos >= _windowSize)
+ {
Flush();
+ }
}
public byte GetByte(uint distance)
{
uint pos = _pos - distance - 1;
if (pos >= _windowSize)
+ {
pos += _windowSize;
+ }
+
return _buffer[pos];
}
}
diff --git a/7zip/Compress/LZMA/LzmaBase.cs b/7zip/Compress/LZMA/LzmaBase.cs
index 3692c21..61b35ee 100644
--- a/7zip/Compress/LZMA/LzmaBase.cs
+++ b/7zip/Compress/LZMA/LzmaBase.cs
@@ -18,9 +18,18 @@ namespace SevenZip.Compression.LZMA
public void Init() { Index = 0; }
public void UpdateChar()
{
- if (Index < 4) Index = 0;
- else if (Index < 10) Index -= 3;
- else Index -= 6;
+ if (Index < 4)
+ {
+ Index = 0;
+ }
+ else if (Index < 10)
+ {
+ Index -= 3;
+ }
+ else
+ {
+ Index -= 6;
+ }
}
public void UpdateMatch() { Index = (uint)(Index < 7 ? 7 : 10); }
public void UpdateRep() { Index = (uint)(Index < 7 ? 8 : 11); }
@@ -42,8 +51,11 @@ namespace SevenZip.Compression.LZMA
{
len -= kMatchMinLen;
if (len < kNumLenToPosStates)
+ {
return len;
- return (uint)(kNumLenToPosStates - 1);
+ }
+
+ return kNumLenToPosStates - 1;
}
public const int kNumAlignBits = 4;
diff --git a/7zip/Compress/LZMA/LzmaDecoder.cs b/7zip/Compress/LZMA/LzmaDecoder.cs
index c4a50ff..a67d349 100644
--- a/7zip/Compress/LZMA/LzmaDecoder.cs
+++ b/7zip/Compress/LZMA/LzmaDecoder.cs
@@ -9,14 +9,14 @@ namespace SevenZip.Compression.LZMA
public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream
{
- class LenDecoder
+ private class LenDecoder
{
- BitDecoder m_Choice = new BitDecoder();
- BitDecoder m_Choice2 = new BitDecoder();
- BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax];
- BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax];
- BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits);
- uint m_NumPosStates = 0;
+ private BitDecoder m_Choice = new();
+ private BitDecoder m_Choice2 = new();
+ private readonly BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax];
+ private readonly BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax];
+ private readonly BitTreeDecoder m_HighCoder = new(Base.kNumHighLenBits);
+ private uint m_NumPosStates = 0;
public void Create(uint numPosStates)
{
@@ -43,12 +43,16 @@ namespace SevenZip.Compression.LZMA
public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState)
{
if (m_Choice.Decode(rangeDecoder) == 0)
+ {
return m_LowCoder[posState].Decode(rangeDecoder);
+ }
else
{
uint symbol = Base.kNumLowLenSymbols;
if (m_Choice2.Decode(rangeDecoder) == 0)
+ {
symbol += m_MidCoder[posState].Decode(rangeDecoder);
+ }
else
{
symbol += Base.kNumMidLenSymbols;
@@ -59,19 +63,25 @@ namespace SevenZip.Compression.LZMA
}
}
- class LiteralDecoder
+ private class LiteralDecoder
{
- struct Decoder2
+ private struct Decoder2
{
- BitDecoder[] m_Decoders;
+ private BitDecoder[] m_Decoders;
public void Create() { m_Decoders = new BitDecoder[0x300]; }
- public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); }
+ public void Init() { for (int i = 0; i < 0x300; i++)
+ {
+ m_Decoders[i].Init();
+ }
+ }
public byte DecodeNormal(RangeCoder.Decoder rangeDecoder)
{
uint symbol = 1;
do
+ {
symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder);
+ }
while (symbol < 0x100);
return (byte)symbol;
}
@@ -88,7 +98,10 @@ namespace SevenZip.Compression.LZMA
if (matchBit != bit)
{
while (symbol < 0x100)
+ {
symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder);
+ }
+
break;
}
}
@@ -97,33 +110,40 @@ namespace SevenZip.Compression.LZMA
}
}
- Decoder2[] m_Coders;
- int m_NumPrevBits;
- int m_NumPosBits;
- uint m_PosMask;
+ private Decoder2[] m_Coders;
+ private int m_NumPrevBits;
+ private int m_NumPosBits;
+ private uint m_PosMask;
public void Create(int numPosBits, int numPrevBits)
{
if (m_Coders != null && m_NumPrevBits == numPrevBits &&
m_NumPosBits == numPosBits)
+ {
return;
+ }
+
m_NumPosBits = numPosBits;
m_PosMask = ((uint)1 << numPosBits) - 1;
m_NumPrevBits = numPrevBits;
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
m_Coders = new Decoder2[numStates];
for (uint i = 0; i < numStates; i++)
+ {
m_Coders[i].Create();
+ }
}
public void Init()
{
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
for (uint i = 0; i < numStates; i++)
+ {
m_Coders[i].Init();
+ }
}
- uint GetState(uint pos, byte prevByte)
+ private uint GetState(uint pos, byte prevByte)
{ return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); }
public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte)
@@ -133,70 +153,81 @@ namespace SevenZip.Compression.LZMA
{ return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); }
};
- LZ.OutWindow m_OutWindow = new LZ.OutWindow();
- RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder();
+ private readonly LZ.OutWindow m_OutWindow = new();
+ private readonly RangeCoder.Decoder m_RangeDecoder = new();
- BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
- BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates];
- BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates];
- BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates];
- BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates];
- BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
+ private readonly BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
+ private readonly BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates];
+ private readonly BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates];
+ private readonly BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates];
+ private readonly BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates];
+ private readonly BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
- BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates];
- BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex];
+ private readonly BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates];
+ private readonly BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex];
- BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits);
+ private readonly BitTreeDecoder m_PosAlignDecoder = new(Base.kNumAlignBits);
- LenDecoder m_LenDecoder = new LenDecoder();
- LenDecoder m_RepLenDecoder = new LenDecoder();
+ private readonly LenDecoder m_LenDecoder = new();
+ private readonly LenDecoder m_RepLenDecoder = new();
- LiteralDecoder m_LiteralDecoder = new LiteralDecoder();
+ private readonly LiteralDecoder m_LiteralDecoder = new();
- uint m_DictionarySize;
- uint m_DictionarySizeCheck;
+ private uint m_DictionarySize;
+ private uint m_DictionarySizeCheck;
- uint m_PosStateMask;
+ private uint m_PosStateMask;
public Decoder()
{
m_DictionarySize = 0xFFFFFFFF;
for (int i = 0; i < Base.kNumLenToPosStates; i++)
+ {
m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits);
+ }
}
- void SetDictionarySize(uint dictionarySize)
+ private void SetDictionarySize(uint dictionarySize)
{
if (m_DictionarySize != dictionarySize)
{
m_DictionarySize = dictionarySize;
m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1);
- uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12));
+ uint blockSize = Math.Max(m_DictionarySizeCheck, 1 << 12);
m_OutWindow.Create(blockSize);
}
}
- void SetLiteralProperties(int lp, int lc)
+ private void SetLiteralProperties(int lp, int lc)
{
if (lp > 8)
+ {
throw new InvalidParamException();
+ }
+
if (lc > 8)
+ {
throw new InvalidParamException();
+ }
+
m_LiteralDecoder.Create(lp, lc);
}
- void SetPosBitsProperties(int pb)
+ private void SetPosBitsProperties(int pb)
{
if (pb > Base.kNumPosStatesBitsMax)
+ {
throw new InvalidParamException();
+ }
+
uint numPosStates = (uint)1 << pb;
m_LenDecoder.Create(numPosStates);
m_RepLenDecoder.Create(numPosStates);
m_PosStateMask = numPosStates - 1;
}
- bool _solid = false;
- void Init(System.IO.Stream inStream, System.IO.Stream outStream)
+ private bool _solid = false;
+ private void Init(System.IO.Stream inStream, System.IO.Stream outStream)
{
m_RangeDecoder.Init(inStream);
m_OutWindow.Init(outStream, _solid);
@@ -218,10 +249,14 @@ namespace SevenZip.Compression.LZMA
m_LiteralDecoder.Init();
for (i = 0; i < Base.kNumLenToPosStates; i++)
+ {
m_PosSlotDecoder[i].Init();
+ }
// m_PosSpecDecoder.Init();
for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++)
+ {
m_PosDecoders[i].Init();
+ }
m_LenDecoder.Init();
m_RepLenDecoder.Init();
@@ -233,7 +268,7 @@ namespace SevenZip.Compression.LZMA
{
Init(inStream, outStream);
- Base.State state = new Base.State();
+ Base.State state = new();
state.Init();
uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0;
@@ -242,7 +277,10 @@ namespace SevenZip.Compression.LZMA
if (nowPos64 < outSize64)
{
if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0)
+ {
throw new DataErrorException();
+ }
+
state.UpdateChar();
byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0);
m_OutWindow.PutByte(b);
@@ -263,11 +301,11 @@ namespace SevenZip.Compression.LZMA
{
byte b;
byte prevByte = m_OutWindow.GetByte(0);
- if (!state.IsCharState())
- b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder,
- (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0));
- else
- b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte);
+ b = !state.IsCharState()
+ ? m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder,
+ (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0))
+ : m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte);
+
m_OutWindow.PutByte(b);
state.UpdateChar();
nowPos64++;
@@ -297,7 +335,9 @@ namespace SevenZip.Compression.LZMA
else
{
if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0)
+ {
distance = rep2;
+ }
else
{
distance = rep3;
@@ -324,8 +364,10 @@ namespace SevenZip.Compression.LZMA
int numDirectBits = (int)((posSlot >> 1) - 1);
rep0 = ((2 | (posSlot & 1)) << numDirectBits);
if (posSlot < Base.kEndPosModelIndex)
+ {
rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders,
- rep0 - posSlot - 1, m_RangeDecoder, numDirectBits);
+ rep0 - posSlot - 1, m_RangeDecoder, numDirectBits);
+ }
else
{
rep0 += (m_RangeDecoder.DecodeDirectBits(
@@ -334,12 +376,17 @@ namespace SevenZip.Compression.LZMA
}
}
else
+ {
rep0 = posSlot;
+ }
}
if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck)
{
if (rep0 == 0xFFFFFFFF)
+ {
break;
+ }
+
throw new DataErrorException();
}
m_OutWindow.CopyBlock(rep0, len);
@@ -350,7 +397,6 @@ namespace SevenZip.Compression.LZMA
}
catch (OperationCanceledException)
{
-
}
m_OutWindow.Flush();
@@ -361,16 +407,25 @@ namespace SevenZip.Compression.LZMA
public void SetDecoderProperties(byte[] properties)
{
if (properties.Length < 5)
+ {
throw new InvalidParamException();
+ }
+
int lc = properties[0] % 9;
int remainder = properties[0] / 9;
int lp = remainder % 5;
int pb = remainder / 5;
if (pb > Base.kNumPosStatesBitsMax)
+ {
throw new InvalidParamException();
+ }
+
UInt32 dictionarySize = 0;
for (int i = 0; i < 4; i++)
+ {
dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8);
+ }
+
SetDictionarySize(dictionarySize);
SetLiteralProperties(lp, lc);
SetPosBitsProperties(pb);
diff --git a/7zip/Compress/LZMA/LzmaEncoder.cs b/7zip/Compress/LZMA/LzmaEncoder.cs
index f07afbd..7281099 100644
--- a/7zip/Compress/LZMA/LzmaEncoder.cs
+++ b/7zip/Compress/LZMA/LzmaEncoder.cs
@@ -9,15 +9,15 @@ namespace SevenZip.Compression.LZMA
public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties
{
- enum EMatchFinderType
+ private enum EMatchFinderType
{
BT2,
BT4,
};
- const UInt32 kIfinityPrice = 0xFFFFFFF;
+ private const UInt32 kIfinityPrice = 0xFFFFFFF;
- static Byte[] g_FastPos = new Byte[1 << 11];
+ private static readonly Byte[] g_FastPos = new Byte[1 << 11];
static Encoder()
{
@@ -29,52 +29,72 @@ namespace SevenZip.Compression.LZMA
{
UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1));
for (UInt32 j = 0; j < k; j++, c++)
+ {
g_FastPos[c] = slotFast;
+ }
}
}
- static UInt32 GetPosSlot(UInt32 pos)
+ private static UInt32 GetPosSlot(UInt32 pos)
{
if (pos < (1 << 11))
+ {
return g_FastPos[pos];
+ }
+
if (pos < (1 << 21))
+ {
return (UInt32)(g_FastPos[pos >> 10] + 20);
+ }
+
return (UInt32)(g_FastPos[pos >> 20] + 40);
}
- static UInt32 GetPosSlot2(UInt32 pos)
+ private static UInt32 GetPosSlot2(UInt32 pos)
{
if (pos < (1 << 17))
+ {
return (UInt32)(g_FastPos[pos >> 6] + 12);
+ }
+
if (pos < (1 << 27))
+ {
return (UInt32)(g_FastPos[pos >> 16] + 32);
+ }
+
return (UInt32)(g_FastPos[pos >> 26] + 52);
}
- Base.State _state = new Base.State();
- Byte _previousByte;
- UInt32[] _repDistances = new UInt32[Base.kNumRepDistances];
+ private Base.State _state = new();
+ private Byte _previousByte;
+ private readonly UInt32[] _repDistances = new UInt32[Base.kNumRepDistances];
- void BaseInit()
+ private void BaseInit()
{
_state.Init();
_previousByte = 0;
for (UInt32 i = 0; i < Base.kNumRepDistances; i++)
+ {
_repDistances[i] = 0;
+ }
}
- const int kDefaultDictionaryLogSize = 22;
- const UInt32 kNumFastBytesDefault = 0x20;
+ private const int kDefaultDictionaryLogSize = 22;
+ private const UInt32 kNumFastBytesDefault = 0x20;
- class LiteralEncoder
+ private class LiteralEncoder
{
public struct Encoder2
{
- BitEncoder[] m_Encoders;
+ private BitEncoder[] m_Encoders;
public void Create() { m_Encoders = new BitEncoder[0x300]; }
- public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); }
+ public void Init() { for (int i = 0; i < 0x300; i++)
+ {
+ m_Encoders[i].Init();
+ }
+ }
public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol)
{
@@ -136,49 +156,56 @@ namespace SevenZip.Compression.LZMA
}
}
- Encoder2[] m_Coders;
- int m_NumPrevBits;
- int m_NumPosBits;
- uint m_PosMask;
+ private Encoder2[] m_Coders;
+ private int m_NumPrevBits;
+ private int m_NumPosBits;
+ private uint m_PosMask;
public void Create(int numPosBits, int numPrevBits)
{
if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits)
+ {
return;
+ }
+
m_NumPosBits = numPosBits;
m_PosMask = ((uint)1 << numPosBits) - 1;
m_NumPrevBits = numPrevBits;
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
m_Coders = new Encoder2[numStates];
for (uint i = 0; i < numStates; i++)
+ {
m_Coders[i].Create();
+ }
}
public void Init()
{
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
for (uint i = 0; i < numStates; i++)
+ {
m_Coders[i].Init();
+ }
}
public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte)
{ return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; }
}
- class LenEncoder
+ private class LenEncoder
{
- RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder();
- RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder();
- RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
- RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
- RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits);
+ private BitEncoder _choice = new();
+ private BitEncoder _choice2 = new();
+ private readonly BitTreeEncoder[] _lowCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax];
+ private readonly BitTreeEncoder[] _midCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax];
+ private readonly BitTreeEncoder _highCoder = new(Base.kNumHighLenBits);
public LenEncoder()
{
for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++)
{
- _lowCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumLowLenBits);
- _midCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumMidLenBits);
+ _lowCoder[posState] = new BitTreeEncoder(Base.kNumLowLenBits);
+ _midCoder[posState] = new BitTreeEncoder(Base.kNumMidLenBits);
}
}
@@ -228,36 +255,44 @@ namespace SevenZip.Compression.LZMA
for (i = 0; i < Base.kNumLowLenSymbols; i++)
{
if (i >= numSymbols)
+ {
return;
+ }
+
prices[st + i] = a0 + _lowCoder[posState].GetPrice(i);
}
for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++)
{
if (i >= numSymbols)
+ {
return;
+ }
+
prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols);
}
for (; i < numSymbols; i++)
+ {
prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols);
+ }
}
};
- const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols;
+ private const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols;
- class LenPriceTableEncoder : LenEncoder
+ private class LenPriceTableEncoder : LenEncoder
{
- UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax];
- UInt32 _tableSize;
- UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax];
+ private readonly UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax];
+ private UInt32 _tableSize;
+ private readonly UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax];
public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; }
public UInt32 GetPrice(UInt32 symbol, UInt32 posState)
{
- return _prices[posState * Base.kNumLenSymbols + symbol];
+ return _prices[(posState * Base.kNumLenSymbols) + symbol];
}
- void UpdateTable(UInt32 posState)
+ private void UpdateTable(UInt32 posState)
{
SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols);
_counters[posState] = _tableSize;
@@ -266,19 +301,23 @@ namespace SevenZip.Compression.LZMA
public void UpdateTables(UInt32 numPosStates)
{
for (UInt32 posState = 0; posState < numPosStates; posState++)
+ {
UpdateTable(posState);
+ }
}
public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
{
base.Encode(rangeEncoder, symbol, posState);
if (--_counters[posState] == 0)
+ {
UpdateTable(posState);
+ }
}
}
- const UInt32 kNumOpts = 1 << 12;
- class Optimal
+ private const UInt32 kNumOpts = 1 << 12;
+ private class Optimal
{
public Base.State State;
@@ -298,83 +337,89 @@ namespace SevenZip.Compression.LZMA
public UInt32 Backs3;
public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; }
- public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; }
- public bool IsShortRep() { return (BackPrev == 0); }
+ public void MakeAsShortRep() { BackPrev = 0; Prev1IsChar = false; }
+ public bool IsShortRep() { return BackPrev == 0; }
};
- Optimal[] _optimum = new Optimal[kNumOpts];
- LZ.IMatchFinder _matchFinder = null;
- RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder();
+ private readonly Optimal[] _optimum = new Optimal[kNumOpts];
+ private LZ.IMatchFinder _matchFinder = null;
+ private readonly RangeCoder.Encoder _rangeEncoder = new();
- RangeCoder.BitEncoder[] _isMatch = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
- RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates];
- RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates];
- RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates];
- RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates];
- RangeCoder.BitEncoder[] _isRep0Long = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
+ private readonly BitEncoder[] _isMatch = new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
+ private readonly BitEncoder[] _isRep = new BitEncoder[Base.kNumStates];
+ private readonly BitEncoder[] _isRepG0 = new BitEncoder[Base.kNumStates];
+ private readonly BitEncoder[] _isRepG1 = new BitEncoder[Base.kNumStates];
+ private readonly BitEncoder[] _isRepG2 = new BitEncoder[Base.kNumStates];
+ private readonly BitEncoder[] _isRep0Long = new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
- RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates];
+ private readonly BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[Base.kNumLenToPosStates];
- RangeCoder.BitEncoder[] _posEncoders = new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex];
- RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits);
+ private readonly BitEncoder[] _posEncoders = new BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex];
+ private readonly BitTreeEncoder _posAlignEncoder = new(Base.kNumAlignBits);
- LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder();
- LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder();
+ private readonly LenPriceTableEncoder _lenEncoder = new();
+ private readonly LenPriceTableEncoder _repMatchLenEncoder = new();
- LiteralEncoder _literalEncoder = new LiteralEncoder();
+ private readonly LiteralEncoder _literalEncoder = new();
- UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2];
+ private readonly UInt32[] _matchDistances = new UInt32[(Base.kMatchMaxLen * 2) + 2];
- UInt32 _numFastBytes = kNumFastBytesDefault;
- UInt32 _longestMatchLength;
- UInt32 _numDistancePairs;
+ private UInt32 _numFastBytes = kNumFastBytesDefault;
+ private UInt32 _longestMatchLength;
+ private UInt32 _numDistancePairs;
- UInt32 _additionalOffset;
+ private UInt32 _additionalOffset;
- UInt32 _optimumEndIndex;
- UInt32 _optimumCurrentIndex;
+ private UInt32 _optimumEndIndex;
+ private UInt32 _optimumCurrentIndex;
- bool _longestMatchWasFound;
+ private bool _longestMatchWasFound;
- UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)];
- UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits];
- UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize];
- UInt32 _alignPriceCount;
+ private readonly UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)];
+ private readonly UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits];
+ private readonly UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize];
+ private UInt32 _alignPriceCount;
- UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2);
+ private UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2);
- int _posStateBits = 2;
- UInt32 _posStateMask = (4 - 1);
- int _numLiteralPosStateBits = 0;
- int _numLiteralContextBits = 3;
+ private int _posStateBits = 2;
+ private UInt32 _posStateMask = (4 - 1);
+ private int _numLiteralPosStateBits = 0;
+ private int _numLiteralContextBits = 3;
- UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize);
- UInt32 _dictionarySizePrev = 0xFFFFFFFF;
- UInt32 _numFastBytesPrev = 0xFFFFFFFF;
+ private UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize);
+ private UInt32 _dictionarySizePrev = 0xFFFFFFFF;
+ private UInt32 _numFastBytesPrev = 0xFFFFFFFF;
- Int64 nowPos64;
- bool _finished;
- System.IO.Stream _inStream;
+ private Int64 nowPos64;
+ private bool _finished;
+ private System.IO.Stream _inStream;
- EMatchFinderType _matchFinderType = EMatchFinderType.BT4;
- bool _writeEndMark = false;
+ private EMatchFinderType _matchFinderType = EMatchFinderType.BT4;
+ private bool _writeEndMark = false;
- bool _needReleaseMFStream;
+ private bool _needReleaseMFStream;
- void Create()
+ private void Create()
{
if (_matchFinder == null)
{
- LZ.BinTree bt = new LZ.BinTree();
+ LZ.BinTree bt = new();
int numHashBytes = 4;
if (_matchFinderType == EMatchFinderType.BT2)
+ {
numHashBytes = 2;
+ }
+
bt.SetType(numHashBytes);
_matchFinder = bt;
}
_literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits);
if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes)
+ {
return;
+ }
+
_matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1);
_dictionarySizePrev = _dictionarySize;
_numFastBytesPrev = _numFastBytes;
@@ -383,17 +428,22 @@ namespace SevenZip.Compression.LZMA
public Encoder()
{
for (int i = 0; i < kNumOpts; i++)
+ {
_optimum[i] = new Optimal();
+ }
+
for (int i = 0; i < Base.kNumLenToPosStates; i++)
- _posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits);
+ {
+ _posSlotEncoder[i] = new BitTreeEncoder(Base.kNumPosSlotBits);
+ }
}
- void SetWriteEndMarkerMode(bool writeEndMarker)
+ private void SetWriteEndMarkerMode(bool writeEndMarker)
{
_writeEndMark = writeEndMarker;
}
- void Init()
+ private void Init()
{
BaseInit();
_rangeEncoder.Init();
@@ -414,9 +464,14 @@ namespace SevenZip.Compression.LZMA
}
_literalEncoder.Init();
for (i = 0; i < Base.kNumLenToPosStates; i++)
+ {
_posSlotEncoder[i].Init();
+ }
+
for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++)
+ {
_posEncoders[i].Init();
+ }
_lenEncoder.Init((UInt32)1 << _posStateBits);
_repMatchLenEncoder.Init((UInt32)1 << _posStateBits);
@@ -429,7 +484,7 @@ namespace SevenZip.Compression.LZMA
_additionalOffset = 0;
}
- void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs)
+ private void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs)
{
lenRes = 0;
numDistancePairs = _matchFinder.GetMatches(_matchDistances);
@@ -437,14 +492,15 @@ namespace SevenZip.Compression.LZMA
{
lenRes = _matchDistances[numDistancePairs - 2];
if (lenRes == _numFastBytes)
+ {
lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1],
Base.kMatchMaxLen - lenRes);
+ }
}
_additionalOffset++;
}
-
- void MovePos(UInt32 num)
+ private void MovePos(UInt32 num)
{
if (num > 0)
{
@@ -453,13 +509,13 @@ namespace SevenZip.Compression.LZMA
}
}
- UInt32 GetRepLen1Price(Base.State state, UInt32 posState)
+ private UInt32 GetRepLen1Price(Base.State state, UInt32 posState)
{
return _isRepG0[state.Index].GetPrice0() +
_isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0();
}
- UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState)
+ private UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState)
{
UInt32 price;
if (repIndex == 0)
@@ -471,7 +527,9 @@ namespace SevenZip.Compression.LZMA
{
price = _isRepG0[state.Index].GetPrice1();
if (repIndex == 1)
+ {
price += _isRepG1[state.Index].GetPrice0();
+ }
else
{
price += _isRepG1[state.Index].GetPrice1();
@@ -481,25 +539,25 @@ namespace SevenZip.Compression.LZMA
return price;
}
- UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState)
+ private UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState)
{
UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
return price + GetPureRepPrice(repIndex, state, posState);
}
- UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState)
+ private UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState)
{
UInt32 price;
UInt32 lenToPosState = Base.GetLenToPosState(len);
- if (pos < Base.kNumFullDistances)
- price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos];
- else
- price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] +
- _alignPrices[pos & Base.kAlignMask];
+ price = pos < Base.kNumFullDistances
+ ? _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]
+ : _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] +
+ _alignPrices[pos & Base.kAlignMask];
+
return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
}
- UInt32 Backward(out UInt32 backRes, UInt32 cur)
+ private UInt32 Backward(out UInt32 backRes, UInt32 cur)
{
_optimumEndIndex = cur;
UInt32 posMem = _optimum[cur].PosPrev;
@@ -533,11 +591,10 @@ namespace SevenZip.Compression.LZMA
return _optimumCurrentIndex;
}
- UInt32[] reps = new UInt32[Base.kNumRepDistances];
- UInt32[] repLens = new UInt32[Base.kNumRepDistances];
+ private readonly UInt32[] reps = new UInt32[Base.kNumRepDistances];
+ private readonly UInt32[] repLens = new UInt32[Base.kNumRepDistances];
-
- UInt32 GetOptimum(UInt32 position, out UInt32 backRes)
+ private UInt32 GetOptimum(UInt32 position, out UInt32 backRes)
{
if (_optimumEndIndex != _optimumCurrentIndex)
{
@@ -567,7 +624,9 @@ namespace SevenZip.Compression.LZMA
return 1;
}
if (numAvailableBytes > Base.kMatchMaxLen)
+ {
numAvailableBytes = Base.kMatchMaxLen;
+ }
UInt32 repMaxIndex = 0;
UInt32 i;
@@ -576,7 +635,9 @@ namespace SevenZip.Compression.LZMA
reps[i] = _repDistances[i];
repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen);
if (repLens[i] > repLens[repMaxIndex])
+ {
repMaxIndex = i;
+ }
}
if (repLens[repMaxIndex] >= _numFastBytes)
{
@@ -598,7 +659,7 @@ namespace SevenZip.Compression.LZMA
if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2)
{
- backRes = (UInt32)0xFFFFFFFF;
+ backRes = 0xFFFFFFFF;
return 1;
}
@@ -640,14 +701,19 @@ namespace SevenZip.Compression.LZMA
UInt32 len = lenEnd;
do
+ {
_optimum[len--].Price = kIfinityPrice;
+ }
while (len >= 2);
for (i = 0; i < Base.kNumRepDistances; i++)
{
UInt32 repLen = repLens[i];
if (repLen < 2)
+ {
continue;
+ }
+
UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState);
do
{
@@ -671,7 +737,10 @@ namespace SevenZip.Compression.LZMA
{
UInt32 offs = 0;
while (len > _matchDistances[offs])
+ {
offs += 2;
+ }
+
for (; ; len++)
{
UInt32 distance = _matchDistances[offs + 1];
@@ -688,7 +757,9 @@ namespace SevenZip.Compression.LZMA
{
offs += 2;
if (offs == numDistancePairs)
+ {
break;
+ }
}
}
}
@@ -699,9 +770,11 @@ namespace SevenZip.Compression.LZMA
{
cur++;
if (cur == lenEnd)
+ {
return Backward(out backRes, cur);
- UInt32 newLen;
- ReadMatchDistances(out newLen, out numDistancePairs);
+ }
+
+ ReadMatchDistances(out uint newLen, out numDistancePairs);
if (newLen >= _numFastBytes)
{
_numDistancePairs = numDistancePairs;
@@ -719,22 +792,36 @@ namespace SevenZip.Compression.LZMA
{
state = _optimum[_optimum[cur].PosPrev2].State;
if (_optimum[cur].BackPrev2 < Base.kNumRepDistances)
+ {
state.UpdateRep();
+ }
else
+ {
state.UpdateMatch();
+ }
}
else
+ {
state = _optimum[posPrev].State;
+ }
+
state.UpdateChar();
}
else
+ {
state = _optimum[posPrev].State;
+ }
+
if (posPrev == cur - 1)
{
if (_optimum[cur].IsShortRep())
+ {
state.UpdateShortRep();
+ }
else
+ {
state.UpdateChar();
+ }
}
else
{
@@ -749,9 +836,13 @@ namespace SevenZip.Compression.LZMA
{
pos = _optimum[cur].BackPrev;
if (pos < Base.kNumRepDistances)
+ {
state.UpdateRep();
+ }
else
+ {
state.UpdateMatch();
+ }
}
Optimal opt = _optimum[posPrev];
if (pos < Base.kNumRepDistances)
@@ -842,9 +933,15 @@ namespace SevenZip.Compression.LZMA
numAvailableBytes = numAvailableBytesFull;
if (numAvailableBytes < 2)
+ {
continue;
+ }
+
if (numAvailableBytes > _numFastBytes)
+ {
numAvailableBytes = _numFastBytes;
+ }
+
if (!nextIsChar && matchByte != currentByte)
{
// try Literal + rep0
@@ -861,7 +958,10 @@ namespace SevenZip.Compression.LZMA
{
UInt32 offset = cur + 1 + lenTest2;
while (lenEnd < offset)
+ {
_optimum[++lenEnd].Price = kIfinityPrice;
+ }
+
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(
0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[offset];
@@ -883,12 +983,18 @@ namespace SevenZip.Compression.LZMA
{
UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes);
if (lenTest < 2)
+ {
continue;
+ }
+
UInt32 lenTestTemp = lenTest;
do
{
while (lenEnd < cur + lenTest)
+ {
_optimum[++lenEnd].Price = kIfinityPrice;
+ }
+
UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState);
Optimal optimum = _optimum[cur + lenTest];
if (curAndLenPrice < optimum.Price)
@@ -903,7 +1009,9 @@ namespace SevenZip.Compression.LZMA
lenTest = lenTestTemp;
if (repIndex == 0)
+ {
startLen = lenTest + 1;
+ }
// if (_maxMode)
if (lenTest < numAvailableBytesFull)
@@ -920,7 +1028,7 @@ namespace SevenZip.Compression.LZMA
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() +
_literalEncoder.GetSubCoder(position + lenTest,
_matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true,
- _matchFinder.GetIndexByte((Int32)((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1))),
+ _matchFinder.GetIndexByte((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1)),
_matchFinder.GetIndexByte((Int32)lenTest - 1));
state2.UpdateChar();
posStateNext = (position + lenTest + 1) & _posStateMask;
@@ -931,7 +1039,10 @@ namespace SevenZip.Compression.LZMA
{
UInt32 offset = lenTest + 1 + lenTest2;
while (lenEnd < cur + offset)
+ {
_optimum[++lenEnd].Price = kIfinityPrice;
+ }
+
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
@@ -952,7 +1063,10 @@ namespace SevenZip.Compression.LZMA
if (newLen > numAvailableBytes)
{
newLen = numAvailableBytes;
- for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ;
+ for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2)
+ {
+ }
+
_matchDistances[numDistancePairs] = newLen;
numDistancePairs += 2;
}
@@ -960,11 +1074,15 @@ namespace SevenZip.Compression.LZMA
{
normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0();
while (lenEnd < cur + newLen)
+ {
_optimum[++lenEnd].Price = kIfinityPrice;
+ }
UInt32 offs = 0;
while (startLen > _matchDistances[offs])
+ {
offs += 2;
+ }
for (UInt32 lenTest = startLen; ; lenTest++)
{
@@ -1004,7 +1122,10 @@ namespace SevenZip.Compression.LZMA
UInt32 offset = lenTest + 1 + lenTest2;
while (lenEnd < cur + offset)
+ {
_optimum[++lenEnd].Price = kIfinityPrice;
+ }
+
curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
@@ -1021,39 +1142,43 @@ namespace SevenZip.Compression.LZMA
}
offs += 2;
if (offs == numDistancePairs)
+ {
break;
+ }
}
}
}
}
}
- bool ChangePair(UInt32 smallDist, UInt32 bigDist)
+ 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);
}
- void WriteEndMarker(UInt32 posState)
+ private void WriteEndMarker(UInt32 posState)
{
if (!_writeEndMark)
+ {
return;
+ }
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1);
_isRep[_state.Index].Encode(_rangeEncoder, 0);
_state.UpdateMatch();
- UInt32 len = Base.kMatchMinLen;
+ const UInt32 len = Base.kMatchMinLen;
_lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
- UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1;
+ const UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1;
UInt32 lenToPosState = Base.GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
- int footerBits = 30;
+ const int footerBits = 30;
UInt32 posReduced = (((UInt32)1) << footerBits) - 1;
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask);
}
- void Flush(UInt32 nowPos)
+ private void Flush(UInt32 nowPos)
{
ReleaseMFStream();
WriteEndMarker(nowPos & _posStateMask);
@@ -1074,13 +1199,17 @@ namespace SevenZip.Compression.LZMA
_needReleaseMFStream = true;
_inStream = null;
if (_trainSize > 0)
+ {
_matchFinder.Skip(_trainSize);
+ }
}
if (_finished)
+ {
return;
- _finished = true;
+ }
+ _finished = true;
Int64 progressPosValuePrev = nowPos64;
if (nowPos64 == 0)
@@ -1090,8 +1219,8 @@ namespace SevenZip.Compression.LZMA
Flush((UInt32)nowPos64);
return;
}
- UInt32 len, numDistancePairs; // it's not used
- ReadMatchDistances(out len, out numDistancePairs);
+ // it's not used
+ ReadMatchDistances(out uint len, out uint numDistancePairs);
UInt32 posState = (UInt32)(nowPos64) & _posStateMask;
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0);
_state.UpdateChar();
@@ -1108,8 +1237,7 @@ namespace SevenZip.Compression.LZMA
}
while (true)
{
- UInt32 pos;
- UInt32 len = GetOptimum((UInt32)nowPos64, out pos);
+ UInt32 len = GetOptimum((UInt32)nowPos64, out uint pos);
UInt32 posState = ((UInt32)nowPos64) & _posStateMask;
UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState;
@@ -1124,7 +1252,10 @@ namespace SevenZip.Compression.LZMA
subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte);
}
else
+ {
subCoder.Encode(_rangeEncoder, curByte);
+ }
+
_previousByte = curByte;
_state.UpdateChar();
}
@@ -1138,15 +1269,21 @@ namespace SevenZip.Compression.LZMA
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 0);
if (len == 1)
+ {
_isRep0Long[complexState].Encode(_rangeEncoder, 0);
+ }
else
+ {
_isRep0Long[complexState].Encode(_rangeEncoder, 1);
+ }
}
else
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 1);
if (pos == 1)
+ {
_isRepG1[_state.Index].Encode(_rangeEncoder, 0);
+ }
else
{
_isRepG1[_state.Index].Encode(_rangeEncoder, 1);
@@ -1154,7 +1291,9 @@ namespace SevenZip.Compression.LZMA
}
}
if (len == 1)
+ {
_state.UpdateShortRep();
+ }
else
{
_repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
@@ -1164,7 +1303,10 @@ namespace SevenZip.Compression.LZMA
if (pos != 0)
{
for (UInt32 i = pos; i >= 1; i--)
+ {
_repDistances[i] = _repDistances[i - 1];
+ }
+
_repDistances[0] = distance;
}
}
@@ -1185,8 +1327,10 @@ namespace SevenZip.Compression.LZMA
UInt32 posReduced = pos - baseVal;
if (posSlot < Base.kEndPosModelIndex)
+ {
RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders,
- baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced);
+ baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced);
+ }
else
{
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
@@ -1196,7 +1340,10 @@ namespace SevenZip.Compression.LZMA
}
UInt32 distance = pos;
for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--)
+ {
_repDistances[i] = _repDistances[i - 1];
+ }
+
_repDistances[0] = distance;
_matchPriceCount++;
}
@@ -1208,9 +1355,15 @@ namespace SevenZip.Compression.LZMA
{
// if (!_fastMode)
if (_matchPriceCount >= (1 << 7))
+ {
FillDistancesPrices();
+ }
+
if (_alignPriceCount >= Base.kAlignTableSize)
+ {
FillAlignPrices();
+ }
+
inSize = nowPos64;
outSize = _rangeEncoder.GetProcessedSizeAdd();
if (_matchFinder.GetNumAvailableBytes() == 0)
@@ -1229,7 +1382,7 @@ namespace SevenZip.Compression.LZMA
}
}
- void ReleaseMFStream()
+ private void ReleaseMFStream()
{
if (_matchFinder != null && _needReleaseMFStream)
{
@@ -1238,16 +1391,16 @@ namespace SevenZip.Compression.LZMA
}
}
- void SetOutStream(System.IO.Stream outStream) { _rangeEncoder.SetStream(outStream); }
- void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); }
+ private void SetOutStream(System.IO.Stream outStream) { _rangeEncoder.SetStream(outStream); }
+ private void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); }
- void ReleaseStreams()
+ private void ReleaseStreams()
{
ReleaseMFStream();
ReleaseOutStream();
}
- void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream,
+ private void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize)
{
_inStream = inStream;
@@ -1270,7 +1423,6 @@ namespace SevenZip.Compression.LZMA
nowPos64 = 0;
}
-
public void Code(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize, ICodeProgress progress, CancellationToken? token = null)
{
@@ -1281,16 +1433,13 @@ namespace SevenZip.Compression.LZMA
while (true)
{
token?.ThrowIfCancellationRequested();
- Int64 processedInSize;
- Int64 processedOutSize;
- bool finished;
- CodeOneBlock(out processedInSize, out processedOutSize, out finished);
+ CodeOneBlock(out long processedInSize, out long processedOutSize, out bool finished);
if (finished)
- return;
- if (progress != null)
{
- progress.SetProgress(processedInSize, processedOutSize);
+ return;
}
+
+ progress?.SetProgress(processedInSize, processedOutSize);
}
}
finally
@@ -1299,21 +1448,24 @@ namespace SevenZip.Compression.LZMA
}
}
- const int kPropSize = 5;
- Byte[] properties = new Byte[kPropSize];
+ private const int kPropSize = 5;
+ private readonly Byte[] properties = new Byte[kPropSize];
public void WriteCoderProperties(System.IO.Stream outStream)
{
- properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits);
+ properties[0] = (Byte)((((_posStateBits * 5) + _numLiteralPosStateBits) * 9) + _numLiteralContextBits);
for (int i = 0; i < 4; i++)
+ {
properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF);
+ }
+
outStream.Write(properties, 0, kPropSize);
}
- UInt32[] tempPrices = new UInt32[Base.kNumFullDistances];
- UInt32 _matchPriceCount;
+ private readonly UInt32[] tempPrices = new UInt32[Base.kNumFullDistances];
+ private UInt32 _matchPriceCount;
- void FillDistancesPrices()
+ private void FillDistancesPrices()
{
for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++)
{
@@ -1327,43 +1479,60 @@ namespace SevenZip.Compression.LZMA
for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++)
{
UInt32 posSlot;
- RangeCoder.BitTreeEncoder encoder = _posSlotEncoder[lenToPosState];
+ BitTreeEncoder encoder = _posSlotEncoder[lenToPosState];
UInt32 st = (lenToPosState << Base.kNumPosSlotBits);
for (posSlot = 0; posSlot < _distTableSize; posSlot++)
+ {
_posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot);
+ }
+
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) << RangeCoder.BitEncoder.kNumBitPriceShiftBits);
+ }
UInt32 st2 = lenToPosState * Base.kNumFullDistances;
UInt32 i;
for (i = 0; i < Base.kStartPosModelIndex; i++)
+ {
_distancesPrices[st2 + i] = _posSlotPrices[st + i];
+ }
+
for (; i < Base.kNumFullDistances; i++)
+ {
_distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i];
+ }
}
_matchPriceCount = 0;
}
- void FillAlignPrices()
+ private void FillAlignPrices()
{
for (UInt32 i = 0; i < Base.kAlignTableSize; i++)
+ {
_alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i);
+ }
+
_alignPriceCount = 0;
}
-
- static string[] kMatchFinderIDs =
+ private static readonly string[] kMatchFinderIDs =
{
"BT2",
"BT4",
};
- static int FindMatchFinder(string s)
+ private static int FindMatchFinder(string s)
{
for (int m = 0; m < kMatchFinderIDs.Length; m++)
+ {
if (s == kMatchFinderIDs[m])
+ {
return m;
+ }
+ }
+
return -1;
}
@@ -1377,10 +1546,16 @@ namespace SevenZip.Compression.LZMA
case CoderPropID.NumFastBytes:
{
if (!(prop is Int32))
+ {
throw new InvalidParamException();
+ }
+
Int32 numFastBytes = (Int32)prop;
if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen)
+ {
throw new InvalidParamException();
+ }
+
_numFastBytes = (UInt32)numFastBytes;
break;
}
@@ -1398,11 +1573,17 @@ namespace SevenZip.Compression.LZMA
case CoderPropID.MatchFinder:
{
if (!(prop is String))
+ {
throw new InvalidParamException();
+ }
+
EMatchFinderType matchFinderIndexPrev = _matchFinderType;
int m = FindMatchFinder(((string)prop).ToUpper());
if (m < 0)
+ {
throw new InvalidParamException();
+ }
+
_matchFinderType = (EMatchFinderType)m;
if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType)
{
@@ -1415,54 +1596,84 @@ namespace SevenZip.Compression.LZMA
{
const int kDicLogSizeMaxCompress = 30;
if (!(prop is Int32))
- throw new InvalidParamException(); ;
+ {
+ throw new InvalidParamException();
+ }
Int32 dictionarySize = (Int32)prop;
if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) ||
dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress))
+ {
throw new InvalidParamException();
+ }
+
_dictionarySize = (UInt32)dictionarySize;
int dicLogSize;
for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++)
+ {
if (dictionarySize <= ((UInt32)(1) << dicLogSize))
+ {
break;
+ }
+ }
+
_distTableSize = (UInt32)dicLogSize * 2;
break;
}
case CoderPropID.PosStateBits:
{
if (!(prop is Int32))
+ {
throw new InvalidParamException();
+ }
+
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax)
+ {
throw new InvalidParamException();
- _posStateBits = (int)v;
- _posStateMask = (((UInt32)1) << (int)_posStateBits) - 1;
+ }
+
+ _posStateBits = v;
+ _posStateMask = (((UInt32)1) << _posStateBits) - 1;
break;
}
case CoderPropID.LitPosBits:
{
if (!(prop is Int32))
+ {
throw new InvalidParamException();
+ }
+
Int32 v = (Int32)prop;
- if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax)
+ if (v < 0 || v > Base.kNumLitPosStatesBitsEncodingMax)
+ {
throw new InvalidParamException();
- _numLiteralPosStateBits = (int)v;
+ }
+
+ _numLiteralPosStateBits = v;
break;
}
case CoderPropID.LitContextBits:
{
if (!(prop is Int32))
+ {
throw new InvalidParamException();
+ }
+
Int32 v = (Int32)prop;
- if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax)
- throw new InvalidParamException(); ;
- _numLiteralContextBits = (int)v;
+ if (v < 0 || v > Base.kNumLitContextBitsMax)
+ {
+ throw new InvalidParamException();
+ }
+ _numLiteralContextBits = v;
break;
}
case CoderPropID.EndMarker:
{
if (!(prop is Boolean))
+ {
throw new InvalidParamException();
+ }
+
SetWriteEndMarkerMode((Boolean)prop);
break;
}
@@ -1472,11 +1683,10 @@ namespace SevenZip.Compression.LZMA
}
}
- uint _trainSize = 0;
+ private uint _trainSize = 0;
public void SetTrainSize(uint trainSize)
{
_trainSize = trainSize;
}
-
}
}
diff --git a/7zip/Compress/RangeCoder/RangeCoder.cs b/7zip/Compress/RangeCoder/RangeCoder.cs
index bf78c3b..45025d1 100644
--- a/7zip/Compress/RangeCoder/RangeCoder.cs
+++ b/7zip/Compress/RangeCoder/RangeCoder.cs
@@ -2,18 +2,18 @@ using System;
namespace SevenZip.Compression.RangeCoder
{
- class Encoder
+ internal class Encoder
{
public const uint kTopValue = (1 << 24);
- System.IO.Stream Stream;
+ private System.IO.Stream Stream;
public UInt64 Low;
public uint Range;
- uint _cacheSize;
- byte _cache;
+ private uint _cacheSize;
+ private byte _cache;
- long StartPosition;
+ private long StartPosition;
public void SetStream(System.IO.Stream stream)
{
@@ -38,7 +38,9 @@ namespace SevenZip.Compression.RangeCoder
public void FlushData()
{
for (int i = 0; i < 5; i++)
+ {
ShiftLow();
+ }
}
public void FlushStream()
@@ -64,7 +66,7 @@ namespace SevenZip.Compression.RangeCoder
public void ShiftLow()
{
- if ((uint)Low < (uint)0xFF000000 || (uint)(Low >> 32) == 1)
+ if ((uint)Low < 0xFF000000 || (uint)(Low >> 32) == 1)
{
byte temp = _cache;
do
@@ -85,7 +87,10 @@ namespace SevenZip.Compression.RangeCoder
{
Range >>= 1;
if (((v >> i) & 1) == 1)
+ {
Low += Range;
+ }
+
if (Range < kTopValue)
{
Range <<= 8;
@@ -98,7 +103,9 @@ namespace SevenZip.Compression.RangeCoder
{
uint newBound = (Range >> numTotalBits) * size0;
if (symbol == 0)
+ {
Range = newBound;
+ }
else
{
Low += newBound;
@@ -119,7 +126,7 @@ namespace SevenZip.Compression.RangeCoder
}
}
- class Decoder
+ internal class Decoder
{
public const uint kTopValue = (1 << 24);
public uint Range;
@@ -135,7 +142,9 @@ namespace SevenZip.Compression.RangeCoder
Code = 0;
Range = 0xFFFFFFFF;
for (int i = 0; i < 5; i++)
+ {
Code = (Code << 8) | (byte)Stream.ReadByte();
+ }
}
public void ReleaseStream()
diff --git a/7zip/Compress/RangeCoder/RangeCoderBit.cs b/7zip/Compress/RangeCoder/RangeCoderBit.cs
index 05a486e..cb88d5c 100644
--- a/7zip/Compress/RangeCoder/RangeCoderBit.cs
+++ b/7zip/Compress/RangeCoder/RangeCoderBit.cs
@@ -2,24 +2,28 @@ using System;
namespace SevenZip.Compression.RangeCoder
{
- struct BitEncoder
+ internal struct BitEncoder
{
public const int kNumBitModelTotalBits = 11;
public const uint kBitModelTotal = (1 << kNumBitModelTotalBits);
- const int kNumMoveBits = 5;
- const int kNumMoveReducingBits = 2;
+ private const int kNumMoveBits = 5;
+ private const int kNumMoveReducingBits = 2;
public const int kNumBitPriceShiftBits = 6;
- uint Prob;
+ private uint Prob;
public void Init() { Prob = kBitModelTotal >> 1; }
public void UpdateModel(uint symbol)
{
if (symbol == 0)
+ {
Prob += (kBitModelTotal - Prob) >> kNumMoveBits;
+ }
else
- Prob -= (Prob) >> kNumMoveBits;
+ {
+ Prob -= Prob >> kNumMoveBits;
+ }
}
public void Encode(Encoder encoder, uint symbol)
@@ -36,7 +40,7 @@ namespace SevenZip.Compression.RangeCoder
{
encoder.Low += newBound;
encoder.Range -= newBound;
- Prob -= (Prob) >> kNumMoveBits;
+ Prob -= Prob >> kNumMoveBits;
}
if (encoder.Range < Encoder.kTopValue)
{
@@ -45,7 +49,7 @@ namespace SevenZip.Compression.RangeCoder
}
}
- private static UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits];
+ private static readonly UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits];
static BitEncoder()
{
@@ -55,40 +59,46 @@ namespace SevenZip.Compression.RangeCoder
UInt32 start = (UInt32)1 << (kNumBits - i - 1);
UInt32 end = (UInt32)1 << (kNumBits - i);
for (UInt32 j = start; j < end; j++)
+ {
ProbPrices[j] = ((UInt32)i << kNumBitPriceShiftBits) +
(((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1));
+ }
}
}
public uint GetPrice(uint symbol)
{
- return ProbPrices[(((Prob - symbol) ^ ((-(int)symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits];
+ return ProbPrices[(((Prob - symbol) ^ (-(int)symbol)) & (kBitModelTotal - 1)) >> kNumMoveReducingBits];
}
public uint GetPrice0() { return ProbPrices[Prob >> kNumMoveReducingBits]; }
public uint GetPrice1() { return ProbPrices[(kBitModelTotal - Prob) >> kNumMoveReducingBits]; }
}
- struct BitDecoder
+ internal struct BitDecoder
{
public const int kNumBitModelTotalBits = 11;
public const uint kBitModelTotal = (1 << kNumBitModelTotalBits);
- const int kNumMoveBits = 5;
+ private const int kNumMoveBits = 5;
- uint Prob;
+ private uint Prob;
public void UpdateModel(int numMoveBits, uint symbol)
{
if (symbol == 0)
+ {
Prob += (kBitModelTotal - Prob) >> numMoveBits;
+ }
else
- Prob -= (Prob) >> numMoveBits;
+ {
+ Prob -= Prob >> numMoveBits;
+ }
}
public void Init() { Prob = kBitModelTotal >> 1; }
- public uint Decode(RangeCoder.Decoder rangeDecoder)
+ public uint Decode(Decoder rangeDecoder)
{
- uint newBound = (uint)(rangeDecoder.Range >> kNumBitModelTotalBits) * (uint)Prob;
+ uint newBound = (rangeDecoder.Range >> kNumBitModelTotalBits) * Prob;
if (rangeDecoder.Code < newBound)
{
rangeDecoder.Range = newBound;
@@ -104,7 +114,7 @@ namespace SevenZip.Compression.RangeCoder
{
rangeDecoder.Range -= newBound;
rangeDecoder.Code -= newBound;
- Prob -= (Prob) >> kNumMoveBits;
+ Prob -= Prob >> kNumMoveBits;
if (rangeDecoder.Range < Decoder.kTopValue)
{
rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte();
diff --git a/7zip/Compress/RangeCoder/RangeCoderBitTree.cs b/7zip/Compress/RangeCoder/RangeCoderBitTree.cs
index 0defdc8..7d3c026 100644
--- a/7zip/Compress/RangeCoder/RangeCoderBitTree.cs
+++ b/7zip/Compress/RangeCoder/RangeCoderBitTree.cs
@@ -2,10 +2,10 @@ using System;
namespace SevenZip.Compression.RangeCoder
{
- struct BitTreeEncoder
+ internal struct BitTreeEncoder
{
- BitEncoder[] Models;
- int NumBitLevels;
+ private readonly BitEncoder[] Models;
+ private readonly int NumBitLevels;
public BitTreeEncoder(int numBitLevels)
{
@@ -16,7 +16,9 @@ namespace SevenZip.Compression.RangeCoder
public void Init()
{
for (uint i = 1; i < (1 << NumBitLevels); i++)
+ {
Models[i].Init();
+ }
}
public void Encode(Encoder rangeEncoder, UInt32 symbol)
@@ -100,10 +102,10 @@ namespace SevenZip.Compression.RangeCoder
}
}
- struct BitTreeDecoder
+ internal struct BitTreeDecoder
{
- BitDecoder[] Models;
- int NumBitLevels;
+ private readonly BitDecoder[] Models;
+ private readonly int NumBitLevels;
public BitTreeDecoder(int numBitLevels)
{
@@ -114,18 +116,23 @@ namespace SevenZip.Compression.RangeCoder
public void Init()
{
for (uint i = 1; i < (1 << NumBitLevels); i++)
+ {
Models[i].Init();
+ }
}
- public uint Decode(RangeCoder.Decoder rangeDecoder)
+ public uint Decode(Decoder rangeDecoder)
{
uint m = 1;
for (int bitIndex = NumBitLevels; bitIndex > 0; bitIndex--)
+ {
m = (m << 1) + Models[m].Decode(rangeDecoder);
+ }
+
return m - ((uint)1 << NumBitLevels);
}
- public uint ReverseDecode(RangeCoder.Decoder rangeDecoder)
+ public uint ReverseDecode(Decoder rangeDecoder)
{
uint m = 1;
uint symbol = 0;
@@ -140,7 +147,7 @@ namespace SevenZip.Compression.RangeCoder
}
public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex,
- RangeCoder.Decoder rangeDecoder, int NumBitLevels)
+ Decoder rangeDecoder, int NumBitLevels)
{
uint m = 1;
uint symbol = 0;
diff --git a/7zip/ICoder.cs b/7zip/ICoder.cs
index 5b8251c..a6773cf 100644
--- a/7zip/ICoder.cs
+++ b/7zip/ICoder.cs
@@ -8,7 +8,7 @@ namespace SevenZip
///
/// The exception that is thrown when an error in input stream occurs during decoding.
///
- class DataErrorException : ApplicationException
+ internal class DataErrorException : ApplicationException
{
public DataErrorException() : base("Data Error") { }
}
@@ -16,7 +16,7 @@ namespace SevenZip
///
/// The exception that is thrown when the value of an argument is outside the allowable range.
///
- class InvalidParamException : ApplicationException
+ internal class InvalidParamException : ApplicationException
{
public InvalidParamException() : base("Invalid Parameter") { }
}
@@ -55,7 +55,7 @@ namespace SevenZip
///
/// callback progress reference.
///
- ///
+ ///
/// if input stream is not valid
///
void Code(System.IO.Stream inStream, System.IO.Stream outStream,
@@ -140,7 +140,6 @@ namespace SevenZip
EndMarker
};
-
public interface ISetCoderProperties
{
void SetCoderProperties(CoderPropID[] propIDs, object[] properties);
diff --git a/App.xaml.cs b/App.xaml.cs
index 34a5dd6..a6f94d0 100644
--- a/App.xaml.cs
+++ b/App.xaml.cs
@@ -35,7 +35,7 @@ namespace WPinternals
internal static Action NavigateToUnlockBoot;
internal static PatchEngine PatchEngine;
internal static WPinternalsConfig Config;
- internal static Mutex mutex = new Mutex(false, "Global\\WPinternalsRunning");
+ internal static Mutex mutex = new(false, "Global\\WPinternalsRunning");
internal static DownloadsViewModel DownloadManager;
internal static bool InterruptBoot = false;
internal static bool IsPnPEventLogMissing = true;
@@ -49,24 +49,29 @@ namespace WPinternals
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
#endif
- if (Environment.GetCommandLineArgs().Count() > 1)
+ if (Environment.GetCommandLineArgs().Length > 1)
+ {
CommandLine.OpenConsole();
+ }
try
{
if (!mutex.WaitOne(0, false))
{
- if (Environment.GetCommandLineArgs().Count() > 1)
+ if (Environment.GetCommandLineArgs().Length > 1)
{
Console.WriteLine("Windows Phone Internals is already running");
CommandLine.CloseConsole();
}
else
+ {
MessageBox.Show("Windows Phone Internals is already running.", "Windows Phone Internals", MessageBoxButton.OK, MessageBoxImage.Exclamation);
+ }
+
Environment.Exit(0);
}
}
- catch (AbandonedMutexException) { };
+ catch (AbandonedMutexException) { }
Registration.CheckExpiration();
@@ -78,20 +83,16 @@ namespace WPinternals
}
else
{
- using (Stream stream = System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("WPinternals.PatchDefinitions.xml"))
- {
- using (StreamReader sr = new StreamReader(stream))
- {
- PatchDefintionsXml = sr.ReadToEnd();
- }
- }
+ using Stream stream = System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("WPinternals.PatchDefinitions.xml");
+ using StreamReader sr = new(stream);
+ PatchDefintionsXml = sr.ReadToEnd();
}
PatchEngine = new PatchEngine(PatchDefintionsXml);
Config = WPinternalsConfig.ReadConfig();
}
- void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
+ private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is Exception)
{
diff --git a/CommandLine.cs b/CommandLine.cs
index 9d39dcc..b45b274 100644
--- a/CommandLine.cs
+++ b/CommandLine.cs
@@ -32,16 +32,16 @@ namespace WPinternals
internal static class CommandLine
{
[DllImport("kernel32.dll", SetLastError = true)]
- static extern bool AllocConsole();
+ private static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
- static extern IntPtr GetConsoleWindow();
+ private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
- static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
+ private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const UInt32 StdOutputHandle = 0xFFFFFFF5;
@@ -57,8 +57,8 @@ namespace WPinternals
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
- const int SW_HIDE = 0;
- const int SW_SHOW = 5;
+ private const int SW_HIDE = 0;
+ private const int SW_SHOW = 5;
private const int MY_CODE_PAGE = 437;
private const uint GENERIC_WRITE = 0x40000000;
@@ -110,7 +110,9 @@ namespace WPinternals
string[] args = Environment.GetCommandLineArgs();
if (args.Length == 1)
+ {
return;
+ }
switch (args[1].ToLower().TrimStart(new char[] { '-', '/' }))
{
@@ -123,22 +125,32 @@ namespace WPinternals
#endif
case "flashpartition":
if (args.Length < 4)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -FlashPartition ");
+ }
+
if (args.Length >= 5)
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FlashPartition(UIContext, args[4], args[2], args[3]);
+ }
else
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FlashPartition(UIContext, null, args[2], args[3]);
+ }
+
break;
case "flashraw":
if (args.Length < 4)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -FlashRaw ");
+ }
+
UInt64 StartSector = 0;
try
{
- if (args[2].StartsWith("0x", StringComparison.OrdinalIgnoreCase))
- StartSector = Convert.ToUInt64(args[2].Substring(2), 16);
- else
- StartSector = Convert.ToUInt64(args[2], 10);
+ StartSector = args[2].StartsWith("0x", StringComparison.OrdinalIgnoreCase)
+ ? Convert.ToUInt64(args[2][2..], 16)
+ : Convert.ToUInt64(args[2], 10);
}
catch
{
@@ -146,13 +158,21 @@ namespace WPinternals
break;
}
if (args.Length >= 5)
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FlashRaw(UIContext, StartSector, args[3], args[4]);
+ }
else
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FlashRaw(UIContext, StartSector, args[3], null);
+ }
+
break;
case "flashpartitionimmediately":
if (args.Length < 5)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -FlashPartition ");
+ }
+
await LumiaV2UnlockBootViewModel.LumiaV2FlashPartition(UIContext, args[4], args[2], args[3], false);
break;
case "readgpt":
@@ -166,12 +186,18 @@ namespace WPinternals
GPT GPT = FlashModel.ReadGPT(); // May throw NotSupportedException
foreach (Partition Partition in GPT.Partitions)
+ {
LogFile.Log(Partition.Name.PadRight(20) + "0x" + Partition.FirstSector.ToString("X8") + " - 0x" + Partition.LastSector.ToString("X8") + " " + Partition.Volume, LogType.ConsoleOnly);
+ }
if (FlashModel.ReadPhoneInfo(false).FlashAppProtocolVersionMajor >= 2)
+ {
FlashModel.SwitchToFlashAppContext();
+ }
else
+ {
await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash);
+ }
Notifier.Stop();
}
@@ -186,7 +212,10 @@ namespace WPinternals
break;
case "backupgpt":
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -BackupGPT ");
+ }
+
LogFile.BeginAction("BackupGPT");
try
{
@@ -210,7 +239,10 @@ namespace WPinternals
break;
case "restoregpt":
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -RestoreGPT ");
+ }
+
LogFile.BeginAction("RestoreGPT");
try
{
@@ -218,7 +250,7 @@ namespace WPinternals
UIContext.Send(s => Notifier.Start(), null);
FlashModel = (NokiaFlashModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash));
byte[] GptChunk = LumiaUnlockBootloaderViewModel.GetGptChunk(FlashModel, 0x20000);
- GPT GPT = new GPT(GptChunk);
+ GPT GPT = new(GptChunk);
string Xml = File.ReadAllText(args[2]);
GPT.MergePartitions(Xml, false);
GPT.Rebuild();
@@ -237,7 +269,10 @@ namespace WPinternals
break;
case "mergegpt":
if (args.Length < 4)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -MergeGPT Or use: WPinternals.exe -MergeGPT ");
+ }
+
LogFile.BeginAction("MergeGPT");
try
{
@@ -254,8 +289,7 @@ namespace WPinternals
if (Archive == null)
{
- if (s != null)
- s.Close();
+ s?.Close();
// Assume Xml-file
GPT.MergePartitionsFromFile(args[3], true);
@@ -264,28 +298,29 @@ namespace WPinternals
{
ZipArchiveEntry PartitionEntry = Archive.GetEntry("Partitions.xml");
if (PartitionEntry == null)
+ {
GPT.MergePartitions(null, true, Archive);
+ }
else
{
- using (Stream ZipStream = PartitionEntry.Open())
- {
- using (StreamReader ZipReader = new StreamReader(ZipStream))
- {
- string PartitionXml = ZipReader.ReadToEnd();
- GPT.MergePartitions(PartitionXml, true, Archive);
- }
- }
+ using Stream ZipStream = PartitionEntry.Open();
+ using StreamReader ZipReader = new(ZipStream);
+ string PartitionXml = ZipReader.ReadToEnd();
+ GPT.MergePartitions(PartitionXml, true, Archive);
}
}
- if (Archive != null)
- Archive.Dispose();
+ Archive?.Dispose();
- if (args.Count() >= 5)
+ if (args.Length >= 5)
+ {
GPT.WritePartitions(args[4]);
+ }
foreach (Partition Partition in GPT.Partitions)
+ {
LogFile.Log(Partition.Name.PadRight(20) + "0x" + Partition.FirstSector.ToString("X8") + " - 0x" + Partition.LastSector.ToString("X8") + " " + Partition.Volume, LogType.ConsoleOnly);
+ }
}
catch (Exception Ex)
{
@@ -298,7 +333,10 @@ namespace WPinternals
break;
case "dumpffu":
if (args.Length < 4)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -DumpFFU ");
+ }
+
FFU = new FFU(args[2]);
if (args.Length < 5)
{
@@ -314,13 +352,18 @@ namespace WPinternals
{
Partition Target = FFU.GPT.GetPartition(args[4]);
if ((Target == null) || (!FFU.IsPartitionPresentInFFU(Target.Name)))
+ {
throw new InvalidOperationException("Partition not found in FFU!");
+ }
+
FFU.WritePartition(Target.Name, System.IO.Path.Combine(args[3], Target.Name + ".bin"));
}
break;
case "dumpuefi":
if (args.Length < 4)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -DumpUEFI ");
+ }
byte[] UefiBinary;
if (FFU.IsFFU(args[2]))
@@ -333,29 +376,21 @@ namespace WPinternals
UefiBinary = File.ReadAllBytes(args[2]);
}
- UEFI UEFI = new UEFI(UefiBinary);
+ UEFI UEFI = new(UefiBinary);
foreach (EFI Efi in UEFI.EFIs)
{
byte[] EfiBinary = UEFI.GetFile(Efi.Guid);
- string Name = Efi.Name;
- if (Name == null)
- Name = Efi.Guid.ToString();
+ string Name = Efi.Name ?? Efi.Guid.ToString();
+
if (!Name.Contains('.'))
{
- switch (Efi.Type)
+ Name += Efi.Type switch
{
- case 5:
- case 7:
- Name += ".dll";
- break;
- case 9:
- Name += ".exe";
- break;
- default:
- Name += ".bin";
- break;
- }
+ 5 or 7 => ".dll",
+ 9 => ".exe",
+ _ => ".bin",
+ };
}
string EfiPath = Path.Combine(args[3], Name);
Directory.CreateDirectory(Path.GetDirectoryName(EfiPath));
@@ -364,53 +399,86 @@ namespace WPinternals
break;
case "testprogrammer":
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -TestProgrammer ");
+ }
+
await TestCode.TestProgrammer(UIContext, args[2]);
break;
case "findflashingprofile":
Notifier = new PhoneNotifierViewModel();
UIContext.Send(s => Notifier.Start(), null);
if (args.Length > 2)
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FindFlashingProfile(Notifier, args[2]);
+ }
else
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FindFlashingProfile(Notifier, null);
+ }
+
Notifier.Stop();
break;
case "findflashingprofileexperimental":
Notifier = new PhoneNotifierViewModel();
UIContext.Send(s => Notifier.Start(), null);
if (args.Length > 2)
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FindFlashingProfile(Notifier, args[2], Experimental: true);
+ }
else
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FindFlashingProfile(Notifier, null, Experimental: true);
+ }
+
Notifier.Stop();
break;
case "findflashingprofilenorestart":
Notifier = new PhoneNotifierViewModel();
UIContext.Send(s => Notifier.Start(), null);
if (args.Length > 2)
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FindFlashingProfile(Notifier, args[2], false);
+ }
else
+ {
await LumiaV2UnlockBootViewModel.LumiaV2FindFlashingProfile(Notifier, null, false);
+ }
+
Notifier.Stop();
break;
case "enabletestsigning":
if (args.Length > 2)
+ {
await LumiaV2UnlockBootViewModel.LumiaV2EnableTestSigning(UIContext, args[2]);
+ }
else
+ {
await LumiaV2UnlockBootViewModel.LumiaV2EnableTestSigning(UIContext, null);
+ }
+
break;
case "enabletestsigningnorestart":
if (args.Length > 2)
+ {
await LumiaV2UnlockBootViewModel.LumiaV2EnableTestSigning(UIContext, args[2], false);
+ }
else
+ {
await LumiaV2UnlockBootViewModel.LumiaV2EnableTestSigning(UIContext, null, false);
+ }
+
break;
case "clearnv":
if (args.Length > 2)
+ {
await LumiaV2UnlockBootViewModel.LumiaV2ClearNV(UIContext, args[2]);
+ }
else
+ {
await LumiaV2UnlockBootViewModel.LumiaV2ClearNV(UIContext, null);
+ }
+
break;
case "switchtomassstoragemode":
LogFile.BeginAction("SwitchToMassStorageMode");
@@ -420,9 +488,14 @@ namespace WPinternals
UIContext.Send(s => Notifier.Start(), null);
LogFile.Log("Command: Switch to Mass Storage Mode", LogType.FileAndConsole);
if (args.Length > 2)
+ {
await LumiaV2UnlockBootViewModel.LumiaV2SwitchToMassStorageMode(Notifier, args[2]);
+ }
else
+ {
await LumiaV2UnlockBootViewModel.LumiaV2SwitchToMassStorageMode(Notifier, null);
+ }
+
Notifier.Stop();
}
catch (Exception Ex)
@@ -455,17 +528,18 @@ namespace WPinternals
// Check if the current FFU matches the connected phone, so that the FFU can be used for profiling.
if (Info.PlatformID.StartsWith(PlatformID, StringComparison.OrdinalIgnoreCase))
+ {
ProfileFFU = CurrentFFU;
+ }
}
}
if (ProfileFFU == null)
{
List FFUs = App.Config.FFURepository.Where(e => (Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists())).ToList();
- if (FFUs.Count() > 0)
- ProfileFFU = new FFU(FFUs[0].Path);
- else
- 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.");
+ 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.");
}
LogFile.Log("Profile FFU: " + ProfileFFU.Path);
@@ -481,22 +555,34 @@ namespace WPinternals
break;
case "addffu":
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -AddFFU ");
+ }
+
App.Config.AddFfuToRepository(args[2]);
break;
case "removeffu":
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -RemoveFFU ");
+ }
+
App.Config.RemoveFfuFromRepository(args[2]);
break;
case "addemergency":
if (args.Length < 5)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -AddEmergnency ");
+ }
+
App.Config.AddEmergencyToRepository(args[2], args[3], args[4]);
break;
case "removeemergency":
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -RemoveEmergency ");
+ }
+
App.Config.RemoveEmergencyFromRepository(args[2]);
break;
case "listrepository":
@@ -510,9 +596,15 @@ namespace WPinternals
LogFile.Log("File: " + Entry.Path + (Entry.Exists() ? "" : " (file is missing)"), LogType.ConsoleOnly);
LogFile.Log("Platform ID: " + Entry.PlatformID, LogType.ConsoleOnly);
if (Entry.FirmwareVersion != null)
+ {
LogFile.Log("Firmware version: " + Entry.FirmwareVersion, LogType.ConsoleOnly);
+ }
+
if (Entry.OSVersion != null)
+ {
LogFile.Log("OS version: " + Entry.OSVersion, LogType.ConsoleOnly);
+ }
+
Count++;
}
LogFile.Log("", LogType.ConsoleOnly);
@@ -525,13 +617,19 @@ namespace WPinternals
LogFile.Log("Type: " + Entry.Type, LogType.ConsoleOnly);
LogFile.Log("Programmer file: " + Entry.ProgrammerPath + (Entry.ProgrammerExists() ? "" : " (file is missing)"), LogType.ConsoleOnly);
if (Entry.PayloadPath != null)
+ {
LogFile.Log("Payload file: " + Entry.PayloadPath + (Entry.PayloadExists() ? "" : " (file is missing)"), LogType.ConsoleOnly);
+ }
+
Count++;
}
break;
case "showffu":
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -ShowFFU ");
+ }
+
string FFUPath = args[2];
LogFile.Log("FFU: " + FFUPath, LogType.ConsoleOnly);
FFU = new FFU(FFUPath);
@@ -540,10 +638,15 @@ namespace WPinternals
LogFile.Log("Platform ID: " + FFU.PlatformID, LogType.ConsoleOnly);
string Firmware = FFU.GetFirmwareVersion();
if (Firmware != null)
+ {
LogFile.Log("Firmware version: " + Firmware, LogType.ConsoleOnly);
+ }
+
string OSVersion = FFU.GetOSVersion();
if (OSVersion != null)
+ {
LogFile.Log("OS version: " + OSVersion, LogType.ConsoleOnly);
+ }
// Show partitions from GPT (also show which partitions are in the FFU payload)
LogFile.Log("", LogType.ConsoleOnly);
@@ -587,31 +690,33 @@ namespace WPinternals
// Check if the current FFU matches the connected phone, so that the FFU can be used for profiling.
if (Info.PlatformID.StartsWith(PlatformID, StringComparison.OrdinalIgnoreCase))
+ {
ProfileFFU = CurrentFFU;
+ }
// Check if the current FFU is supported for unlocking.
- if (App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == CurrentVersion))
+ if (App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == CurrentVersion))
+ {
SupportedFFU = CurrentFFU;
+ }
}
}
if (ProfileFFU == null)
{
List FFUs = App.Config.FFURepository.Where(e => (Info.PlatformID.StartsWith(e.PlatformID, StringComparison.OrdinalIgnoreCase) && e.Exists())).ToList();
- if (FFUs.Count() > 0)
- ProfileFFU = new FFU(FFUs[0].Path);
- else
- 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.");
+ 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.");
}
LogFile.Log("Profile FFU: " + ProfileFFU.Path);
if (SupportedFFU == null)
{
- List FFUs = App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == e.OSVersion)).ToList();
- if (FFUs.Count() > 0)
- SupportedFFU = new FFU(FFUs[0].Path);
- else
- throw new WPinternalsException("No donor-FFU found with supported OS version", "No donor-FFU has been found in the repository with a supported OS version. You can add a donor-FFU within the download section of the tool or by using the command line. A donor-FFU can be for a different device and a different CPU than your device. It is only used to gather Operating System specific binaries to be patched and used as part of the unlock process.");
+ List FFUs = App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion)).ToList();
+ SupportedFFU = FFUs.Count > 0
+ ? new FFU(FFUs[0].Path)
+ : throw new WPinternalsException("No donor-FFU found with supported OS version", "No donor-FFU has been found in the repository with a supported OS version. You can add a donor-FFU within the download section of the tool or by using the command line. A donor-FFU can be for a different device and a different CPU than your device. It is only used to gather Operating System specific binaries to be patched and used as part of the unlock process.");
}
await LumiaUnlockBootloaderViewModel.LumiaUnlockUEFI(Notifier, ProfileFFU.Path, null, SupportedFFU.Path);
@@ -633,7 +738,10 @@ namespace WPinternals
{
LogFile.Log("Command: Flash Custom ROM", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -FlashCustomROM ");
+ }
+
string CustomRomPath = args[2];
LogFile.Log("Custom ROM: " + CustomRomPath, LogType.FileAndConsole);
Notifier = new PhoneNotifierViewModel();
@@ -661,7 +769,10 @@ namespace WPinternals
{
LogFile.Log("Command: Flash FFU", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -FlashFFU ");
+ }
+
FFUPath = args[2];
LogFile.Log("FFU file: " + FFUPath, LogType.FileAndConsole);
Notifier = new PhoneNotifierViewModel();
@@ -695,7 +806,10 @@ namespace WPinternals
App.PatchEngine.TargetPath = Drive + "\\";
PatchResult = App.PatchEngine.Patch("SecureBootHack-MainOS");
if (!PatchResult)
+ {
throw new WPinternalsException("Patch failed", "An error occured while patching Operating System files on the MainOS partition of your phone. Make sure your phone runs a supported Operating System version.");
+ }
+
LogFile.Log("Fixed bootloader", LogType.FileAndConsole);
LogFile.Log("The phone is left in Mass Storage mode", LogType.FileAndConsole);
LogFile.Log("Press and hold the power-button of the phone for at least 10 seconds to reset the phone", LogType.FileAndConsole);
@@ -721,14 +835,23 @@ namespace WPinternals
App.PatchEngine.TargetPath = Drive + "\\EFIESP\\";
PatchResult = App.PatchEngine.Patch("SecureBootHack-V2-EFIESP");
if (!PatchResult)
+ {
throw new WPinternalsException("Patch failed", "An error occured while patching Operating System files on the EFIESP partition of your phone. Make sure no boot files have been tampered with and you use the latest version of the tool. This error cannot be caused by an incorrect Operating System version as the tool automatically uses replacement if the version isn't supported.");
+ }
+
App.PatchEngine.TargetPath = Drive + "\\";
PatchResult = App.PatchEngine.Patch("SecureBootHack-MainOS");
if (!PatchResult)
+ {
throw new WPinternalsException("Patch failed", "An error occured while patching Operating System files on the MainOS partition of your phone. Make sure your phone runs a supported Operating System version.");
+ }
+
PatchResult = App.PatchEngine.Patch("RootAccess-MainOS");
if (!PatchResult)
+ {
throw new WPinternalsException("Patch failed", "An error occured while modifying Operating System files on the MainOS partition of your phone for Root Access. Make sure your phone runs a supported Operating System version.");
+ }
+
LogFile.Log("Root Access enabled!", LogType.FileAndConsole);
LogFile.Log("The phone is left in Mass Storage mode", LogType.FileAndConsole);
LogFile.Log("Press and hold the power-button of the phone for at least 10 seconds to reset the phone", LogType.FileAndConsole);
@@ -745,31 +868,40 @@ namespace WPinternals
case "unlockbootloaderonimage":
LogFile.Log("Command: Unlock bootloader on image", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -UnlockBootLoaderOnImage ");
+ }
+
FFUFilePath = null;
EfiEspImagePath = args[2];
if (args.Length > 3)
{
if (FFU.IsFFU(args[3]))
+ {
FFUFilePath = args[3];
+ }
else
+ {
MainOsImagePath = args[3];
+ }
}
if (args.Length > 4)
+ {
FFUFilePath = args[4];
+ }
- using (FileStream FileSystemStream = new FileStream(EfiEspImagePath, FileMode.Open, FileAccess.ReadWrite))
+ using (FileStream FileSystemStream = new(EfiEspImagePath, FileMode.Open, FileAccess.ReadWrite))
{
UnlockedEFIESPFileSystem = new DiscUtils.Fat.FatFileSystem(FileSystemStream);
if (FFUFilePath != null)
{
- FFU SupportedFFU = new FFU(FFUFilePath);
+ FFU SupportedFFU = new(FFUFilePath);
LogFile.Log("Donor FFU: " + SupportedFFU.Path);
byte[] SupportedEFIESP = SupportedFFU.GetPartition("EFIESP");
- DiscUtils.Fat.FatFileSystem SupportedEFIESPFileSystem = new DiscUtils.Fat.FatFileSystem(new MemoryStream(SupportedEFIESP));
- DiscUtils.SparseStream SupportedMobileStartupStream = SupportedEFIESPFileSystem.OpenFile(@"\Windows\System32\Boot\mobilestartup.efi", FileMode.Open);
- MemoryStream SupportedMobileStartupMemStream = new MemoryStream();
+ DiscUtils.Fat.FatFileSystem SupportedEFIESPFileSystem = new(new MemoryStream(SupportedEFIESP));
+ DiscUtils.Streams.SparseStream SupportedMobileStartupStream = SupportedEFIESPFileSystem.OpenFile(@"\Windows\System32\Boot\mobilestartup.efi", FileMode.Open);
+ MemoryStream SupportedMobileStartupMemStream = new();
SupportedMobileStartupStream.CopyTo(SupportedMobileStartupMemStream);
byte[] SupportedMobileStartup = SupportedMobileStartupMemStream.ToArray();
SupportedMobileStartupMemStream.Close();
@@ -785,42 +917,48 @@ namespace WPinternals
App.PatchEngine.TargetImage = UnlockedEFIESPFileSystem;
PatchResult = App.PatchEngine.Patch("SecureBootHack-V2-EFIESP");
if (!PatchResult)
+ {
throw new WPinternalsException("Failed to patch bootloader", "An error occured while patching Operating System files on the EFIESP partition provided. Make sure no boot files have been tampered with and you use the latest version of the tool. This error cannot be caused by an incorrect Operating System version as the tool automatically uses replacement if the version isn't supported, unless the replacement files have been tampered with or are not compatible.");
+ }
// Edit BCD
LogFile.Log("Edit BCD");
- using (Stream BCDFileStream = UnlockedEFIESPFileSystem.OpenFile(@"efi\Microsoft\Boot\BCD", FileMode.Open, FileAccess.ReadWrite))
+ using Stream BCDFileStream = UnlockedEFIESPFileSystem.OpenFile(@"efi\Microsoft\Boot\BCD", FileMode.Open, FileAccess.ReadWrite);
+ using DiscUtils.Registry.RegistryHive BCDHive = new(BCDFileStream);
+ DiscUtils.BootConfig.Store BCDStore = new(BCDHive.Root);
+ DiscUtils.BootConfig.BcdObject MobileStartupObject = BCDStore.GetObject(new Guid("{01de5a27-8705-40db-bad6-96fa5187d4a6}"));
+ DiscUtils.BootConfig.Element NoCodeIntegrityElement = MobileStartupObject.GetElement(0x16000048);
+ if (NoCodeIntegrityElement != null)
{
- using (DiscUtils.Registry.RegistryHive BCDHive = new DiscUtils.Registry.RegistryHive(BCDFileStream))
- {
- DiscUtils.BootConfig.Store BCDStore = new DiscUtils.BootConfig.Store(BCDHive.Root);
- DiscUtils.BootConfig.BcdObject MobileStartupObject = BCDStore.GetObject(new Guid("{01de5a27-8705-40db-bad6-96fa5187d4a6}"));
- DiscUtils.BootConfig.Element NoCodeIntegrityElement = MobileStartupObject.GetElement(0x16000048);
- if (NoCodeIntegrityElement != null)
- NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
- else
- MobileStartupObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
+ }
+ else
+ {
+ MobileStartupObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ }
- DiscUtils.BootConfig.BcdObject WinLoadObject = BCDStore.GetObject(new Guid("{7619dcc9-fafe-11d9-b411-000476eba25f}"));
- NoCodeIntegrityElement = WinLoadObject.GetElement(0x16000048);
- if (NoCodeIntegrityElement != null)
- NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
- else
- WinLoadObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
- }
+ DiscUtils.BootConfig.BcdObject WinLoadObject = BCDStore.GetObject(new Guid("{7619dcc9-fafe-11d9-b411-000476eba25f}"));
+ NoCodeIntegrityElement = WinLoadObject.GetElement(0x16000048);
+ if (NoCodeIntegrityElement != null)
+ {
+ NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
+ }
+ else
+ {
+ WinLoadObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
}
}
if (MainOsImagePath != null)
{
- using (FileStream FileSystemStream = new FileStream(MainOsImagePath, FileMode.Open, FileAccess.ReadWrite))
- {
- UnlockedMainOsFileSystem = new DiscUtils.Ntfs.NtfsFileSystem(FileSystemStream);
+ using FileStream FileSystemStream = new(MainOsImagePath, FileMode.Open, FileAccess.ReadWrite);
+ UnlockedMainOsFileSystem = new DiscUtils.Ntfs.NtfsFileSystem(FileSystemStream);
- App.PatchEngine.TargetImage = UnlockedMainOsFileSystem;
- PatchResult = App.PatchEngine.Patch("SecureBootHack-MainOS");
- if (!PatchResult)
- throw new WPinternalsException("Failed to patch MainOS", "An error occured while patching Operating System files on the MainOS partition you provided. Make sure your phone runs a supported Operating System version.");
+ App.PatchEngine.TargetImage = UnlockedMainOsFileSystem;
+ PatchResult = App.PatchEngine.Patch("SecureBootHack-MainOS");
+ if (!PatchResult)
+ {
+ throw new WPinternalsException("Failed to patch MainOS", "An error occured while patching Operating System files on the MainOS partition you provided. Make sure your phone runs a supported Operating System version.");
}
}
LogFile.Log("Bootloader unlocked on image", LogType.FileAndConsole);
@@ -828,26 +966,30 @@ namespace WPinternals
case "enablerootaccessonimage":
LogFile.Log("Command: Enable root access on image", LogType.FileAndConsole);
if (args.Length < 4)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -EnableRootAccessOnImage ");
+ }
FFUFilePath = null;
EfiEspImagePath = args[2];
MainOsImagePath = args[3];
if (args.Length > 4)
+ {
FFUFilePath = args[4];
+ }
- using (FileStream FileSystemStream = new FileStream(EfiEspImagePath, FileMode.Open, FileAccess.ReadWrite))
+ using (FileStream FileSystemStream = new(EfiEspImagePath, FileMode.Open, FileAccess.ReadWrite))
{
UnlockedEFIESPFileSystem = new DiscUtils.Fat.FatFileSystem(FileSystemStream);
if (FFUFilePath != null)
{
- FFU SupportedFFU = new FFU(FFUFilePath);
+ FFU SupportedFFU = new(FFUFilePath);
LogFile.Log("Supported FFU: " + SupportedFFU.Path);
byte[] SupportedEFIESP = SupportedFFU.GetPartition("EFIESP");
- DiscUtils.Fat.FatFileSystem SupportedEFIESPFileSystem = new DiscUtils.Fat.FatFileSystem(new MemoryStream(SupportedEFIESP));
- DiscUtils.SparseStream SupportedMobileStartupStream = SupportedEFIESPFileSystem.OpenFile(@"\Windows\System32\Boot\mobilestartup.efi", FileMode.Open);
- MemoryStream SupportedMobileStartupMemStream = new MemoryStream();
+ DiscUtils.Fat.FatFileSystem SupportedEFIESPFileSystem = new(new MemoryStream(SupportedEFIESP));
+ DiscUtils.Streams.SparseStream SupportedMobileStartupStream = SupportedEFIESPFileSystem.OpenFile(@"\Windows\System32\Boot\mobilestartup.efi", FileMode.Open);
+ MemoryStream SupportedMobileStartupMemStream = new();
SupportedMobileStartupStream.CopyTo(SupportedMobileStartupMemStream);
byte[] SupportedMobileStartup = SupportedMobileStartupMemStream.ToArray();
SupportedMobileStartupMemStream.Close();
@@ -863,70 +1005,90 @@ namespace WPinternals
App.PatchEngine.TargetImage = UnlockedEFIESPFileSystem;
PatchResult = App.PatchEngine.Patch("SecureBootHack-V2-EFIESP");
if (!PatchResult)
+ {
throw new WPinternalsException("Failed to patch bootloader", "An error occured while patching Operating System files on the EFIESP partition provided. Make sure no boot files have been tampered with and you use the latest version of the tool. This error cannot be caused by an incorrect Operating System version as the tool automatically uses replacement if the version isn't supported, unless the replacement files have been tampered with or are not compatible.");
+ }
// Edit BCD
LogFile.Log("Edit BCD");
- using (Stream BCDFileStream = UnlockedEFIESPFileSystem.OpenFile(@"efi\Microsoft\Boot\BCD", FileMode.Open, FileAccess.ReadWrite))
+ using Stream BCDFileStream = UnlockedEFIESPFileSystem.OpenFile(@"efi\Microsoft\Boot\BCD", FileMode.Open, FileAccess.ReadWrite);
+ using DiscUtils.Registry.RegistryHive BCDHive = new(BCDFileStream);
+ DiscUtils.BootConfig.Store BCDStore = new(BCDHive.Root);
+ DiscUtils.BootConfig.BcdObject MobileStartupObject = BCDStore.GetObject(new Guid("{01de5a27-8705-40db-bad6-96fa5187d4a6}"));
+ DiscUtils.BootConfig.Element NoCodeIntegrityElement = MobileStartupObject.GetElement(0x16000048);
+ if (NoCodeIntegrityElement != null)
{
- using (DiscUtils.Registry.RegistryHive BCDHive = new DiscUtils.Registry.RegistryHive(BCDFileStream))
- {
- DiscUtils.BootConfig.Store BCDStore = new DiscUtils.BootConfig.Store(BCDHive.Root);
- DiscUtils.BootConfig.BcdObject MobileStartupObject = BCDStore.GetObject(new Guid("{01de5a27-8705-40db-bad6-96fa5187d4a6}"));
- DiscUtils.BootConfig.Element NoCodeIntegrityElement = MobileStartupObject.GetElement(0x16000048);
- if (NoCodeIntegrityElement != null)
- NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
- else
- MobileStartupObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
+ }
+ else
+ {
+ MobileStartupObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ }
- DiscUtils.BootConfig.BcdObject WinLoadObject = BCDStore.GetObject(new Guid("{7619dcc9-fafe-11d9-b411-000476eba25f}"));
- NoCodeIntegrityElement = WinLoadObject.GetElement(0x16000048);
- if (NoCodeIntegrityElement != null)
- NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
- else
- WinLoadObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
- }
+ DiscUtils.BootConfig.BcdObject WinLoadObject = BCDStore.GetObject(new Guid("{7619dcc9-fafe-11d9-b411-000476eba25f}"));
+ NoCodeIntegrityElement = WinLoadObject.GetElement(0x16000048);
+ if (NoCodeIntegrityElement != null)
+ {
+ NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
+ }
+ else
+ {
+ WinLoadObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
}
}
- using (FileStream FileSystemStream = new FileStream(MainOsImagePath, FileMode.Open, FileAccess.ReadWrite))
+ using (FileStream FileSystemStream = new(MainOsImagePath, FileMode.Open, FileAccess.ReadWrite))
{
UnlockedMainOsFileSystem = new DiscUtils.Ntfs.NtfsFileSystem(FileSystemStream);
App.PatchEngine.TargetImage = UnlockedMainOsFileSystem;
PatchResult = App.PatchEngine.Patch("SecureBootHack-MainOS");
if (!PatchResult)
+ {
throw new WPinternalsException("Failed to patch MainOS", "An error occured while patching Operating System files on the MainOS partition you provided. Make sure your phone runs a supported Operating System version.");
+ }
+
PatchResult = App.PatchEngine.Patch("RootAccess-MainOS");
if (!PatchResult)
+ {
throw new WPinternalsException("Failed to patch MainOS", "An error occured while modifying Operating System files on the MainOS partition you provided for Root Access. Make sure your phone runs a supported Operating System version.");
+ }
}
LogFile.Log("Root access enabled on image", LogType.FileAndConsole);
break;
case "unlockbootloaderonmountedimage":
LogFile.Log("Command: Unlock bootloader on mounted image", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -UnlockBootLoaderOnMountedImage ");
+ }
+
FFUFilePath = null;
EfiEspImagePath = args[2];
if (args.Length > 3)
{
if (FFU.IsFFU(args[3]))
+ {
FFUFilePath = args[3];
+ }
else
+ {
MainOsImagePath = args[3];
+ }
}
if (args.Length > 4)
+ {
FFUFilePath = args[4];
+ }
if (FFUFilePath != null)
{
- FFU SupportedFFU = new FFU(FFUFilePath);
+ FFU SupportedFFU = new(FFUFilePath);
LogFile.Log("Donor-FFU: " + SupportedFFU.Path);
byte[] SupportedEFIESP = SupportedFFU.GetPartition("EFIESP");
- DiscUtils.Fat.FatFileSystem SupportedEFIESPFileSystem = new DiscUtils.Fat.FatFileSystem(new MemoryStream(SupportedEFIESP));
- DiscUtils.SparseStream SupportedMobileStartupStream = SupportedEFIESPFileSystem.OpenFile(@"\Windows\System32\Boot\mobilestartup.efi", FileMode.Open);
- MemoryStream SupportedMobileStartupMemStream = new MemoryStream();
+ DiscUtils.Fat.FatFileSystem SupportedEFIESPFileSystem = new(new MemoryStream(SupportedEFIESP));
+ DiscUtils.Streams.SparseStream SupportedMobileStartupStream = SupportedEFIESPFileSystem.OpenFile(@"\Windows\System32\Boot\mobilestartup.efi", FileMode.Open);
+ MemoryStream SupportedMobileStartupMemStream = new();
SupportedMobileStartupStream.CopyTo(SupportedMobileStartupMemStream);
byte[] SupportedMobileStartup = SupportedMobileStartupMemStream.ToArray();
SupportedMobileStartupMemStream.Close();
@@ -942,28 +1104,36 @@ namespace WPinternals
App.PatchEngine.TargetPath = EfiEspImagePath;
PatchResult = App.PatchEngine.Patch("SecureBootHack-V2-EFIESP");
if (!PatchResult)
+ {
throw new WPinternalsException("Failed to patch bootloader", "An error occured while patching Operating System files on the EFIESP partition provided. Make sure no boot files have been tampered with and you use the latest version of the tool. This error cannot be caused by an incorrect Operating System version as the tool automatically uses replacement if the version isn't supported, unless the replacement files have been tampered with or are not compatible.");
+ }
// Edit BCD
LogFile.Log("Edit BCD");
using (Stream BCDFileStream = File.Open(Path.Combine(EfiEspImagePath, @"efi\Microsoft\Boot\BCD"), FileMode.Open, FileAccess.ReadWrite))
{
- using (DiscUtils.Registry.RegistryHive BCDHive = new DiscUtils.Registry.RegistryHive(BCDFileStream))
+ using DiscUtils.Registry.RegistryHive BCDHive = new(BCDFileStream);
+ DiscUtils.BootConfig.Store BCDStore = new(BCDHive.Root);
+ DiscUtils.BootConfig.BcdObject MobileStartupObject = BCDStore.GetObject(new Guid("{01de5a27-8705-40db-bad6-96fa5187d4a6}"));
+ DiscUtils.BootConfig.Element NoCodeIntegrityElement = MobileStartupObject.GetElement(0x16000048);
+ if (NoCodeIntegrityElement != null)
{
- DiscUtils.BootConfig.Store BCDStore = new DiscUtils.BootConfig.Store(BCDHive.Root);
- DiscUtils.BootConfig.BcdObject MobileStartupObject = BCDStore.GetObject(new Guid("{01de5a27-8705-40db-bad6-96fa5187d4a6}"));
- DiscUtils.BootConfig.Element NoCodeIntegrityElement = MobileStartupObject.GetElement(0x16000048);
- if (NoCodeIntegrityElement != null)
- NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
- else
- MobileStartupObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
+ }
+ else
+ {
+ MobileStartupObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ }
- DiscUtils.BootConfig.BcdObject WinLoadObject = BCDStore.GetObject(new Guid("{7619dcc9-fafe-11d9-b411-000476eba25f}"));
- NoCodeIntegrityElement = WinLoadObject.GetElement(0x16000048);
- if (NoCodeIntegrityElement != null)
- NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
- else
- WinLoadObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ DiscUtils.BootConfig.BcdObject WinLoadObject = BCDStore.GetObject(new Guid("{7619dcc9-fafe-11d9-b411-000476eba25f}"));
+ NoCodeIntegrityElement = WinLoadObject.GetElement(0x16000048);
+ if (NoCodeIntegrityElement != null)
+ {
+ NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
+ }
+ else
+ {
+ WinLoadObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
}
}
@@ -972,29 +1142,35 @@ namespace WPinternals
App.PatchEngine.TargetPath = MainOsImagePath;
PatchResult = App.PatchEngine.Patch("SecureBootHack-MainOS");
if (!PatchResult)
+ {
throw new WPinternalsException("Failed to patch MainOS", "An error occured while patching Operating System files on the MainOS partition you provided. Make sure your phone runs a supported Operating System version.");
+ }
}
LogFile.Log("Bootloader unlocked on image", LogType.FileAndConsole);
break;
case "enablerootaccessonmountedimage":
LogFile.Log("Command: Enable root access on mounted image", LogType.FileAndConsole);
if (args.Length < 4)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -EnableRootAccessOnMountedImage ");
+ }
FFUFilePath = null;
EfiEspImagePath = args[2];
MainOsImagePath = args[3];
if (args.Length > 4)
+ {
FFUFilePath = args[4];
+ }
if (FFUFilePath != null)
{
- FFU SupportedFFU = new FFU(FFUFilePath);
+ FFU SupportedFFU = new(FFUFilePath);
LogFile.Log("Supported FFU: " + SupportedFFU.Path);
byte[] SupportedEFIESP = SupportedFFU.GetPartition("EFIESP");
- DiscUtils.Fat.FatFileSystem SupportedEFIESPFileSystem = new DiscUtils.Fat.FatFileSystem(new MemoryStream(SupportedEFIESP));
- DiscUtils.SparseStream SupportedMobileStartupStream = SupportedEFIESPFileSystem.OpenFile(@"\Windows\System32\Boot\mobilestartup.efi", FileMode.Open);
- MemoryStream SupportedMobileStartupMemStream = new MemoryStream();
+ DiscUtils.Fat.FatFileSystem SupportedEFIESPFileSystem = new(new MemoryStream(SupportedEFIESP));
+ DiscUtils.Streams.SparseStream SupportedMobileStartupStream = SupportedEFIESPFileSystem.OpenFile(@"\Windows\System32\Boot\mobilestartup.efi", FileMode.Open);
+ MemoryStream SupportedMobileStartupMemStream = new();
SupportedMobileStartupStream.CopyTo(SupportedMobileStartupMemStream);
byte[] SupportedMobileStartup = SupportedMobileStartupMemStream.ToArray();
SupportedMobileStartupMemStream.Close();
@@ -1010,38 +1186,52 @@ namespace WPinternals
App.PatchEngine.TargetPath = EfiEspImagePath;
PatchResult = App.PatchEngine.Patch("SecureBootHack-V2-EFIESP");
if (!PatchResult)
+ {
throw new WPinternalsException("Failed to patch bootloader", "An error occured while patching Operating System files on the EFIESP partition provided. Make sure no boot files have been tampered with and you use the latest version of the tool. This error cannot be caused by an incorrect Operating System version as the tool automatically uses replacement if the version isn't supported, unless the replacement files have been tampered with or are not compatible.");
+ }
// Edit BCD
LogFile.Log("Edit BCD");
using (Stream BCDFileStream = File.Open(Path.Combine(EfiEspImagePath, @"efi\Microsoft\Boot\BCD"), FileMode.Open, FileAccess.ReadWrite))
{
- using (DiscUtils.Registry.RegistryHive BCDHive = new DiscUtils.Registry.RegistryHive(BCDFileStream))
+ using DiscUtils.Registry.RegistryHive BCDHive = new(BCDFileStream);
+ DiscUtils.BootConfig.Store BCDStore = new(BCDHive.Root);
+ DiscUtils.BootConfig.BcdObject MobileStartupObject = BCDStore.GetObject(new Guid("{01de5a27-8705-40db-bad6-96fa5187d4a6}"));
+ DiscUtils.BootConfig.Element NoCodeIntegrityElement = MobileStartupObject.GetElement(0x16000048);
+ if (NoCodeIntegrityElement != null)
{
- DiscUtils.BootConfig.Store BCDStore = new DiscUtils.BootConfig.Store(BCDHive.Root);
- DiscUtils.BootConfig.BcdObject MobileStartupObject = BCDStore.GetObject(new Guid("{01de5a27-8705-40db-bad6-96fa5187d4a6}"));
- DiscUtils.BootConfig.Element NoCodeIntegrityElement = MobileStartupObject.GetElement(0x16000048);
- if (NoCodeIntegrityElement != null)
- NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
- else
- MobileStartupObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
+ }
+ else
+ {
+ MobileStartupObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ }
- DiscUtils.BootConfig.BcdObject WinLoadObject = BCDStore.GetObject(new Guid("{7619dcc9-fafe-11d9-b411-000476eba25f}"));
- NoCodeIntegrityElement = WinLoadObject.GetElement(0x16000048);
- if (NoCodeIntegrityElement != null)
- NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
- else
- WinLoadObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
+ DiscUtils.BootConfig.BcdObject WinLoadObject = BCDStore.GetObject(new Guid("{7619dcc9-fafe-11d9-b411-000476eba25f}"));
+ NoCodeIntegrityElement = WinLoadObject.GetElement(0x16000048);
+ if (NoCodeIntegrityElement != null)
+ {
+ NoCodeIntegrityElement.Value = DiscUtils.BootConfig.ElementValue.ForBoolean(true);
+ }
+ else
+ {
+ WinLoadObject.AddElement(0x16000048, DiscUtils.BootConfig.ElementValue.ForBoolean(true));
}
}
App.PatchEngine.TargetPath = MainOsImagePath;
PatchResult = App.PatchEngine.Patch("SecureBootHack-MainOS");
if (!PatchResult)
+ {
throw new WPinternalsException("Failed to patch MainOS", "An error occured while patching Operating System files on the MainOS partition you provided. Make sure your phone runs a supported Operating System version.");
+ }
+
PatchResult = App.PatchEngine.Patch("RootAccess-MainOS");
if (!PatchResult)
+ {
throw new WPinternalsException("Failed to patch MainOS", "An error occured while modifying Operating System files on the MainOS partition you provided for Root Access. Make sure your phone runs a supported Operating System version.");
+ }
+
LogFile.Log("Root access enabled on image", LogType.FileAndConsole);
break;
case "downloadffu":
@@ -1065,12 +1255,15 @@ namespace WPinternals
ProductCode = NormalModel.ExecuteJsonMethodAsString("ReadProductCode", "ProductCode");
}
URL = LumiaDownloadModel.SearchFFU(null, ProductCode, null, out ProductType);
- if (args.Length >= 3)
- DownloadFolder = args[4];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 3
+ ? args[4]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
URI = new Uri(URL);
@@ -1078,7 +1271,7 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
@@ -1089,17 +1282,23 @@ namespace WPinternals
case "downloadffubyoperatorcode":
LogFile.Log("Command: Download FFU by Operator Code", LogType.FileAndConsole);
if (args.Length < 4)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -DownloadFFUbyOperatorCode ");
+ }
+
ProductType = args[2];
LogFile.Log("Product type: " + ProductType, LogType.FileAndConsole);
OperatorCode = args[3];
LogFile.Log("Operator code: " + OperatorCode, LogType.FileAndConsole);
- if (args.Length >= 5)
- DownloadFolder = args[4];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 5
+ ? args[4]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
URL = LumiaDownloadModel.SearchFFU(ProductType, null, OperatorCode);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
@@ -1108,7 +1307,7 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
@@ -1118,16 +1317,22 @@ namespace WPinternals
case "downloadffubyproductcode":
LogFile.Log("Command: Download FFU by Product Code", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -DownloadFFUbyProductCode ");
+ }
+
ProductCode = args[2];
LogFile.Log("Product code: " + ProductCode, LogType.FileAndConsole);
URL = LumiaDownloadModel.SearchFFU(null, ProductCode, null, out ProductType);
- if (args.Length >= 4)
- DownloadFolder = args[3];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 4
+ ? args[3]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
URI = new Uri(URL);
@@ -1135,7 +1340,7 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
@@ -1145,15 +1350,21 @@ namespace WPinternals
case "downloadffubyproducttype":
LogFile.Log("Command: Download FFU by Product Type", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -DownloadFFUbyProductType ");
+ }
+
ProductType = args[2];
LogFile.Log("Product type: " + ProductType, LogType.FileAndConsole);
- if (args.Length >= 4)
- DownloadFolder = args[3];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 4
+ ? args[3]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
URL = LumiaDownloadModel.SearchFFU(ProductType, null, null);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
@@ -1162,7 +1373,7 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
@@ -1172,7 +1383,10 @@ namespace WPinternals
case "searchffubyproducttype":
LogFile.Log("Command: Search FFU by Product Type", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -SearchFFUbyProductType ");
+ }
+
ProductType = args[2];
LogFile.Log("Lumia model: " + ProductType, LogType.FileAndConsole);
URL = LumiaDownloadModel.SearchFFU(ProductType, null, null);
@@ -1189,7 +1403,10 @@ namespace WPinternals
{
NormalModel = (NokiaPhoneModel)Notifier.CurrentModel;
ProductType = NormalModel.ExecuteJsonMethodAsString("ReadManufacturerModelName", "ManufacturerModelName");
- if (ProductType.IndexOf('_') >= 0) ProductType = ProductType.Substring(0, ProductType.IndexOf('_'));
+ if (ProductType.Contains('_'))
+ {
+ ProductType = ProductType.Substring(0, ProductType.IndexOf('_'));
+ }
}
else if ((Notifier.CurrentInterface == PhoneInterfaces.Lumia_Bootloader) || (Notifier.CurrentInterface == PhoneInterfaces.Lumia_Flash))
{
@@ -1201,17 +1418,23 @@ namespace WPinternals
{
NormalModel = (NokiaPhoneModel)(await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Normal));
ProductType = NormalModel.ExecuteJsonMethodAsString("ReadManufacturerModelName", "ManufacturerModelName");
- if (ProductType.IndexOf('_') >= 0) ProductType = ProductType.Substring(0, ProductType.IndexOf('_'));
+ if (ProductType.Contains('_'))
+ {
+ ProductType = ProductType.Substring(0, ProductType.IndexOf('_'));
+ }
}
URLs = LumiaDownloadModel.SearchEmergencyFiles(ProductType);
if (URLs != null)
{
- if (args.Length >= 3)
- DownloadFolder = args[2];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 3
+ ? args[2]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
for (int i = 0; i < URLs.Length; i++)
{
@@ -1221,11 +1444,16 @@ namespace WPinternals
LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole);
EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName);
if (i == 0)
+ {
ProgrammerPath = EmergencyFilePath;
+ }
else
+ {
PayloadPath = EmergencyFilePath;
+ }
+
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URLs[i], EmergencyFilePath);
}
@@ -1238,17 +1466,23 @@ namespace WPinternals
case "downloademergencybyproducttype":
LogFile.Log("Command: Download Emergency files", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new WPinternalsException("Wrong number of arguments. Usage: WPinternals.exe -DownloadEmergencyByProductType ");
+ }
+
ProductType = args[2];
URLs = LumiaDownloadModel.SearchEmergencyFiles(ProductType);
if (URLs != null)
{
- if (args.Length >= 4)
- DownloadFolder = args[3];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 4
+ ? args[3]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
for (int i = 0; i < URLs.Length; i++)
{
@@ -1258,11 +1492,16 @@ namespace WPinternals
LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole);
EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName);
if (i == 0)
+ {
ProgrammerPath = EmergencyFilePath;
+ }
else
+ {
PayloadPath = EmergencyFilePath;
+ }
+
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URLs[i], EmergencyFilePath);
}
@@ -1292,12 +1531,15 @@ namespace WPinternals
ProductCode = NormalModel.ExecuteJsonMethodAsString("ReadProductCode", "ProductCode");
}
URL = LumiaDownloadModel.SearchFFU(null, ProductCode, null, out ProductType);
- if (args.Length >= 3)
- DownloadFolder = args[2];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 3
+ ? args[2]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
URI = new Uri(URL);
@@ -1305,7 +1547,7 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
@@ -1323,11 +1565,16 @@ namespace WPinternals
LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole);
EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName);
if (i == 0)
+ {
ProgrammerPath = EmergencyFilePath;
+ }
else
+ {
PayloadPath = EmergencyFilePath;
+ }
+
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URLs[i], EmergencyFilePath);
}
@@ -1336,17 +1583,20 @@ namespace WPinternals
App.Config.AddEmergencyToRepository(ProductType, ProgrammerPath, PayloadPath);
}
- if (App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == e.OSVersion)).Count() == 0)
+ if (!App.Config.FFURepository.Any(e => App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion)))
{
ProductType = "RM-1085";
URL = LumiaDownloadModel.SearchFFU(ProductType, null, null);
- if (args.Length >= 3)
- DownloadFolder = args[2];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 3
+ ? args[2]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
URI = new Uri(URL);
@@ -1354,30 +1604,38 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
LogFile.Log("Download finished", LogType.FileAndConsole);
App.Config.AddFfuToRepository(FFUFilePath);
- if (App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == e.OSVersion)).Count() == 0)
+ if (!App.Config.FFURepository.Any(e => App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion)))
+ {
throw new WPinternalsException("Unable to find compatible FFU", "No donor-FFU has been found in the repository with a supported OS version. You can add a donor-FFU within the download section of the tool or by using the command line. A donor-FFU can be for a different device and a different CPU than your device. It is only used to gather Operating System specific binaries to be patched and used as part of the unlock process.");
+ }
}
Notifier.Stop();
break;
case "downloadallbyproducttype":
LogFile.Log("Command: Download all by Product Type", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -DownloadAllByProductType ");
+ }
+
ProductType = args[2];
LogFile.Log("Product type: " + ProductType, LogType.FileAndConsole);
- if (args.Length >= 4)
- DownloadFolder = args[3];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 4
+ ? args[3]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
URL = LumiaDownloadModel.SearchFFU(ProductType, null, null);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
@@ -1386,7 +1644,7 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
@@ -1404,11 +1662,16 @@ namespace WPinternals
LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole);
EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName);
if (i == 0)
+ {
ProgrammerPath = EmergencyFilePath;
+ }
else
+ {
PayloadPath = EmergencyFilePath;
+ }
+
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URLs[i], EmergencyFilePath);
}
@@ -1417,17 +1680,20 @@ namespace WPinternals
App.Config.AddEmergencyToRepository(ProductType, ProgrammerPath, PayloadPath);
}
- if (App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == e.OSVersion)).Count() == 0)
+ if (!App.Config.FFURepository.Any(e => App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion)))
{
ProductType = "RM-1085";
URL = LumiaDownloadModel.SearchFFU(ProductType, null, null);
- if (args.Length >= 4)
- DownloadFolder = args[3];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 4
+ ? args[3]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
URI = new Uri(URL);
@@ -1435,30 +1701,38 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
LogFile.Log("Download finished", LogType.FileAndConsole);
App.Config.AddFfuToRepository(FFUFilePath);
- if (App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == e.OSVersion)).Count() == 0)
+ if (!App.Config.FFURepository.Any(e => App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion)))
+ {
throw new WPinternalsException("Unable to find compatible FFU", "No donor-FFU has been found in the repository with a supported OS version. You can add a donor-FFU within the download section of the tool or by using the command line. A donor-FFU can be for a different device and a different CPU than your device. It is only used to gather Operating System specific binaries to be patched and used as part of the unlock process.");
+ }
}
break;
case "downloadallbyproductcode":
LogFile.Log("Command: Download all by Product Code", LogType.FileAndConsole);
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -DownloadAllByProductCode ");
+ }
+
ProductCode = args[2];
LogFile.Log("Product code: " + ProductCode, LogType.FileAndConsole);
URL = LumiaDownloadModel.SearchFFU(null, ProductCode, null, out ProductType);
- if (args.Length >= 4)
- DownloadFolder = args[3];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 4
+ ? args[3]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
URI = new Uri(URL);
@@ -1466,7 +1740,7 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
@@ -1484,11 +1758,16 @@ namespace WPinternals
LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole);
EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName);
if (i == 0)
+ {
ProgrammerPath = EmergencyFilePath;
+ }
else
+ {
PayloadPath = EmergencyFilePath;
+ }
+
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URLs[i], EmergencyFilePath);
}
@@ -1497,17 +1776,20 @@ namespace WPinternals
App.Config.AddEmergencyToRepository(ProductType, ProgrammerPath, PayloadPath);
}
- if (App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == e.OSVersion)).Count() == 0)
+ if (!App.Config.FFURepository.Any(e => App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion)))
{
ProductType = "RM-1085";
URL = LumiaDownloadModel.SearchFFU(ProductType, null, null);
- if (args.Length >= 4)
- DownloadFolder = args[3];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 4
+ ? args[3]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
URI = new Uri(URL);
@@ -1515,31 +1797,39 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
LogFile.Log("Download finished", LogType.FileAndConsole);
App.Config.AddFfuToRepository(FFUFilePath);
- if (App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == e.OSVersion)).Count() == 0)
+ if (!App.Config.FFURepository.Any(e => App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion)))
+ {
throw new WPinternalsException("Unable to find compatible FFU", "No donor-FFU has been found in the repository with a supported OS version. You can add a donor-FFU within the download section of the tool or by using the command line. A donor-FFU can be for a different device and a different CPU than your device. It is only used to gather Operating System specific binaries to be patched and used as part of the unlock process.");
+ }
}
break;
case "downloadallbyoperatorcode":
LogFile.Log("Command: Download FFU by Operator Code", LogType.FileAndConsole);
if (args.Length < 4)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -DownloadFFUbyOperatorCode ");
+ }
+
ProductType = args[2];
LogFile.Log("Product type: " + ProductType, LogType.FileAndConsole);
OperatorCode = args[3];
LogFile.Log("Operator code: " + OperatorCode, LogType.FileAndConsole);
- if (args.Length >= 5)
- DownloadFolder = args[4];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 5
+ ? args[4]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
URL = LumiaDownloadModel.SearchFFU(ProductType, null, OperatorCode);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
@@ -1548,7 +1838,7 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
@@ -1566,11 +1856,16 @@ namespace WPinternals
LogFile.Log("File: " + EmergencyFileName, LogType.FileAndConsole);
EmergencyFilePath = Path.Combine(DownloadFolder, EmergencyFileName);
if (i == 0)
+ {
ProgrammerPath = EmergencyFilePath;
+ }
else
+ {
PayloadPath = EmergencyFilePath;
+ }
+
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URLs[i], EmergencyFilePath);
}
@@ -1579,17 +1874,20 @@ namespace WPinternals
App.Config.AddEmergencyToRepository(ProductType, ProgrammerPath, PayloadPath);
}
- if (App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == e.OSVersion)).Count() == 0)
+ if (!App.Config.FFURepository.Any(e => App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion)))
{
ProductType = "RM-1085";
URL = LumiaDownloadModel.SearchFFU(ProductType, null, null);
- if (args.Length >= 5)
- DownloadFolder = args[4];
- else
- DownloadFolder = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+ DownloadFolder = args.Length >= 5
+ ? args[4]
+ : Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\Repository\\" + ProductType.ToUpper());
+
if (!Directory.Exists(DownloadFolder))
+ {
Directory.CreateDirectory(DownloadFolder);
+ }
+
LogFile.Log("Download folder: " + DownloadFolder, LogType.FileAndConsole);
LogFile.Log("URL: " + URL, LogType.FileAndConsole);
URI = new Uri(URL);
@@ -1597,32 +1895,40 @@ namespace WPinternals
LogFile.Log("File: " + FFUFileName, LogType.FileAndConsole);
FFUFilePath = Path.Combine(DownloadFolder, FFUFileName);
LogFile.Log("Downloading...", LogType.FileAndConsole);
- using (System.Net.WebClient myWebClient = new System.Net.WebClient())
+ using (System.Net.WebClient myWebClient = new())
{
await myWebClient.DownloadFileTaskAsync(URL, FFUFilePath);
}
LogFile.Log("Download finished", LogType.FileAndConsole);
App.Config.AddFfuToRepository(FFUFilePath);
- if (App.Config.FFURepository.Where(e => App.PatchEngine.PatchDefinitions.Where(p => p.Name == "SecureBootHack-V2-EFIESP").First().TargetVersions.Any(v => v.Description == e.OSVersion)).Count() == 0)
+ if (!App.Config.FFURepository.Any(e => App.PatchEngine.PatchDefinitions.First(p => p.Name == "SecureBootHack-V2-EFIESP").TargetVersions.Any(v => v.Description == e.OSVersion)))
+ {
throw new WPinternalsException("Unable to find compatible FFU", "No donor-FFU has been found in the repository with a supported OS version. You can add a donor-FFU within the download section of the tool or by using the command line. A donor-FFU can be for a different device and a different CPU than your device. It is only used to gather Operating System specific binaries to be patched and used as part of the unlock process.");
+ }
}
break;
case "rewritepartitionsfrommassstorage":
if (args.Length < 2)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -RewritePartitionsFromMassStorage \n The name of the imgs must be the partition names. For example, DPP.img will get written to the DPP partition.");
+ }
await TestCode.RewriteParts(args[2]);
break;
case "restoregptusingedl":
if (args.Length < 3)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -RestoreGPTUsingEDL ");
+ }
await TestCode.RecoverBadGPT(args[2], args[3]);
break;
case "restoregptusingmassstorage":
if (args.Length < 2)
+ {
throw new ArgumentException("Wrong number of arguments. Usage: WPinternals.exe -RestoreGPTUsingMassStorage ");
+ }
await TestCode.RewriteGPT(args[2]);
break;
@@ -1700,8 +2006,10 @@ namespace WPinternals
LogFile.LogException(Ex);
}
- if (Environment.GetCommandLineArgs().Count() > 1)
+ if (Environment.GetCommandLineArgs().Length > 1)
+ {
CloseConsole();
+ }
}
// http://stackoverflow.com/questions/472282/show-console-in-windows-application
@@ -1711,7 +2019,9 @@ namespace WPinternals
internal static void OpenConsole()
{
if (IsConsoleVisible)
+ {
return;
+ }
if (AttachConsole(-1))
{
@@ -1742,10 +2052,10 @@ namespace WPinternals
// "The standard handles of a process may be redirected by a call to SetStdHandle, in which case GetStdHandle returns the redirected handle. If the standard handles have been redirected, you can specify the CONIN$ value in a call to the CreateFile function to get a handle to a console's input buffer. Similarly, you can specify the CONOUT$ value to get a handle to a console's active screen buffer."
// Get the handle to CONOUT$.
IntPtr stdHandle = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
- Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
- FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
+ Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new(stdHandle, true);
+ FileStream fileStream = new(safeFileHandle, FileAccess.Write);
Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
- StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
+ StreamWriter standardOutput = new(fileStream, encoding);
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}
diff --git a/DiscUtils/Block.cs b/DiscUtils/Block.cs
deleted file mode 100644
index 4d98399..0000000
--- a/DiscUtils/Block.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- internal class Block
- {
- public Block()
- {
- }
-
- public long Position { get; set; }
-
- public byte[] Data { get; set; }
-
- public int Available { get; set; }
-
- public bool Equals(Block other)
- {
- return Position == other.Position;
- }
- }
-}
diff --git a/DiscUtils/BlockCache.cs b/DiscUtils/BlockCache.cs
deleted file mode 100644
index 2d54ab7..0000000
--- a/DiscUtils/BlockCache.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- using System.Collections.Generic;
-
- internal class BlockCache
- where T : Block, new()
- {
- private int _blockSize;
- private Dictionary _blocks;
- private LinkedList _lru;
- private List _freeBlocks;
- private int _blocksCreated;
- private int _totalBlocks;
-
- private int _freeBlockCount;
-
- public BlockCache(int blockSize, int blockCount)
- {
- _blockSize = blockSize;
- _totalBlocks = blockCount;
-
- _blocks = new Dictionary();
- _lru = new LinkedList();
- _freeBlocks = new List(_totalBlocks);
-
- _freeBlockCount = _totalBlocks;
- }
-
- public int FreeBlockCount
- {
- get { return _freeBlockCount; }
- }
-
- public bool ContainsBlock(long position)
- {
- return _blocks.ContainsKey(position);
- }
-
- public bool TryGetBlock(long position, out T block)
- {
- if (_blocks.TryGetValue(position, out block))
- {
- _lru.Remove(block);
- _lru.AddFirst(block);
- return true;
- }
-
- return false;
- }
-
- public T GetBlock(long position)
- {
- T result;
-
- if (TryGetBlock(position, out result))
- {
- return result;
- }
-
- result = GetFreeBlock();
- result.Position = position;
- result.Available = -1;
- StoreBlock(result);
-
- return result;
- }
-
- public void ReleaseBlock(long position)
- {
- T block;
- if (_blocks.TryGetValue(position, out block))
- {
- _blocks.Remove(position);
- _lru.Remove(block);
- _freeBlocks.Add(block);
- _freeBlockCount++;
- }
- }
-
- private void StoreBlock(T block)
- {
- _blocks[block.Position] = block;
- _lru.AddFirst(block);
- }
-
- private T GetFreeBlock()
- {
- T block;
-
- if (_freeBlocks.Count > 0)
- {
- int idx = _freeBlocks.Count - 1;
- block = _freeBlocks[idx];
- _freeBlocks.RemoveAt(idx);
- _freeBlockCount--;
- }
- else if (_blocksCreated < _totalBlocks)
- {
- block = new T();
- block.Data = new byte[_blockSize];
- _blocksCreated++;
- _freeBlockCount--;
- }
- else
- {
- block = _lru.Last.Value;
- _lru.RemoveLast();
- _blocks.Remove(block.Position);
- }
-
- return block;
- }
- }
-}
diff --git a/DiscUtils/BlockCacheSettings.cs b/DiscUtils/BlockCacheSettings.cs
deleted file mode 100644
index ccc3ff6..0000000
--- a/DiscUtils/BlockCacheSettings.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- ///
- /// Settings controlling BlockCache instances.
- ///
- public sealed class BlockCacheSettings
- {
- ///
- /// Initializes a new instance of the BlockCacheSettings class.
- ///
- public BlockCacheSettings()
- {
- this.BlockSize = (int)(4 * Sizes.OneKiB);
- this.ReadCacheSize = 4 * Sizes.OneMiB;
- this.LargeReadSize = 64 * Sizes.OneKiB;
- this.OptimumReadSize = (int)(64 * Sizes.OneKiB);
- }
-
- ///
- /// Initializes a new instance of the BlockCacheSettings class.
- ///
- /// The cache settings.
- internal BlockCacheSettings(BlockCacheSettings settings)
- {
- this.BlockSize = settings.BlockSize;
- this.ReadCacheSize = settings.ReadCacheSize;
- this.LargeReadSize = settings.LargeReadSize;
- this.OptimumReadSize = settings.OptimumReadSize;
- }
-
- ///
- /// Gets or sets the size (in bytes) of each cached block.
- ///
- public int BlockSize { get; set; }
-
- ///
- /// Gets or sets the size (in bytes) of the read cache.
- ///
- public long ReadCacheSize { get; set; }
-
- ///
- /// Gets or sets the maximum read size that will be cached.
- ///
- /// Large reads are not cached, on the assumption they will not
- /// be repeated. This setting controls what is considered 'large'.
- /// Any read that is more than this many bytes will not be cached.
- public long LargeReadSize { get; set; }
-
- ///
- /// Gets or sets the optimum size of a read to the wrapped stream.
- ///
- /// This value must be a multiple of BlockSize.
- public int OptimumReadSize { get; set; }
- }
-}
diff --git a/DiscUtils/BlockCacheStatistics.cs b/DiscUtils/BlockCacheStatistics.cs
deleted file mode 100644
index 97a7d58..0000000
--- a/DiscUtils/BlockCacheStatistics.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- ///
- /// Statistical information about the effectiveness of a BlockCache instance.
- ///
- public sealed class BlockCacheStatistics
- {
- ///
- /// Gets the number of requested 'large' reads, as defined by the LargeReadSize setting.
- ///
- public long LargeReadsIn { get; internal set; }
-
- ///
- /// Gets the number of requested unaligned reads.
- ///
- /// Unaligned reads are reads where the read doesn't start on a multiple of
- /// the block size.
- public long UnalignedReadsIn { get; internal set; }
-
- ///
- /// Gets the total number of requested reads.
- ///
- public long TotalReadsIn { get; internal set; }
-
- ///
- /// Gets the total number of reads passed on by the cache.
- ///
- public long TotalReadsOut { get; internal set; }
-
- ///
- /// Gets the number of times a read request was serviced (in part or whole) from the cache.
- ///
- public long ReadCacheHits { get; internal set; }
-
- ///
- /// Gets the number of time a read request was serviced (in part or whole) from the wrapped stream.
- ///
- public long ReadCacheMisses { get; internal set; }
-
- ///
- /// Gets the number of requested unaligned writes.
- ///
- /// Unaligned writes are writes where the write doesn't start on a multiple of
- /// the block size.
- public long UnalignedWritesIn { get; internal set; }
-
- ///
- /// Gets the total number of requested writes.
- ///
- public long TotalWritesIn { get; internal set; }
-
- ///
- /// Gets the number of free blocks in the read cache.
- ///
- public int FreeReadBlocks { get; internal set; }
- }
-}
diff --git a/DiscUtils/BlockCacheStream.cs b/DiscUtils/BlockCacheStream.cs
deleted file mode 100644
index 722ce20..0000000
--- a/DiscUtils/BlockCacheStream.cs
+++ /dev/null
@@ -1,472 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- using System;
- using System.Collections.Generic;
- using System.IO;
-
- ///
- /// A stream implementing a block-oriented read cache.
- ///
- public sealed class BlockCacheStream : SparseStream
- {
- private SparseStream _wrappedStream;
- private Ownership _ownWrapped;
- private BlockCacheSettings _settings;
- private BlockCacheStatistics _stats;
-
- private long _position;
- private bool _atEof;
-
- private BlockCache _cache;
- private byte[] _readBuffer;
- private int _blocksInReadBuffer;
-
- ///
- /// Initializes a new instance of the BlockCacheStream class.
- ///
- /// The stream to wrap.
- /// Whether to assume ownership of toWrap.
- public BlockCacheStream(SparseStream toWrap, Ownership ownership)
- : this(toWrap, ownership, new BlockCacheSettings())
- {
- }
-
- ///
- /// Initializes a new instance of the BlockCacheStream class.
- ///
- /// The stream to wrap.
- /// Whether to assume ownership of toWrap.
- /// The cache settings.
- public BlockCacheStream(SparseStream toWrap, Ownership ownership, BlockCacheSettings settings)
- {
- if (!toWrap.CanRead)
- {
- throw new ArgumentException("The wrapped stream does not support reading", "toWrap");
- }
-
- if (!toWrap.CanSeek)
- {
- throw new ArgumentException("The wrapped stream does not support seeking", "toWrap");
- }
-
- _wrappedStream = toWrap;
- _ownWrapped = ownership;
- _settings = new BlockCacheSettings(settings);
-
- if (_settings.OptimumReadSize % _settings.BlockSize != 0)
- {
- throw new ArgumentException("Invalid settings, OptimumReadSize must be a multiple of BlockSize", "settings");
- }
-
- _readBuffer = new byte[_settings.OptimumReadSize];
- _blocksInReadBuffer = _settings.OptimumReadSize / _settings.BlockSize;
-
- int totalBlocks = (int)(_settings.ReadCacheSize / _settings.BlockSize);
-
- _cache = new BlockCache(_settings.BlockSize, totalBlocks);
- _stats = new BlockCacheStatistics();
- _stats.FreeReadBlocks = totalBlocks;
- }
-
- ///
- /// Gets the parts of the stream that are stored.
- ///
- /// This may be an empty enumeration if all bytes are zero.
- public override IEnumerable Extents
- {
- get
- {
- CheckDisposed();
- return _wrappedStream.Extents;
- }
- }
-
- ///
- /// Gets an indication as to whether the stream can be read.
- ///
- public override bool CanRead
- {
- get { return true; }
- }
-
- ///
- /// Gets an indication as to whether the stream position can be changed.
- ///
- public override bool CanSeek
- {
- get { return true; }
- }
-
- ///
- /// Gets an indication as to whether the stream can be written to.
- ///
- public override bool CanWrite
- {
- get { return _wrappedStream.CanWrite; }
- }
-
- ///
- /// Gets the length of the stream.
- ///
- public override long Length
- {
- get
- {
- CheckDisposed();
- return _wrappedStream.Length;
- }
- }
-
- ///
- /// Gets and sets the current stream position.
- ///
- public override long Position
- {
- get
- {
- CheckDisposed();
- return _position;
- }
-
- set
- {
- CheckDisposed();
- _position = value;
- }
- }
-
- ///
- /// Gets the performance statistics for this instance.
- ///
- public BlockCacheStatistics Statistics
- {
- get
- {
- _stats.FreeReadBlocks = _cache.FreeBlockCount;
- return _stats;
- }
- }
-
- ///
- /// Gets the parts of a stream that are stored, within a specified range.
- ///
- /// The offset of the first byte of interest.
- /// The number of bytes of interest.
- /// An enumeration of stream extents, indicating stored bytes.
- public override IEnumerable GetExtentsInRange(long start, long count)
- {
- CheckDisposed();
- return _wrappedStream.GetExtentsInRange(start, count);
- }
-
- ///
- /// Reads data from the stream.
- ///
- /// The buffer to fill.
- /// The buffer offset to start from.
- /// The number of bytes to read.
- /// The number of bytes read.
- public override int Read(byte[] buffer, int offset, int count)
- {
- CheckDisposed();
-
- if (_position >= Length)
- {
- if (_atEof)
- {
- throw new IOException("Attempt to read beyond end of stream");
- }
- else
- {
- _atEof = true;
- return 0;
- }
- }
-
- _stats.TotalReadsIn++;
-
- if (count > _settings.LargeReadSize)
- {
- _stats.LargeReadsIn++;
- _stats.TotalReadsOut++;
- _wrappedStream.Position = _position;
- int numRead = _wrappedStream.Read(buffer, offset, count);
- _position = _wrappedStream.Position;
-
- if (_position >= Length)
- {
- _atEof = true;
- }
-
- return numRead;
- }
-
- int totalBytesRead = 0;
- bool servicedFromCache = false;
- bool servicedOutsideCache = false;
- int blockSize = _settings.BlockSize;
-
- long firstBlock = _position / blockSize;
- int offsetInNextBlock = (int)(_position % blockSize);
- long endBlock = Utilities.Ceil(Math.Min(_position + count, Length), blockSize);
- int numBlocks = (int)(endBlock - firstBlock);
-
- if (offsetInNextBlock != 0)
- {
- _stats.UnalignedReadsIn++;
- }
-
- int blocksRead = 0;
- while (blocksRead < numBlocks)
- {
- Block block;
-
- // Read from the cache as much as possible
- while (blocksRead < numBlocks && _cache.TryGetBlock(firstBlock + blocksRead, out block))
- {
- int bytesToRead = Math.Min(count - totalBytesRead, block.Available - offsetInNextBlock);
-
- Array.Copy(block.Data, offsetInNextBlock, buffer, offset + totalBytesRead, bytesToRead);
- offsetInNextBlock = 0;
- totalBytesRead += bytesToRead;
- _position += bytesToRead;
- blocksRead++;
-
- servicedFromCache = true;
- }
-
- // Now handle a sequence of (one or more) blocks that are not cached
- if (blocksRead < numBlocks && !_cache.ContainsBlock(firstBlock + blocksRead))
- {
- servicedOutsideCache = true;
-
- // Figure out how many blocks to read from the wrapped stream
- int blocksToRead = 0;
- while (blocksRead + blocksToRead < numBlocks
- && blocksToRead < _blocksInReadBuffer
- && !_cache.ContainsBlock(firstBlock + blocksRead + blocksToRead))
- {
- ++blocksToRead;
- }
-
- // Allow for the end of the stream not being block-aligned
- long readPosition = (firstBlock + blocksRead) * (long)blockSize;
- int bytesToRead = (int)Math.Min(blocksToRead * (long)blockSize, Length - readPosition);
-
- // Do the read
- _stats.TotalReadsOut++;
- _wrappedStream.Position = readPosition;
- int bytesRead = Utilities.ReadFully(_wrappedStream, _readBuffer, 0, bytesToRead);
- if (bytesRead != bytesToRead)
- {
- throw new IOException("Short read before end of stream");
- }
-
- // Cache the read blocks
- for (int i = 0; i < blocksToRead; ++i)
- {
- int copyBytes = Math.Min(blockSize, bytesToRead - (i * blockSize));
- block = _cache.GetBlock(firstBlock + blocksRead + i);
- Array.Copy(_readBuffer, i * blockSize, block.Data, 0, copyBytes);
- block.Available = copyBytes;
-
- if (copyBytes < blockSize)
- {
- Array.Clear(_readBuffer, (i * blockSize) + copyBytes, blockSize - copyBytes);
- }
- }
-
- blocksRead += blocksToRead;
-
- // Propogate the data onto the caller
- int bytesToCopy = Math.Min(count - totalBytesRead, bytesRead - offsetInNextBlock);
- Array.Copy(_readBuffer, offsetInNextBlock, buffer, offset + totalBytesRead, bytesToCopy);
- totalBytesRead += bytesToCopy;
- _position += bytesToCopy;
- offsetInNextBlock = 0;
- }
- }
-
- if (_position >= Length && totalBytesRead == 0)
- {
- _atEof = true;
- }
-
- if (servicedFromCache)
- {
- _stats.ReadCacheHits++;
- }
-
- if (servicedOutsideCache)
- {
- _stats.ReadCacheMisses++;
- }
-
- return totalBytesRead;
- }
-
- ///
- /// Flushes the stream.
- ///
- public override void Flush()
- {
- CheckDisposed();
- _wrappedStream.Flush();
- }
-
- ///
- /// Moves the stream position.
- ///
- /// The origin-relative location.
- /// The base location.
- /// The new absolute stream position.
- public override long Seek(long offset, SeekOrigin origin)
- {
- CheckDisposed();
-
- long effectiveOffset = offset;
- if (origin == SeekOrigin.Current)
- {
- effectiveOffset += _position;
- }
- else if (origin == SeekOrigin.End)
- {
- effectiveOffset += Length;
- }
-
- _atEof = false;
-
- if (effectiveOffset < 0)
- {
- throw new IOException("Attempt to move before beginning of disk");
- }
- else
- {
- _position = effectiveOffset;
- return _position;
- }
- }
-
- ///
- /// Sets the length of the stream.
- ///
- /// The new length.
- public override void SetLength(long value)
- {
- CheckDisposed();
- _wrappedStream.SetLength(value);
- }
-
- ///
- /// Writes data to the stream at the current location.
- ///
- /// The data to write.
- /// The first byte to write from buffer.
- /// The number of bytes to write.
- public override void Write(byte[] buffer, int offset, int count)
- {
- CheckDisposed();
-
- _stats.TotalWritesIn++;
-
- int blockSize = _settings.BlockSize;
- long firstBlock = _position / blockSize;
- long endBlock = Utilities.Ceil(Math.Min(_position + count, Length), blockSize);
- int numBlocks = (int)(endBlock - firstBlock);
-
- try
- {
- _wrappedStream.Position = _position;
- _wrappedStream.Write(buffer, offset, count);
- }
- catch
- {
- InvalidateBlocks(firstBlock, numBlocks);
- throw;
- }
-
- int offsetInNextBlock = (int)(_position % blockSize);
- if (offsetInNextBlock != 0)
- {
- _stats.UnalignedWritesIn++;
- }
-
- // For each block touched, if it's cached, update it
- int bytesProcessed = 0;
- for (int i = 0; i < numBlocks; ++i)
- {
- int bufferPos = offset + bytesProcessed;
- int bytesThisBlock = Math.Min(count - bytesProcessed, blockSize - offsetInNextBlock);
-
- Block block;
- if (_cache.TryGetBlock(firstBlock + i, out block))
- {
- Array.Copy(buffer, bufferPos, block.Data, offsetInNextBlock, bytesThisBlock);
- block.Available = Math.Max(block.Available, offsetInNextBlock + bytesThisBlock);
- }
-
- offsetInNextBlock = 0;
- bytesProcessed += bytesThisBlock;
- }
-
- _position += count;
- }
-
- ///
- /// Disposes of this instance, freeing up associated resources.
- ///
- /// true if invoked from Dispose, else false.
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (_wrappedStream != null && _ownWrapped == Ownership.Dispose)
- {
- _wrappedStream.Dispose();
- }
-
- _wrappedStream = null;
- }
-
- base.Dispose(disposing);
- }
-
- private void CheckDisposed()
- {
- if (_wrappedStream == null)
- {
- throw new ObjectDisposedException("BlockCacheStream");
- }
- }
-
- private void InvalidateBlocks(long firstBlock, int numBlocks)
- {
- for (long i = firstBlock; i < (firstBlock + numBlocks); ++i)
- {
- _cache.ReleaseBlock(i);
- }
- }
- }
-}
diff --git a/DiscUtils/BootConfig/ApplicationImageType.cs b/DiscUtils/BootConfig/ApplicationImageType.cs
deleted file mode 100644
index 9725607..0000000
--- a/DiscUtils/BootConfig/ApplicationImageType.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- ///
- /// Enumeration of known application image types.
- ///
- public enum ApplicationImageType
- {
- ///
- /// Unknown type.
- ///
- None = 0x0,
-
- ///
- /// Firmware application.
- ///
- Firmware = 0x1,
-
- ///
- /// Windows boot loader.
- ///
- WindowsBoot = 0x2,
-
- ///
- /// Legacy boot loader.
- ///
- LegacyLoader = 0x3,
-
- ///
- /// Real mode boot loader.
- ///
- RealMode = 0x4
- }
-}
diff --git a/DiscUtils/BootConfig/ApplicationType.cs b/DiscUtils/BootConfig/ApplicationType.cs
deleted file mode 100644
index c6d32a9..0000000
--- a/DiscUtils/BootConfig/ApplicationType.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- ///
- /// Enumeration of known application types.
- ///
- public enum ApplicationType
- {
- ///
- /// Unknown type.
- ///
- None = 0,
-
- ///
- /// Firmware boot manager (e.g. UEFI).
- ///
- FirmwareBootManager = 1,
-
- ///
- /// Windows boot manager.
- ///
- BootManager = 2,
-
- ///
- /// Operating System Loader.
- ///
- OsLoader = 3,
-
- ///
- /// Resume loader.
- ///
- Resume = 4,
-
- ///
- /// Memory diagnostic application.
- ///
- MemoryDiagnostics = 5,
-
- ///
- /// Legacy NT loader application.
- ///
- NtLoader = 6,
-
- ///
- /// Windows setup application.
- ///
- SetupLoader = 7,
-
- ///
- /// Boot sector application.
- ///
- BootSector = 8,
-
- ///
- /// Startup application.
- ///
- Startup = 9
- }
-}
diff --git a/DiscUtils/BootConfig/BaseStorage.cs b/DiscUtils/BootConfig/BaseStorage.cs
deleted file mode 100644
index 3322099..0000000
--- a/DiscUtils/BootConfig/BaseStorage.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using System;
- using System.Collections.Generic;
-
- ///
- /// Base class for BCD storage repositories.
- ///
- internal abstract class BaseStorage
- {
- ///
- /// Tests if an element is present (i.e. has a value) on an object.
- ///
- /// The object to inspect.
- /// The element to inspect.
- /// true if present, else false.
- public abstract bool HasValue(Guid obj, int element);
-
- ///
- /// Gets the value of a string element.
- ///
- /// The object to inspect.
- /// The element to retrieve.
- /// The value as a string.
- public abstract string GetString(Guid obj, int element);
-
- public abstract byte[] GetBinary(Guid obj, int element);
-
- public abstract void SetString(Guid obj, int element, string value);
-
- public abstract void SetBinary(Guid obj, int element, byte[] value);
-
- public abstract string[] GetMultiString(Guid obj, int element);
-
- public abstract void SetMultiString(Guid obj, int element, string[] values);
-
- public abstract IEnumerable EnumerateObjects();
-
- public abstract IEnumerable EnumerateElements(Guid obj);
-
- public abstract int GetObjectType(Guid obj);
-
- public abstract bool ObjectExists(Guid obj);
-
- public abstract Guid CreateObject(Guid obj, int type);
-
- public abstract void CreateElement(Guid obj, int element);
-
- public abstract void DeleteObject(Guid obj);
-
- public abstract void DeleteElement(Guid obj, int element);
- }
-}
diff --git a/DiscUtils/BootConfig/BcdObject.cs b/DiscUtils/BootConfig/BcdObject.cs
deleted file mode 100644
index 934ea3e..0000000
--- a/DiscUtils/BootConfig/BcdObject.cs
+++ /dev/null
@@ -1,365 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-//
-// Symbolic names of BCD Objects taken from Geoff Chappell's website:
-// http://www.geoffchappell.com/viewer.htm?doc=notes/windows/boot/bcd/objects.htm
-//
-//
-
-namespace DiscUtils.BootConfig
-{
- using System;
- using System.Collections.Generic;
-
- ///
- /// Represents a Boot Configuration Database object (application, device or inherited settings).
- ///
- public class BcdObject
- {
- ///
- /// Well-known object for Emergency Management Services settings.
- ///
- public const string EmsSettingsGroupId = "{0CE4991B-E6B3-4B16-B23C-5E0D9250E5D9}";
-
- ///
- /// Well-known object for the Resume boot loader.
- ///
- public const string ResumeLoaderSettingsGroupId = "{1AFA9C49-16AB-4A5C-4A90-212802DA9460}";
-
- ///
- /// Alias for the Default boot entry.
- ///
- public const string DefaultBootEntryId = "{1CAE1EB7-A0DF-4D4D-9851-4860E34EF535}";
-
- ///
- /// Well-known object for Emergency Management Services settings.
- ///
- public const string DebuggerSettingsGroupId = "{4636856E-540F-4170-A130-A84776F4C654}";
-
- ///
- /// Well-known object for NTLDR application.
- ///
- public const string WindowsLegacyNtldrId = "{466F5A88-0AF2-4F76-9038-095B170DC21C}";
-
- ///
- /// Well-known object for bad memory settings.
- ///
- public const string BadMemoryGroupId = "{5189B25C-5558-4BF2-BCA4-289B11BD29E2}";
-
- ///
- /// Well-known object for Boot Loader settings.
- ///
- public const string BootLoaderSettingsGroupId = "{6EFB52BF-1766-41DB-A6B3-0EE5EFF72BD7}";
-
- ///
- /// Well-known object for EFI setup.
- ///
- public const string WindowsSetupEfiId = "{7254A080-1510-4E85-AC0F-E7FB3D444736}";
-
- ///
- /// Well-known object for Global settings.
- ///
- public const string GlobalSettingsGroupId = "{7EA2E1AC-2E61-4728-AAA3-896D9D0A9F0E}";
-
- ///
- /// Well-known object for Windows Boot Manager.
- ///
- public const string WindowsBootManagerId = "{9DEA862C-5CDD-4E70-ACC1-F32B344D4795}";
-
- ///
- /// Well-known object for PCAT Template.
- ///
- public const string WindowsOsTargetTemplatePcatId = "{A1943BBC-EA85-487C-97C7-C9EDE908A38A}";
-
- ///
- /// Well-known object for Firmware Boot Manager.
- ///
- public const string FirmwareBootManagerId = "{A5A30FA2-3D06-4E9F-B5F4-A01DF9D1FCBA}";
-
- ///
- /// Well-known object for Windows Setup RAMDISK options.
- ///
- public const string WindowsSetupRamdiskOptionsId = "{AE5534E0-A924-466C-B836-758539A3EE3A}";
-
- ///
- /// Well-known object for EFI template.
- ///
- public const string WindowsOsTargetTemplateEfiId = "{B012B84D-C47C-4ED5-B722-C0C42163E569}";
-
- ///
- /// Well-known object for Windows memory tester application.
- ///
- public const string WindowsMemoryTesterId = "{B2721D73-1DB4-4C62-BF78-C548A880142D}";
-
- ///
- /// Well-known object for Windows PCAT setup.
- ///
- public const string WindowsSetupPcatId = "{CBD971BF-B7B8-4885-951A-FA03044F5D71}";
-
- ///
- /// Alias for the current boot entry.
- ///
- public const string CurrentBootEntryId = "{FA926493-6F1C-4193-A414-58F0B2456D1E}";
-
- private static Dictionary s_nameToGuid;
- private static Dictionary s_guidToName;
-
- private BaseStorage _storage;
- private Guid _id;
- private int _type;
-
- static BcdObject()
- {
- s_nameToGuid = new Dictionary();
- s_guidToName = new Dictionary();
-
- AddMapping("{emssettings}", EmsSettingsGroupId);
- AddMapping("{resumeloadersettings}", ResumeLoaderSettingsGroupId);
- AddMapping("{default}", DefaultBootEntryId);
- AddMapping("{dbgsettings}", DebuggerSettingsGroupId);
- AddMapping("{legacy}", WindowsLegacyNtldrId);
- AddMapping("{ntldr}", WindowsLegacyNtldrId);
- AddMapping("{badmemory}", BadMemoryGroupId);
- AddMapping("{bootloadersettings}", BootLoaderSettingsGroupId);
- AddMapping("{globalsettings}", GlobalSettingsGroupId);
- AddMapping("{bootmgr}", WindowsBootManagerId);
- AddMapping("{fwbootmgr}", FirmwareBootManagerId);
- AddMapping("{ramdiskoptions}", WindowsSetupRamdiskOptionsId);
- AddMapping("{memdiag}", WindowsMemoryTesterId);
- AddMapping("{current}", CurrentBootEntryId);
- }
-
- internal BcdObject(BaseStorage store, Guid id)
- {
- _storage = store;
- _id = id;
- _type = _storage.GetObjectType(id);
- }
-
- ///
- /// Gets the identity of this object.
- ///
- public Guid Identity
- {
- get { return _id; }
- }
-
- ///
- /// Gets the friendly name for this object, if known.
- ///
- public string FriendlyName
- {
- get
- {
- string name;
- if (s_guidToName.TryGetValue(_id, out name))
- {
- return name;
- }
-
- return _id.ToString("B");
- }
- }
-
- ///
- /// Gets the object type for this object.
- ///
- public ObjectType ObjectType
- {
- get { return (ObjectType)((_type >> 28) & 0xF); }
- }
-
- ///
- /// Gets the image type for this application.
- ///
- public ApplicationImageType ApplicationImageType
- {
- get { return IsApplication ? (ApplicationImageType)((_type & 0x00F00000) >> 20) : 0; }
- }
-
- ///
- /// Gets the application type for this application.
- ///
- public ApplicationType ApplicationType
- {
- get { return IsApplication ? (ApplicationType)(_type & 0xFFFFF) : 0; }
- }
-
- ///
- /// Gets the elements in this object.
- ///
- public IEnumerable Elements
- {
- get
- {
- foreach (var el in _storage.EnumerateElements(_id))
- {
- yield return new Element(_storage, _id, ApplicationType, el);
- }
- }
- }
-
- private bool IsApplication
- {
- get { return ObjectType == ObjectType.Application; }
- }
-
- ///
- /// Indicates if the settings in this object are inheritable by another object.
- ///
- /// The type of the object to test for inheritability.
- /// true if the settings can be inherited, else false.
- public bool IsInheritableBy(ObjectType type)
- {
- if (type == ObjectType.Inherit)
- {
- throw new ArgumentException("Can not test inheritability by inherit objects", "type");
- }
-
- if (ObjectType != ObjectType.Inherit)
- {
- return false;
- }
-
- InheritType setting = (InheritType)((_type & 0x00F00000) >> 20);
-
- return setting == InheritType.AnyObject
- || (setting == InheritType.ApplicationObjects && type == ObjectType.Application)
- || (setting == InheritType.DeviceObjects && type == ObjectType.Device);
- }
-
- ///
- /// Indicates if this object has a specific element.
- ///
- /// The identity of the element to look for.
- /// true if present, else false.
- public bool HasElement(int id)
- {
- return _storage.HasValue(_id, id);
- }
-
- ///
- /// Indicates if this object has a specific element.
- ///
- /// The identity of the element to look for.
- /// true if present, else false.
- public bool HasElement(WellKnownElement id)
- {
- return HasElement((int)id);
- }
-
- ///
- /// Gets a specific element in this object.
- ///
- /// The identity of the element to look for.
- /// The element object.
- public Element GetElement(int id)
- {
- if (HasElement(id))
- {
- return new Element(_storage, _id, ApplicationType, id);
- }
-
- return null;
- }
-
- ///
- /// Gets a specific element in this object.
- ///
- /// The identity of the element to look for.
- /// The element object.
- public Element GetElement(WellKnownElement id)
- {
- return GetElement((int)id);
- }
-
- ///
- /// Adds an element in this object.
- ///
- /// The identity of the element to add.
- /// The initial value of the element.
- /// The element object.
- public Element AddElement(int id, ElementValue initialValue)
- {
- _storage.CreateElement(_id, id);
- Element el = new Element(_storage, _id, ApplicationType, id);
- el.Value = initialValue;
- return el;
- }
-
- ///
- /// Adds an element in this object.
- ///
- /// The identity of the element to add.
- /// The initial value of the element.
- /// The element object.
- public Element AddElement(WellKnownElement id, ElementValue initialValue)
- {
- return AddElement((int)id, initialValue);
- }
-
- ///
- /// Removes a specific element.
- ///
- /// The element to remove.
- public void RemoveElement(int id)
- {
- _storage.DeleteElement(_id, id);
- }
-
- ///
- /// Removes a specific element.
- ///
- /// The element to remove.
- public void RemoveElement(WellKnownElement id)
- {
- RemoveElement((int)id);
- }
-
- ///
- /// Returns the object identity as a GUID string.
- ///
- /// A string representation, with surrounding curly braces.
- public override string ToString()
- {
- return _id.ToString("B");
- }
-
- internal static int MakeApplicationType(ApplicationImageType imageType, ApplicationType appType)
- {
- return 0x10000000 | (((int)imageType << 20) & 0x00F00000) | ((int)appType & 0x0000FFFF);
- }
-
- internal static int MakeInheritType(InheritType inheritType)
- {
- return 0x20000000 | (((int)inheritType << 20) & 0x00F00000);
- }
-
- private static void AddMapping(string name, string id)
- {
- Guid guid = new Guid(id);
- s_nameToGuid[name] = guid;
- s_guidToName[guid] = name;
- }
- }
-}
diff --git a/DiscUtils/BootConfig/BooleanElementValue.cs b/DiscUtils/BootConfig/BooleanElementValue.cs
deleted file mode 100644
index 39c2fe8..0000000
--- a/DiscUtils/BootConfig/BooleanElementValue.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- internal class BooleanElementValue : ElementValue
- {
- private bool _value;
-
- public BooleanElementValue(byte[] value)
- {
- _value = value[0] != 0;
- }
-
- public BooleanElementValue(bool value)
- {
- _value = value;
- }
-
- public override ElementFormat Format
- {
- get { return ElementFormat.Boolean; }
- }
-
- public override string ToString()
- {
- return _value ? "True" : "False";
- }
-
- internal byte[] GetBytes()
- {
- return new byte[] { (_value ? (byte)1 : (byte)0) };
- }
- }
-}
diff --git a/DiscUtils/BootConfig/DeviceAndPathRecord.cs b/DiscUtils/BootConfig/DeviceAndPathRecord.cs
deleted file mode 100644
index c86fe1b..0000000
--- a/DiscUtils/BootConfig/DeviceAndPathRecord.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using System;
- using System.Text;
-
- internal class DeviceAndPathRecord : DeviceRecord
- {
- private DeviceRecord _container;
- private string _path;
-
- public override int Size
- {
- get { throw new NotImplementedException(); }
- }
-
- public override void GetBytes(byte[] data, int offset)
- {
- throw new NotImplementedException();
- }
-
- public override string ToString()
- {
- return _container.ToString() + ":" + _path;
- }
-
- protected override void DoParse(byte[] data, int offset)
- {
- base.DoParse(data, offset);
-
- _container = DeviceRecord.Parse(data, offset + 0x34);
-
- int pathStart = 0x34 + _container.Size;
- _path = Encoding.Unicode.GetString(data, offset + pathStart, Length - pathStart);
- }
- }
-}
diff --git a/DiscUtils/BootConfig/DeviceElementValue.cs b/DiscUtils/BootConfig/DeviceElementValue.cs
deleted file mode 100644
index 65aff9a..0000000
--- a/DiscUtils/BootConfig/DeviceElementValue.cs
+++ /dev/null
@@ -1,114 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using System;
- using System.Globalization;
-
- internal class DeviceElementValue : ElementValue
- {
- private Guid _parentObject;
- private DeviceRecord _record;
-
- public DeviceElementValue()
- {
- _parentObject = Guid.Empty;
-
- PartitionRecord record = new PartitionRecord();
- record.Type = 5;
- _record = record;
- }
-
- public DeviceElementValue(Guid parentObject, PhysicalVolumeInfo pvi)
- {
- _parentObject = parentObject;
-
- PartitionRecord record = new PartitionRecord();
- record.Type = 6;
- if (pvi.VolumeType == PhysicalVolumeType.BiosPartition)
- {
- record.PartitionType = 1;
- record.DiskIdentity = new byte[4];
- Utilities.WriteBytesLittleEndian(pvi.DiskSignature, record.DiskIdentity, 0);
- record.PartitionIdentity = new byte[8];
- Utilities.WriteBytesLittleEndian(pvi.PhysicalStartSector * 512, record.PartitionIdentity, 0);
- }
- else if (pvi.VolumeType == PhysicalVolumeType.GptPartition)
- {
- record.PartitionType = 0;
- record.DiskIdentity = new byte[16];
- Utilities.WriteBytesLittleEndian(pvi.DiskIdentity, record.DiskIdentity, 0);
- record.PartitionIdentity = new byte[16];
- Utilities.WriteBytesLittleEndian(pvi.PartitionIdentity, record.PartitionIdentity, 0);
- }
- else
- {
- throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "Unknown how to convert volume type {0} to a Device element", pvi.VolumeType));
- }
-
- _record = record;
- }
-
- public DeviceElementValue(byte[] value)
- {
- _parentObject = Utilities.ToGuidLittleEndian(value, 0x00);
- _record = DeviceRecord.Parse(value, 0x10);
- }
-
- public override Guid ParentObject
- {
- get { return _parentObject; }
- }
-
- public override ElementFormat Format
- {
- get { return ElementFormat.Device; }
- }
-
- public override string ToString()
- {
- if (_parentObject != Guid.Empty)
- {
- return _parentObject.ToString() + ":" + _record.ToString();
- }
- else if (_record != null)
- {
- return _record.ToString();
- }
- else
- {
- return "";
- }
- }
-
- internal byte[] GetBytes()
- {
- byte[] buffer = new byte[_record.Size + 0x10];
-
- Utilities.WriteBytesLittleEndian(_parentObject, buffer, 0);
- _record.GetBytes(buffer, 0x10);
-
- return buffer;
- }
- }
-}
diff --git a/DiscUtils/BootConfig/DeviceRecord.cs b/DiscUtils/BootConfig/DeviceRecord.cs
deleted file mode 100644
index 2418d39..0000000
--- a/DiscUtils/BootConfig/DeviceRecord.cs
+++ /dev/null
@@ -1,84 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using System;
- using System.IO;
-
- internal abstract class DeviceRecord
- {
- public int Type { get; set; }
-
- public int Length { get; set; }
-
- public abstract int Size { get; }
-
- public static DeviceRecord Parse(byte[] data, int offset)
- {
- int type = Utilities.ToInt32LittleEndian(data, offset);
- int length = Utilities.ToInt32LittleEndian(data, offset + 0x8);
- if (offset + length > data.Length)
- {
- throw new InvalidDataException("Device record is truncated");
- }
-
- DeviceRecord newRecord = null;
- switch (type)
- {
- case 0:
- newRecord = new DeviceAndPathRecord();
- break;
- case 5: // Logical 'boot' device
- case 6: // Disk partition
- newRecord = new PartitionRecord();
- break;
- case 8: // custom:nnnnnn
- break;
- default:
- throw new NotImplementedException("Unknown device type: " + type);
- }
-
- if (newRecord != null)
- {
- newRecord.DoParse(data, offset);
- }
-
- return newRecord;
- }
-
- public abstract void GetBytes(byte[] data, int offset);
-
- protected virtual void DoParse(byte[] data, int offset)
- {
- Type = Utilities.ToInt32LittleEndian(data, offset);
- Length = Utilities.ToInt32LittleEndian(data, offset + 0x8);
- }
-
- protected void WriteHeader(byte[] data, int offset)
- {
- Length = Size;
- Utilities.WriteBytesLittleEndian(Type, data, offset);
- Utilities.WriteBytesLittleEndian(Size, data, offset + 0x8);
- }
- }
-}
diff --git a/DiscUtils/BootConfig/DiscUtilsRegistryStorage.cs b/DiscUtils/BootConfig/DiscUtilsRegistryStorage.cs
deleted file mode 100644
index 9c65e2b..0000000
--- a/DiscUtils/BootConfig/DiscUtilsRegistryStorage.cs
+++ /dev/null
@@ -1,162 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using DiscUtils.Registry;
- using System;
- using System.Collections.Generic;
- using System.Globalization;
-
- internal class DiscUtilsRegistryStorage : BaseStorage
- {
- private const string ElementsPathTemplate = @"Objects\{0}\Elements";
- private const string ElementPathTemplate = @"Objects\{0}\Elements\{1:X8}";
- private const string ObjectTypePathTemplate = @"Objects\{0}\Description";
- private const string ObjectsPath = @"Objects";
-
- private RegistryKey _rootKey;
-
- public DiscUtilsRegistryStorage(RegistryKey key)
- {
- _rootKey = key;
- }
-
- public override string GetString(Guid obj, int element)
- {
- return GetValue(obj, element) as string;
- }
-
- public override void SetString(Guid obj, int element, string value)
- {
- SetValue(obj, element, value);
- }
-
- public override byte[] GetBinary(Guid obj, int element)
- {
- return GetValue(obj, element) as byte[];
- }
-
- public override void SetBinary(Guid obj, int element, byte[] value)
- {
- SetValue(obj, element, value);
- }
-
- public override string[] GetMultiString(Guid obj, int element)
- {
- return GetValue(obj, element) as string[];
- }
-
- public override void SetMultiString(Guid obj, int element, string[] values)
- {
- SetValue(obj, element, values);
- }
-
- public override IEnumerable EnumerateObjects()
- {
- RegistryKey parentKey = _rootKey.OpenSubKey("Objects");
- foreach (var key in parentKey.GetSubKeyNames())
- {
- yield return new Guid(key);
- }
- }
-
- public override IEnumerable EnumerateElements(Guid obj)
- {
- string path = string.Format(CultureInfo.InvariantCulture, ElementsPathTemplate, obj.ToString("B"));
- RegistryKey parentKey = _rootKey.OpenSubKey(path);
- foreach (var key in parentKey.GetSubKeyNames())
- {
- yield return int.Parse(key, NumberStyles.HexNumber);
- }
- }
-
- public override int GetObjectType(Guid obj)
- {
- string path = string.Format(CultureInfo.InvariantCulture, ObjectTypePathTemplate, obj.ToString("B"));
-
- RegistryKey descKey = _rootKey.OpenSubKey(path);
-
- object val = descKey.GetValue("Type");
- return (int)val;
- }
-
- public override bool HasValue(Guid obj, int element)
- {
- string path = string.Format(CultureInfo.InvariantCulture, ElementPathTemplate, obj.ToString("B"), element);
- return _rootKey.OpenSubKey(path) != null;
- }
-
- public override bool ObjectExists(Guid obj)
- {
- string path = string.Format(CultureInfo.InvariantCulture, ObjectTypePathTemplate, obj.ToString("B"));
-
- return _rootKey.OpenSubKey(path) != null;
- }
-
- public override Guid CreateObject(Guid obj, int type)
- {
- Guid realObj = (obj == Guid.Empty) ? Guid.NewGuid() : obj;
- string path = string.Format(CultureInfo.InvariantCulture, ObjectTypePathTemplate, realObj.ToString("B"));
-
- RegistryKey key = _rootKey.CreateSubKey(path);
- key.SetValue("Type", type, RegistryValueType.Dword);
-
- return realObj;
- }
-
- public override void CreateElement(Guid obj, int element)
- {
- string path = string.Format(CultureInfo.InvariantCulture, ElementPathTemplate, obj.ToString("B"), element);
-
- _rootKey.CreateSubKey(path);
- }
-
- public override void DeleteObject(Guid obj)
- {
- string path = string.Format(CultureInfo.InvariantCulture, ObjectTypePathTemplate, obj.ToString("B"));
-
- _rootKey.DeleteSubKeyTree(path);
- }
-
- public override void DeleteElement(Guid obj, int element)
- {
- string path = string.Format(CultureInfo.InvariantCulture, ElementPathTemplate, obj.ToString("B"), element);
-
- _rootKey.DeleteSubKeyTree(path);
- }
-
- private object GetValue(Guid obj, int element)
- {
- string path = string.Format(CultureInfo.InvariantCulture, ElementPathTemplate, obj.ToString("B"), element);
- RegistryKey key = _rootKey.OpenSubKey(path);
- return key.GetValue("Element");
- }
-
- private void SetValue(Guid obj, int element, object value)
- {
- string path = string.Format(CultureInfo.InvariantCulture, ElementPathTemplate, obj.ToString("B"), element);
- RegistryKey key = _rootKey.OpenSubKey(path);
- key.SetValue("Element", value);
- }
- }
-}
diff --git a/DiscUtils/BootConfig/Element.cs b/DiscUtils/BootConfig/Element.cs
deleted file mode 100644
index a75c4f2..0000000
--- a/DiscUtils/BootConfig/Element.cs
+++ /dev/null
@@ -1,390 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-//
-// Symbolic names of BCD Elements taken from Geoff Chappell's website:
-// http://www.geoffchappell.com/viewer.htm?doc=notes/windows/boot/bcd/elements.htm
-//
-//
-
-namespace DiscUtils.BootConfig
-{
- using System;
- using System.Globalization;
-
- ///
- /// Represents an element in a Boot Configuration Database object.
- ///
- public class Element
- {
- private BaseStorage _storage;
- private Guid _obj;
- private ApplicationType _appType;
- private int _identifier;
- private ElementValue _value;
-
- internal Element(BaseStorage storage, Guid obj, ApplicationType appType, int identifier)
- {
- _storage = storage;
- _obj = obj;
- _appType = appType;
- _identifier = identifier;
- }
-
- ///
- /// Gets the friendly name of the element, if any.
- ///
- public string FriendlyName
- {
- get
- {
- return "{" + IdentifierToName(_appType, _identifier) + "}";
- }
- }
-
- ///
- /// Gets the class of the element.
- ///
- public ElementClass Class
- {
- get { return (ElementClass)((_identifier >> 28) & 0xF); }
- }
-
- ///
- /// Gets the element's format.
- ///
- public ElementFormat Format
- {
- get { return (ElementFormat)((_identifier >> 24) & 0xF); }
- }
-
- ///
- /// Gets or sets the element's value.
- ///
- public ElementValue Value
- {
- get
- {
- if (_value == null)
- {
- _value = LoadValue();
- }
-
- return _value;
- }
-
- set
- {
- if (Format != value.Format)
- {
- throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Attempt to assign {1} value to {0} format element", Format, value.Format));
- }
-
- _value = value;
- WriteValue();
- }
- }
-
- ///
- /// Gets the element's id as a hex string.
- ///
- /// A hex string.
- public override string ToString()
- {
- return _identifier.ToString("X8", CultureInfo.InvariantCulture);
- }
-
- private static string IdentifierToName(ApplicationType appType, int identifier)
- {
- ElementClass idClass = GetClass(identifier);
- if (idClass == ElementClass.Library)
- {
- switch (identifier)
- {
- case 0x11000001: return "device";
- case 0x12000002: return "path";
- case 0x12000004: return "description";
- case 0x12000005: return "locale";
- case 0x14000006: return "inherit";
- case 0x15000007: return "truncatememory";
- case 0x14000008: return "recoverysequence";
- case 0x16000009: return "recoveryenabled";
- case 0x1700000A: return "badmemorylist";
- case 0x1600000B: return "badmemoryaccess";
- case 0x1500000C: return "firstmegabytepolicy";
-
- case 0x16000010: return "bootdebug";
- case 0x15000011: return "debugtype";
- case 0x15000012: return "debugaddress";
- case 0x15000013: return "debugport";
- case 0x15000014: return "baudrate";
- case 0x15000015: return "channel";
- case 0x12000016: return "targetname";
- case 0x16000017: return "noumex";
- case 0x15000018: return "debugstart";
-
- case 0x16000020: return "bootems";
- case 0x15000022: return "emsport";
- case 0x15000023: return "emsbaudrate";
-
- case 0x12000030: return "loadoptions";
-
- case 0x16000040: return "advancedoptions";
- case 0x16000041: return "optionsedit";
- case 0x15000042: return "keyringaddress";
- case 0x16000046: return "graphicsmodedisabled";
- case 0x15000047: return "configaccesspolicy";
- case 0x16000048: return "nointegritychecks";
- case 0x16000049: return "testsigning";
- case 0x16000050: return "extendedinput";
- case 0x15000051: return "initialconsoleinput";
- }
- }
- else if (idClass == ElementClass.Application)
- {
- switch (appType)
- {
- case ApplicationType.FirmwareBootManager:
- case ApplicationType.BootManager:
- switch (identifier)
- {
- case 0x24000001: return "displayorder";
- case 0x24000002: return "bootsequence";
- case 0x23000003: return "default";
- case 0x25000004: return "timeout";
- case 0x26000005: return "resume";
- case 0x23000006: return "resumeobject";
-
- case 0x24000010: return "toolsdisplayorder";
-
- case 0x26000020: return "displaybootmenu";
- case 0x26000021: return "noerrordisplay";
- case 0x21000022: return "bcddevice";
- case 0x22000023: return "bcdfilepath";
-
- case 0x27000030: return "customactions";
- }
-
- break;
-
- case ApplicationType.OsLoader:
- switch (identifier)
- {
- case 0x21000001: return "osdevice";
- case 0x22000002: return "systemroot";
- case 0x23000003: return "resumeobject";
-
- case 0x26000010: return "detecthal";
- case 0x22000011: return "kernel";
- case 0x22000012: return "hal";
- case 0x22000013: return "dbgtransport";
-
- case 0x25000020: return "nx";
- case 0x25000021: return "pae";
- case 0x26000022: return "winpe";
- case 0x26000024: return "nocrashautoreboot";
- case 0x26000025: return "lastknowngood";
- case 0x26000026: return "oslnointegritychecks";
- case 0x26000027: return "osltestsigning";
-
- case 0x26000030: return "nolowmem";
- case 0x25000031: return "removememory";
- case 0x25000032: return "increaseuserva";
- case 0x25000033: return "perfmem";
-
- case 0x26000040: return "vga";
- case 0x26000041: return "quietboot";
- case 0x26000042: return "novesa";
-
- case 0x25000050: return "clustermodeaddressing";
- case 0x26000051: return "usephysicaldestination";
- case 0x25000052: return "restrictapiccluster";
-
- case 0x26000060: return "onecpu";
- case 0x25000061: return "numproc";
- case 0x26000062: return "maxproc";
- case 0x25000063: return "configflags";
-
- case 0x26000070: return "usefirmwarepcisettings";
- case 0x25000071: return "msi";
- case 0x25000072: return "pciexpress";
-
- case 0x25000080: return "safeboot";
- case 0x26000081: return "safebootalternateshell";
-
- case 0x26000090: return "bootlog";
- case 0x26000091: return "sos";
-
- case 0x260000A0: return "debug";
- case 0x260000A1: return "halbreakpoint";
-
- case 0x260000B0: return "ems";
-
- case 0x250000C0: return "forcefailure";
- case 0x250000C1: return "driverloadfailurepolicy";
-
- case 0x250000E0: return "bootstatuspolicy";
- }
-
- break;
-
- case ApplicationType.Resume:
- switch (identifier)
- {
- case 0x21000001: return "filedevice";
- case 0x22000002: return "filepath";
- case 0x26000003: return "customsettings";
- case 0x26000004: return "pae";
- case 0x21000005: return "associatedosdevice";
- case 0x26000006: return "debugoptionenabled";
- }
-
- break;
-
- case ApplicationType.MemoryDiagnostics:
- switch (identifier)
- {
- case 0x25000001: return "passcount";
- case 0x25000002: return "testmix";
- case 0x25000003: return "failurecount";
- case 0x25000004: return "testtofail";
- }
-
- break;
-
- case ApplicationType.NtLoader:
- case ApplicationType.SetupLoader:
- switch (identifier)
- {
- case 0x22000001: return "bpbstring";
- }
-
- break;
-
- case ApplicationType.Startup:
- switch (identifier)
- {
- case 0x26000001: return "pxesoftreboot";
- case 0x22000002: return "applicationname";
- }
-
- break;
- }
- }
- else if (idClass == ElementClass.Device)
- {
- switch (identifier)
- {
- case 0x35000001: return "ramdiskimageoffset";
- case 0x35000002: return "ramdisktftpclientport";
- case 0x31000003: return "ramdisksdidevice";
- case 0x32000004: return "ramdisksdipath";
- case 0x35000005: return "ramdiskimagelength";
- case 0x36000006: return "exportascd";
- case 0x35000007: return "ramdisktftpblocksize";
- }
- }
- else if (idClass == ElementClass.Hidden)
- {
- switch (identifier)
- {
- case 0x45000001: return "devicetype";
- case 0x42000002: return "apprelativepath";
- case 0x42000003: return "ramdiskdevicerelativepath";
- case 0x46000004: return "omitosloaderelements";
- case 0x46000010: return "recoveryos";
- }
- }
-
- return identifier.ToString("X8", CultureInfo.InvariantCulture);
- }
-
- private static ElementClass GetClass(int identifier)
- {
- return (ElementClass)((identifier >> 28) & 0xF);
- }
-
- private ElementValue LoadValue()
- {
- switch (Format)
- {
- case ElementFormat.Boolean:
- return new BooleanElementValue(_storage.GetBinary(_obj, _identifier));
-
- case ElementFormat.Device:
- return new DeviceElementValue(_storage.GetBinary(_obj, _identifier));
-
- case ElementFormat.Guid:
- return new GuidElementValue(_storage.GetString(_obj, _identifier));
-
- case ElementFormat.GuidList:
- return new GuidListElementValue(_storage.GetMultiString(_obj, _identifier));
-
- case ElementFormat.Integer:
- return new IntegerElementValue(_storage.GetBinary(_obj, _identifier));
-
- case ElementFormat.IntegerList:
- return new IntegerListElementValue(_storage.GetBinary(_obj, _identifier));
-
- case ElementFormat.String:
- return new StringElementValue(_storage.GetString(_obj, _identifier));
-
- default:
- throw new NotImplementedException("Unknown element format: " + Format);
- }
- }
-
- private void WriteValue()
- {
- switch (_value.Format)
- {
- case ElementFormat.Boolean:
- _storage.SetBinary(_obj, _identifier, ((BooleanElementValue)_value).GetBytes());
- break;
-
- case ElementFormat.Device:
- _storage.SetBinary(_obj, _identifier, ((DeviceElementValue)_value).GetBytes());
- break;
-
- case ElementFormat.GuidList:
- _storage.SetMultiString(_obj, _identifier, ((GuidListElementValue)_value).GetGuidStrings());
- break;
-
- case ElementFormat.Integer:
- _storage.SetBinary(_obj, _identifier, ((IntegerElementValue)_value).GetBytes());
- break;
-
- case ElementFormat.IntegerList:
- _storage.SetBinary(_obj, _identifier, ((IntegerListElementValue)_value).GetBytes());
- break;
-
- case ElementFormat.Guid:
- case ElementFormat.String:
- _storage.SetString(_obj, _identifier, _value.ToString());
- break;
-
- default:
- throw new NotImplementedException("Unknown element format: " + Format);
- }
- }
- }
-}
diff --git a/DiscUtils/BootConfig/ElementClass.cs b/DiscUtils/BootConfig/ElementClass.cs
deleted file mode 100644
index cf8aecd..0000000
--- a/DiscUtils/BootConfig/ElementClass.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- ///
- /// The known classes of element.
- ///
- public enum ElementClass
- {
- ///
- /// Unknown class.
- ///
- None = 0,
-
- ///
- /// Common setting.
- ///
- Library = 1,
-
- ///
- /// An application setting.
- ///
- Application = 2,
-
- ///
- /// A device (or partition) setting.
- ///
- Device = 3,
-
- ///
- /// A hidden setting.
- ///
- Hidden = 4
- }
-}
diff --git a/DiscUtils/BootConfig/ElementFormat.cs b/DiscUtils/BootConfig/ElementFormat.cs
deleted file mode 100644
index 49101e3..0000000
--- a/DiscUtils/BootConfig/ElementFormat.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- ///
- /// The known formats used to store BCD values.
- ///
- public enum ElementFormat
- {
- ///
- /// Unknown format.
- ///
- None = 0,
-
- ///
- /// A block device, or partition.
- ///
- Device = 1,
-
- ///
- /// A unicode string.
- ///
- String = 2,
-
- ///
- /// A Globally Unique Identifier (GUID).
- ///
- Guid = 3,
-
- ///
- /// A GUID list.
- ///
- GuidList = 4,
-
- ///
- /// An integer.
- ///
- Integer = 5,
-
- ///
- /// A boolean.
- ///
- Boolean = 6,
-
- ///
- /// An integer list.
- ///
- IntegerList = 7
- }
-}
diff --git a/DiscUtils/BootConfig/ElementValue.cs b/DiscUtils/BootConfig/ElementValue.cs
deleted file mode 100644
index 8b52ea8..0000000
--- a/DiscUtils/BootConfig/ElementValue.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using System;
-
- ///
- /// The value of an element.
- ///
- public abstract class ElementValue
- {
- ///
- /// Gets the format of the value.
- ///
- public abstract ElementFormat Format { get; }
-
- ///
- /// Gets the parent object (only for Device values).
- ///
- public virtual Guid ParentObject
- {
- get { return Guid.Empty; }
- }
-
- ///
- /// Gets a value representing a device (aka partition).
- ///
- /// Object containing detailed information about the device.
- /// The volume to represent.
- /// The value as an object.
- public static ElementValue ForDevice(Guid parentObject, PhysicalVolumeInfo physicalVolume)
- {
- return new DeviceElementValue(parentObject, physicalVolume);
- }
-
- ///
- /// Gets a value representing the logical boot device.
- ///
- /// The boot pseudo-device as an object.
- public static ElementValue ForBootDevice()
- {
- return new DeviceElementValue();
- }
-
- ///
- /// Gets a value representing a string value.
- ///
- /// The value to convert.
- /// The value as an object.
- public static ElementValue ForString(string value)
- {
- return new StringElementValue(value);
- }
-
- ///
- /// Gets a value representing an integer value.
- ///
- /// The value to convert.
- /// The value as an object.
- public static ElementValue ForInteger(long value)
- {
- return new IntegerElementValue((ulong)value);
- }
-
- ///
- /// Gets a value representing an integer list value.
- ///
- /// The value to convert.
- /// The value as an object.
- public static ElementValue ForIntegerList(long[] values)
- {
- ulong[] ulValues = new ulong[values.Length];
- for (int i = 0; i < values.Length; ++i)
- {
- ulValues[i] = (ulong)values[i];
- }
-
- return new IntegerListElementValue(ulValues);
- }
-
- ///
- /// Gets a value representing a boolean value.
- ///
- /// The value to convert.
- /// The value as an object.
- public static ElementValue ForBoolean(bool value)
- {
- return new BooleanElementValue(value);
- }
-
- ///
- /// Gets a value representing a GUID value.
- ///
- /// The value to convert.
- /// The value as an object.
- public static ElementValue ForGuid(Guid value)
- {
- return new GuidElementValue(value.ToString("B"));
- }
-
- ///
- /// Gets a value representing a GUID list value.
- ///
- /// The value to convert.
- /// The value as an object.
- public static ElementValue ForGuidList(Guid[] values)
- {
- string[] strValues = new string[values.Length];
- for (int i = 0; i < values.Length; ++i)
- {
- strValues[i] = values[i].ToString("B");
- }
-
- return new GuidListElementValue(strValues);
- }
- }
-}
diff --git a/DiscUtils/BootConfig/GuidElementValue.cs b/DiscUtils/BootConfig/GuidElementValue.cs
deleted file mode 100644
index d6d89f7..0000000
--- a/DiscUtils/BootConfig/GuidElementValue.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- internal class GuidElementValue : ElementValue
- {
- private string _value;
-
- public GuidElementValue(string value)
- {
- _value = value;
- }
-
- public override ElementFormat Format
- {
- get { return ElementFormat.Guid; }
- }
-
- public override string ToString()
- {
- if (string.IsNullOrEmpty(_value))
- {
- return "";
- }
-
- return _value;
- }
- }
-}
diff --git a/DiscUtils/BootConfig/GuidListElementValue.cs b/DiscUtils/BootConfig/GuidListElementValue.cs
deleted file mode 100644
index edad6cd..0000000
--- a/DiscUtils/BootConfig/GuidListElementValue.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- internal class GuidListElementValue : ElementValue
- {
- private string[] _values;
-
- public GuidListElementValue(string[] values)
- {
- _values = values;
- }
-
- public override ElementFormat Format
- {
- get { return ElementFormat.GuidList; }
- }
-
- public override string ToString()
- {
- if (_values == null || _values.Length == 0)
- {
- return "";
- }
-
- string result = _values[0];
- for (int i = 1; i < _values.Length; ++i)
- {
- result += "," + _values[i];
- }
-
- return result;
- }
-
- internal string[] GetGuidStrings()
- {
- return _values;
- }
- }
-}
diff --git a/DiscUtils/BootConfig/InheritType.cs b/DiscUtils/BootConfig/InheritType.cs
deleted file mode 100644
index bc8747a..0000000
--- a/DiscUtils/BootConfig/InheritType.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- ///
- /// Indicates the type of objects that can inherit from an object.
- ///
- public enum InheritType
- {
- ///
- /// Undefined value.
- ///
- None = 0x0,
-
- ///
- /// Any type of object may inherit from this object.
- ///
- AnyObject = 0x1,
-
- ///
- /// Only Application objects may inherit from this object.
- ///
- ApplicationObjects = 0x2,
-
- ///
- /// Only Device objects may inherit from this object.
- ///
- DeviceObjects = 0x3
- }
-}
diff --git a/DiscUtils/BootConfig/IntegerElementValue.cs b/DiscUtils/BootConfig/IntegerElementValue.cs
deleted file mode 100644
index 8deea77..0000000
--- a/DiscUtils/BootConfig/IntegerElementValue.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using System;
- using System.Globalization;
-
- internal class IntegerElementValue : ElementValue
- {
- private ulong _value;
-
- public IntegerElementValue(byte[] value)
- {
- // Actual bytes stored may be less than 8
- byte[] buffer = new byte[8];
- Array.Copy(value, buffer, value.Length);
-
- _value = Utilities.ToUInt64LittleEndian(buffer, 0);
- }
-
- public IntegerElementValue(ulong value)
- {
- _value = value;
- }
-
- public override ElementFormat Format
- {
- get { return ElementFormat.Integer; }
- }
-
- public override string ToString()
- {
- return string.Format(CultureInfo.InvariantCulture, "{0}", _value);
- }
-
- internal byte[] GetBytes()
- {
- byte[] bytes = new byte[8];
- Utilities.WriteBytesLittleEndian(_value, bytes, 0);
- return bytes;
- }
- }
-}
diff --git a/DiscUtils/BootConfig/IntegerListElementValue.cs b/DiscUtils/BootConfig/IntegerListElementValue.cs
deleted file mode 100644
index ab2fb11..0000000
--- a/DiscUtils/BootConfig/IntegerListElementValue.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using System.Globalization;
-
- internal class IntegerListElementValue : ElementValue
- {
- private ulong[] _values;
-
- public IntegerListElementValue(byte[] value)
- {
- _values = new ulong[value.Length / 8];
- for (int i = 0; i < _values.Length; ++i)
- {
- _values[i] = Utilities.ToUInt64LittleEndian(value, i * 8);
- }
- }
-
- public IntegerListElementValue(ulong[] values)
- {
- _values = values;
- }
-
- public override ElementFormat Format
- {
- get { return ElementFormat.IntegerList; }
- }
-
- public override string ToString()
- {
- if (_values == null || _values.Length == 0)
- {
- return "";
- }
-
- string result = string.Empty;
- for (int i = 0; i < _values.Length; ++i)
- {
- if (i != 0)
- {
- result += " ";
- }
-
- result += _values[i].ToString("X16", CultureInfo.InvariantCulture);
- }
-
- return result;
- }
-
- internal byte[] GetBytes()
- {
- byte[] bytes = new byte[_values.Length * 8];
- for (int i = 0; i < _values.Length; ++i)
- {
- Utilities.WriteBytesLittleEndian(_values[i], bytes, i * 8);
- }
-
- return bytes;
- }
- }
-}
diff --git a/DiscUtils/BootConfig/ObjectType.cs b/DiscUtils/BootConfig/ObjectType.cs
deleted file mode 100644
index 89db8b8..0000000
--- a/DiscUtils/BootConfig/ObjectType.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- ///
- /// Enumeration of known object types.
- ///
- public enum ObjectType
- {
- ///
- /// An unknown type.
- ///
- None = 0x0,
-
- ///
- /// An application object.
- ///
- Application = 0x1,
-
- ///
- /// Inheritable common settings.
- ///
- Inherit = 0x2,
-
- ///
- /// Device (or partition) object.
- ///
- Device = 0x3
- }
-}
diff --git a/DiscUtils/BootConfig/PartitionRecord.cs b/DiscUtils/BootConfig/PartitionRecord.cs
deleted file mode 100644
index 537084b..0000000
--- a/DiscUtils/BootConfig/PartitionRecord.cs
+++ /dev/null
@@ -1,149 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using System;
- using System.Globalization;
-
- internal class PartitionRecord : DeviceRecord
- {
- public int PartitionType { get; set; }
-
- public byte[] DiskIdentity { get; set; }
-
- public byte[] PartitionIdentity { get; set; }
-
- public override int Size
- {
- get { return 0x48; }
- }
-
- public override void GetBytes(byte[] data, int offset)
- {
- WriteHeader(data, offset);
-
- if (Type == 5)
- {
- Array.Clear(data, offset + 0x10, 0x38);
- }
- else if (Type == 6)
- {
- Utilities.WriteBytesLittleEndian(PartitionType, data, offset + 0x24);
-
- if (PartitionType == 1)
- {
- Array.Copy(DiskIdentity, 0, data, offset + 0x28, 4);
- Array.Copy(PartitionIdentity, 0, data, offset + 0x10, 8);
- }
- else if (PartitionType == 0)
- {
- Array.Copy(DiskIdentity, 0, data, offset + 0x28, 16);
- Array.Copy(PartitionIdentity, 0, data, offset + 0x10, 16);
- }
- else
- {
- throw new NotImplementedException("Unknown partition type: " + PartitionType);
- }
- }
- else
- {
- throw new NotImplementedException("Unknown device type: " + Type);
- }
- }
-
- public override string ToString()
- {
- if (Type == 5)
- {
- return "";
- }
- else if (Type == 6)
- {
- if (PartitionType == 1)
- {
- return string.Format(
- CultureInfo.InvariantCulture,
- "(disk:{0:X2}{1:X2}{2:X2}{3:X2} part-offset:{4})",
- DiskIdentity[0],
- DiskIdentity[1],
- DiskIdentity[2],
- DiskIdentity[3],
- Utilities.ToUInt64LittleEndian(PartitionIdentity, 0));
- }
- else
- {
- Guid diskGuid = Utilities.ToGuidLittleEndian(DiskIdentity, 0);
- Guid partitionGuid = Utilities.ToGuidLittleEndian(PartitionIdentity, 0);
- return string.Format(CultureInfo.InvariantCulture, "(disk:{0} partition:{1})", diskGuid, partitionGuid);
- }
- }
- else if (Type == 8)
- {
- return "custom:";
- }
- else
- {
- return "";
- }
- }
-
- protected override void DoParse(byte[] data, int offset)
- {
- base.DoParse(data, offset);
-
- if (Type == 5)
- {
- // Nothing to do - just empty...
- }
- else if (Type == 6)
- {
- PartitionType = Utilities.ToInt32LittleEndian(data, offset + 0x24);
-
- if (PartitionType == 1)
- {
- // BIOS disk
- DiskIdentity = new byte[4];
- Array.Copy(data, offset + 0x28, DiskIdentity, 0, 4);
- PartitionIdentity = new byte[8];
- Array.Copy(data, offset + 0x10, PartitionIdentity, 0, 8);
- }
- else if (PartitionType == 0)
- {
- // GPT disk
- DiskIdentity = new byte[16];
- Array.Copy(data, offset + 0x28, DiskIdentity, 0, 16);
- PartitionIdentity = new byte[16];
- Array.Copy(data, offset + 0x10, PartitionIdentity, 0, 16);
- }
- else
- {
- throw new NotImplementedException("Unknown partition type: " + PartitionType);
- }
- }
- else
- {
- throw new NotImplementedException("Unknown device type: " + Type);
- }
- }
- }
-}
diff --git a/DiscUtils/BootConfig/Store.cs b/DiscUtils/BootConfig/Store.cs
deleted file mode 100644
index 2ee939a..0000000
--- a/DiscUtils/BootConfig/Store.cs
+++ /dev/null
@@ -1,168 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- using DiscUtils.Registry;
- using System;
- using System.Collections.Generic;
-
- ///
- /// Represents a Boot Configuration Database store (i.e. a BCD file).
- ///
- public class Store
- {
- private BaseStorage _store;
-
- ///
- /// Initializes a new instance of the Store class.
- ///
- /// The registry key that is the root of the configuration database.
- public Store(RegistryKey key)
- {
- _store = new DiscUtilsRegistryStorage(key);
- }
-
- ///
- /// Gets the objects within the store.
- ///
- public IEnumerable Objects
- {
- get
- {
- foreach (var obj in _store.EnumerateObjects())
- {
- yield return new BcdObject(_store, obj);
- }
- }
- }
-
- ///
- /// Initializes a new Boot Configuration Database.
- ///
- /// The registry key at the root of the database.
- /// The BCD store.
- public static Store Initialize(RegistryKey root)
- {
- RegistryKey descKey = root.CreateSubKey("Description");
- descKey.SetValue("KeyName", "BCD00000001");
- root.CreateSubKey("Objects");
- return new Store(root);
- }
-
- ///
- /// Gets an object from the store.
- ///
- /// The identity of the object.
- /// The requested object, or null.
- public BcdObject GetObject(Guid id)
- {
- if (_store.ObjectExists(id))
- {
- return new BcdObject(_store, id);
- }
- else
- {
- return null;
- }
- }
-
- ///
- /// Creates a specific object.
- ///
- /// The identity of the object to create.
- /// The object's type.
- /// The object representing the new application.
- public BcdObject CreateObject(Guid id, int type)
- {
- _store.CreateObject(id, type);
- return new BcdObject(_store, id);
- }
-
- ///
- /// Creates an application object.
- ///
- /// The image type of the application.
- /// The application's type.
- /// The object representing the new application.
- public BcdObject CreateApplication(ApplicationImageType imageType, ApplicationType appType)
- {
- Guid obj = _store.CreateObject(Guid.NewGuid(), BcdObject.MakeApplicationType(imageType, appType));
- return new BcdObject(_store, obj);
- }
-
- ///
- /// Creates an application object.
- ///
- /// The identity of the object to create.
- /// The image type of the application.
- /// The application's type.
- /// The object representing the new application.
- public BcdObject CreateApplication(Guid id, ApplicationImageType imageType, ApplicationType appType)
- {
- Guid obj = _store.CreateObject(id, BcdObject.MakeApplicationType(imageType, appType));
- return new BcdObject(_store, obj);
- }
-
- ///
- /// Creates an 'inherit' object that contains common settings.
- ///
- /// The type of object the settings apply to.
- /// The object representing the new settings.
- public BcdObject CreateInherit(InheritType inheritType)
- {
- Guid obj = _store.CreateObject(Guid.NewGuid(), BcdObject.MakeInheritType(inheritType));
- return new BcdObject(_store, obj);
- }
-
- ///
- /// Creates an 'inherit' object that contains common settings.
- ///
- /// The identity of the object to create.
- /// The type of object the settings apply to.
- /// The object representing the new settings.
- public BcdObject CreateInherit(Guid id, InheritType inheritType)
- {
- Guid obj = _store.CreateObject(id, BcdObject.MakeInheritType(inheritType));
- return new BcdObject(_store, obj);
- }
-
- ///
- /// Creates a new device object, representing a partition.
- ///
- /// The object representing the new device.
- public BcdObject CreateDevice()
- {
- Guid obj = _store.CreateObject(Guid.NewGuid(), 0x30000000);
- return new BcdObject(_store, obj);
- }
-
- ///
- /// Removes an object.
- ///
- /// The identity of the object to remove.
- public void RemoveObject(Guid id)
- {
- _store.DeleteObject(id);
- }
- }
-}
diff --git a/DiscUtils/BootConfig/StringElementValue.cs b/DiscUtils/BootConfig/StringElementValue.cs
deleted file mode 100644
index 39ff24e..0000000
--- a/DiscUtils/BootConfig/StringElementValue.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils.BootConfig
-{
- internal class StringElementValue : ElementValue
- {
- private string _value;
-
- public StringElementValue(string value)
- {
- _value = value;
- }
-
- public override ElementFormat Format
- {
- get { return ElementFormat.String; }
- }
-
- public override string ToString()
- {
- return _value;
- }
- }
-}
diff --git a/DiscUtils/BootConfig/WellKnownElement.cs b/DiscUtils/BootConfig/WellKnownElement.cs
deleted file mode 100644
index 84ae8b5..0000000
--- a/DiscUtils/BootConfig/WellKnownElement.cs
+++ /dev/null
@@ -1,618 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-//
-// Symbolic names of BCD Elements taken from Geoff Chappell's website:
-// http://www.geoffchappell.com/viewer.htm?doc=notes/windows/boot/bcd/elements.htm
-//
-//
-
-namespace DiscUtils.BootConfig
-{
- ///
- /// Enumeration of known BCD elements.
- ///
- public enum WellKnownElement : int
- {
- ///
- /// Not specified.
- ///
- None = 0,
-
- ///
- /// Device containing the application.
- ///
- LibraryApplicationDevice = 0x11000001,
-
- ///
- /// Path to the application.
- ///
- LibraryApplicationPath = 0x12000002,
-
- ///
- /// Description of the object.
- ///
- LibraryDescription = 0x12000004,
-
- ///
- /// Preferred locale of the object.
- ///
- LibraryPreferredLocale = 0x12000005,
-
- ///
- /// Objects containing elements inherited by the object.
- ///
- LibraryInheritedObjects = 0x14000006,
-
- ///
- /// Upper bound on physical addresses used by Windows.
- ///
- LibraryTruncatePhysicalMemory = 0x15000007,
-
- ///
- /// List of objects, indicating recovery sequence.
- ///
- LibraryRecoverySequence = 0x14000008,
-
- ///
- /// Enables auto recovery.
- ///
- LibraryAutoRecoveryEnabled = 0x16000009,
-
- ///
- /// List of bad memory regions.
- ///
- LibraryBadMemoryList = 0x1700000A,
-
- ///
- /// Allow use of bad memory regions.
- ///
- LibraryAllowBadMemoryAccess = 0x1600000B,
-
- ///
- /// Policy on use of first mega-byte of physical RAM.
- ///
- /// 0 = UseNone, 1 = UseAll, 2 = UsePrivate.
- LibraryFirstMegaBytePolicy = 0x1500000C,
-
- ///
- /// Debugger enabled.
- ///
- LibraryDebuggerEnabled = 0x16000010,
-
- ///
- /// Debugger type.
- ///
- /// 0 = Serial, 1 = 1394, 2 = USB.
- LibraryDebuggerType = 0x15000011,
-
- ///
- /// Debugger serial port address.
- ///
- LibraryDebuggerSerialAddress = 0x15000012,
-
- ///
- /// Debugger serial port.
- ///
- LibraryDebuggerSerialPort = 0x15000013,
-
- ///
- /// Debugger serial port baud rate.
- ///
- LibraryDebuggerSerialBaudRate = 0x15000014,
-
- ///
- /// Debugger 1394 channel.
- ///
- LibraryDebugger1394Channel = 0x15000015,
-
- ///
- /// Debugger USB target name.
- ///
- LibraryDebuggerUsbTargetName = 0x12000016,
-
- ///
- /// Debugger ignores user mode exceptions.
- ///
- LibraryDebuggerIgnoreUserModeExceptions = 0x16000017,
-
- ///
- /// Debugger start policy.
- ///
- /// 0 = Active, 1 = AutoEnable, 2 = Disable.
- LibraryDebuggerStartPolicy = 0x15000018,
-
- ///
- /// Emergency Management System enabled.
- ///
- LibraryEmergencyManagementSystemEnabled = 0x16000020,
-
- ///
- /// Emergency Management System serial port.
- ///
- LibraryEmergencyManagementSystemPort = 0x15000022,
-
- ///
- /// Emergency Management System baud rate.
- ///
- LibraryEmergencyManagementSystemBaudRate = 0x15000023,
-
- ///
- /// Load options.
- ///
- LibraryLoadOptions = 0x12000030,
-
- ///
- /// Displays advanced options.
- ///
- LibraryDisplayAdvancedOptions = 0x16000040,
-
- ///
- /// Displays UI to edit advanced options.
- ///
- LibraryDisplayOptionsEdit = 0x16000041,
-
- ///
- /// FVE (Full Volume Encryption - aka BitLocker?) KeyRing address.
- ///
- LibraryFveKeyRingAddress = 0x16000042,
-
- ///
- /// Device to contain Boot Status Log.
- ///
- LibraryBootStatusLogDevice = 0x11000043,
-
- ///
- /// Path to Boot Status Log.
- ///
- LibraryBootStatusLogFile = 0x12000044,
-
- ///
- /// Whether to append to the existing Boot Status Log.
- ///
- LibraryBootStatusLogAppend = 0x12000045,
-
- ///
- /// Disables graphics mode.
- ///
- LibraryGraphicsModeDisabled = 0x16000046,
-
- ///
- /// Configure access policy.
- ///
- /// 0 = default, 1 = DisallowMmConfig.
- LibraryConfigAccessPolicy = 0x15000047,
-
- ///
- /// Disables integrity checks.
- ///
- LibraryDisableIntegrityChecks = 0x16000048,
-
- ///
- /// Allows pre-release signatures (test signing).
- ///
- LibraryAllowPrereleaseSignatures = 0x16000049,
-
- ///
- /// Console extended input.
- ///
- LibraryConsoleExtendedInput = 0x16000050,
-
- ///
- /// Initial console input.
- ///
- LibraryInitialConsoleInput = 0x15000051,
-
- ///
- /// Application display order.
- ///
- BootMgrDisplayOrder = 0x24000001,
-
- ///
- /// Application boot sequence.
- ///
- BootMgrBootSequence = 0x24000002,
-
- ///
- /// Default application.
- ///
- BootMgrDefaultObject = 0x23000003,
-
- ///
- /// User input timeout.
- ///
- BootMgrTimeout = 0x25000004,
-
- ///
- /// Attempt to resume from hibernated state.
- ///
- BootMgrAttemptResume = 0x26000005,
-
- ///
- /// The resume application.
- ///
- BootMgrResumeObject = 0x23000006,
-
- ///
- /// The tools display order.
- ///
- BootMgrToolsDisplayOrder = 0x24000010,
-
- ///
- /// Displays the boot menu.
- ///
- BootMgrDisplayBootMenu = 0x26000020,
-
- ///
- /// No error display.
- ///
- BootMgrNoErrorDisplay = 0x26000021,
-
- ///
- /// The BCD device.
- ///
- BootMgrBcdDevice = 0x21000022,
-
- ///
- /// The BCD file path.
- ///
- BootMgrBcdFilePath = 0x22000023,
-
- ///
- /// The custom actions list.
- ///
- BootMgrCustomActionsList = 0x27000030,
-
- ///
- /// Device containing the Operating System.
- ///
- OsLoaderOsDevice = 0x21000001,
-
- ///
- /// System root on the OS device.
- ///
- OsLoaderSystemRoot = 0x22000002,
-
- ///
- /// The resume application associated with this OS.
- ///
- OsLoaderAssociatedResumeObject = 0x23000003,
-
- ///
- /// Auto-detect the correct kernel & HAL.
- ///
- OsLoaderDetectKernelAndHal = 0x26000010,
-
- ///
- /// The filename of the kernel.
- ///
- OsLoaderKernelPath = 0x22000011,
-
- ///
- /// The filename of the HAL.
- ///
- OsLoaderHalPath = 0x22000012,
-
- ///
- /// The debug transport path.
- ///
- OsLoaderDebugTransportPath = 0x22000013,
-
- ///
- /// NX (No-Execute) policy.
- ///
- /// 0 = OptIn, 1 = OptOut, 2 = AlwaysOff, 3 = AlwaysOn.
- OsLoaderNxPolicy = 0x25000020,
-
- ///
- /// PAE policy.
- ///
- /// 0 = default, 1 = ForceEnable, 2 = ForceDisable.
- OsLoaderPaePolicy = 0x25000021,
-
- ///
- /// WinPE mode.
- ///
- OsLoaderWinPeMode = 0x26000022,
-
- ///
- /// Disable automatic reboot on OS crash.
- ///
- OsLoaderDisableCrashAutoReboot = 0x26000024,
-
- ///
- /// Use the last known good settings.
- ///
- OsLoaderUseLastGoodSettings = 0x26000025,
-
- ///
- /// Disable integrity checks.
- ///
- OsLoaderDisableIntegrityChecks = 0x26000026,
-
- ///
- /// Allows pre-release signatures (test signing).
- ///
- OsLoaderAllowPrereleaseSignatures = 0x26000027,
-
- ///
- /// Loads all executables above 4GB boundary.
- ///
- OsLoaderNoLowMemory = 0x26000030,
-
- ///
- /// Excludes a given amount of memory from use by Windows.
- ///
- OsLoaderRemoveMemory = 0x25000031,
-
- ///
- /// Increases the User Mode virtual address space.
- ///
- OsLoaderIncreaseUserVa = 0x25000032,
-
- ///
- /// Size of buffer (in MB) for perfomance data logging.
- ///
- OsLoaderPerformanceDataMemory = 0x25000033,
-
- ///
- /// Uses the VGA display driver.
- ///
- OsLoaderUseVgaDriver = 0x26000040,
-
- ///
- /// Quiet boot.
- ///
- OsLoaderDisableBootDisplay = 0x26000041,
-
- ///
- /// Disables use of the VESA BIOS.
- ///
- OsLoaderDisableVesaBios = 0x26000042,
-
- ///
- /// Maximum processors in a single APIC cluster.
- ///
- OsLoaderClusterModeAddressing = 0x25000050,
-
- ///
- /// Forces the physical APIC to be used.
- ///
- OsLoaderUsePhysicalDestination = 0x26000051,
-
- ///
- /// The largest APIC cluster number the system can use.
- ///
- OsLoaderRestrictApicCluster = 0x25000052,
-
- ///
- /// Forces only the boot processor to be used.
- ///
- OsLoaderUseBootProcessorOnly = 0x26000060,
-
- ///
- /// The number of processors to be used.
- ///
- OsLoaderNumberOfProcessors = 0x25000061,
-
- ///
- /// Use maximum number of processors.
- ///
- OsLoaderForceMaxProcessors = 0x26000062,
-
- ///
- /// Processor specific configuration flags.
- ///
- OsLoaderProcessorConfigurationFlags = 0x25000063,
-
- ///
- /// Uses BIOS-configured PCI resources.
- ///
- OsLoaderUseFirmwarePciSettings = 0x26000070,
-
- ///
- /// Message Signalled Interrupt setting.
- ///
- OsLoaderMsiPolicy = 0x25000071,
-
- ///
- /// PCE Express Policy.
- ///
- OsLoaderPciExpressPolicy = 0x25000072,
-
- ///
- /// The safe boot option.
- ///
- /// 0 = Minimal, 1 = Network, 2 = DsRepair.
- OsLoaderSafeBoot = 0x25000080,
-
- ///
- /// Loads the configured alternate shell during a safe boot.
- ///
- OsLoaderSafeBootAlternateShell = 0x26000081,
-
- ///
- /// Enables boot log.
- ///
- OsLoaderBootLogInitialization = 0x26000090,
-
- ///
- /// Displays diagnostic information during boot.
- ///
- OsLoaderVerboseObjectLoadMode = 0x26000091,
-
- ///
- /// Enables the kernel debugger.
- ///
- OsLoaderKernelDebuggerEnabled = 0x260000A0,
-
- ///
- /// Causes the kernal to halt early during boot.
- ///
- OsLoaderDebuggerHalBreakpoint = 0x260000A1,
-
- ///
- /// Enables Windows Emergency Management System.
- ///
- OsLoaderEmsEnabled = 0x260000B0,
-
- ///
- /// Forces a failure on boot.
- ///
- OsLoaderForceFailure = 0x250000C0,
-
- ///
- /// The OS failure policy.
- ///
- OsLoaderDriverLoadFailurePolicy = 0x250000C1,
-
- ///
- /// The OS boot status policy.
- ///
- OsLoaderBootStatusPolicy = 0x250000E0,
-
- ///
- /// The device containing the hibernation file.
- ///
- ResumeHiberFileDevice = 0x21000001,
-
- ///
- /// The path to the hibernation file.
- ///
- ResumeHiberFilePath = 0x22000002,
-
- ///
- /// Allows resume loader to use custom settings.
- ///
- ResumeUseCustomSettings = 0x26000003,
-
- ///
- /// PAE settings for resume application.
- ///
- ResumePaeMode = 0x26000004,
-
- ///
- /// An MS-DOS device with containing resume application.
- ///
- ResumeAssociatedDosDevice = 0x21000005,
-
- ///
- /// Enables debug option.
- ///
- ResumeDebugOptionEnabled = 0x26000006,
-
- ///
- /// The number of iterations to run.
- ///
- MemDiagPassCount = 0x25000001,
-
- ///
- /// The test mix.
- ///
- MemDiagTestMix = 0x25000002,
-
- ///
- /// The failure count.
- ///
- MemDiagFailureCount = 0x25000003,
-
- ///
- /// The tests to fail.
- ///
- MemDiagTestToFail = 0x25000004,
-
- ///
- /// BPB string.
- ///
- LoaderBpbString = 0x22000001,
-
- ///
- /// Causes a soft PXE reboot.
- ///
- StartupPxeSoftReboot = 0x26000001,
-
- ///
- /// PXE application name.
- ///
- StartupPxeApplicationName = 0x22000002,
-
- ///
- /// Offset of the RAM disk image.
- ///
- DeviceRamDiskImageOffset = 0x35000001,
-
- ///
- /// Client port for TFTP.
- ///
- DeviceRamDiskTftpClientPort = 0x35000002,
-
- ///
- /// Device containing the SDI file.
- ///
- DeviceRamDiskSdiDevice = 0x31000003,
-
- ///
- /// Path to the SDI file.
- ///
- DeviceRamDiskSdiPath = 0x32000004,
-
- ///
- /// Length of the RAM disk image.
- ///
- DeviceRamDiskRamDiskImageLength = 0x35000005,
-
- ///
- /// Exports the image as a CD.
- ///
- DeviceRamDiskExportAsCd = 0x36000006,
-
- ///
- /// The TFTP transfer block size.
- ///
- DeviceRamDiskTftpBlockSize = 0x35000007,
-
- ///
- /// The device type.
- ///
- SetupDeviceType = 0x45000001,
-
- ///
- /// The application relative path.
- ///
- SetupAppRelativePath = 0x42000002,
-
- ///
- /// The device relative path.
- ///
- SetupRamDiskDeviceRelativePath = 0x42000003,
-
- ///
- /// Omit OS loader elements.
- ///
- SetupOmitOsLoaderElements = 0x46000004,
-
- ///
- /// Recovery OS flag.
- ///
- SetupRecoveryOs = 0x46000010,
- }
-}
diff --git a/DiscUtils/Buffer.cs b/DiscUtils/Buffer.cs
deleted file mode 100644
index 26e2cec..0000000
--- a/DiscUtils/Buffer.cs
+++ /dev/null
@@ -1,120 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- using System;
- using System.Collections.Generic;
-
- ///
- /// Abstract base class for implementations of IBuffer.
- ///
- public abstract class Buffer : MarshalByRefObject, IBuffer
- {
- ///
- /// Gets a value indicating whether this buffer can be read.
- ///
- public abstract bool CanRead { get; }
-
- ///
- /// Gets a value indicating whether this buffer can be modified.
- ///
- public abstract bool CanWrite { get; }
-
- ///
- /// Gets the current capacity of the buffer, in bytes.
- ///
- public abstract long Capacity { get; }
-
- ///
- /// Gets the parts of the stream that are stored.
- ///
- /// This may be an empty enumeration if all bytes are zero.
- public virtual IEnumerable Extents
- {
- get
- {
- return GetExtentsInRange(0, Capacity);
- }
- }
-
- ///
- /// Reads from the buffer into a byte array.
- ///
- /// The offset within the buffer to start reading.
- /// The destination byte array.
- /// The start offset within the destination buffer.
- /// The number of bytes to read.
- /// The actual number of bytes read.
- public abstract int Read(long pos, byte[] buffer, int offset, int count);
-
- ///
- /// Writes a byte array into the buffer.
- ///
- /// The start offset within the buffer.
- /// The source byte array.
- /// The start offset within the source byte array.
- /// The number of bytes to write.
- public abstract void Write(long pos, byte[] buffer, int offset, int count);
-
- ///
- /// Clears bytes from the buffer.
- ///
- /// The start offset within the buffer.
- /// The number of bytes to clear.
- ///
- /// Logically equivalent to writing count null/zero bytes to the buffer, some
- /// implementations determine that some (or all) of the range indicated is not actually
- /// stored. There is no direct, automatic, correspondence to clearing bytes and them
- /// not being represented as an 'extent' - for example, the implementation of the underlying
- /// stream may not permit fine-grained extent storage.
- /// It is always safe to call this method to 'zero-out' a section of a buffer, regardless of
- /// the underlying buffer implementation.
- ///
- public virtual void Clear(long pos, int count)
- {
- Write(pos, new byte[count], 0, count);
- }
-
- ///
- /// Flushes all data to the underlying storage.
- ///
- /// The default behaviour, implemented by this class, is to take no action.
- public virtual void Flush()
- {
- }
-
- ///
- /// Sets the capacity of the buffer, truncating if appropriate.
- ///
- /// The desired capacity of the buffer.
- public abstract void SetCapacity(long value);
-
- ///
- /// Gets the parts of a buffer that are stored, within a specified range.
- ///
- /// The offset of the first byte of interest.
- /// The number of bytes of interest.
- /// An enumeration of stream extents, indicating stored bytes.
- public abstract IEnumerable GetExtentsInRange(long start, long count);
- }
-}
diff --git a/DiscUtils/BufferStream.cs b/DiscUtils/BufferStream.cs
deleted file mode 100644
index 260e033..0000000
--- a/DiscUtils/BufferStream.cs
+++ /dev/null
@@ -1,218 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- using System.Collections.Generic;
- using System.IO;
-
- ///
- /// Converts a Buffer into a Stream.
- ///
- public class BufferStream : SparseStream
- {
- private IBuffer _buffer;
- private FileAccess _access;
-
- private long _position;
-
- ///
- /// Initializes a new instance of the BufferStream class.
- ///
- /// The buffer to use.
- /// The access permitted to clients.
- public BufferStream(IBuffer buffer, FileAccess access)
- {
- _buffer = buffer;
- _access = access;
- }
-
- ///
- /// Gets an indication of whether read access is permitted.
- ///
- public override bool CanRead
- {
- get { return _access != FileAccess.Write; }
- }
-
- ///
- /// Gets an indication of whether seeking is permitted.
- ///
- public override bool CanSeek
- {
- get { return true; }
- }
-
- ///
- /// Gets an indication of whether write access is permitted.
- ///
- public override bool CanWrite
- {
- get { return _access != FileAccess.Read; }
- }
-
- ///
- /// Gets the length of the stream (the capacity of the underlying buffer).
- ///
- public override long Length
- {
- get { return _buffer.Capacity; }
- }
-
- ///
- /// Gets and sets the current position within the stream.
- ///
- public override long Position
- {
- get { return _position; }
- set { _position = value; }
- }
-
- ///
- /// Gets the stored extents within the sparse stream.
- ///
- public override IEnumerable Extents
- {
- get { return _buffer.Extents; }
- }
-
- ///
- /// Flushes all data to the underlying storage.
- ///
- public override void Flush()
- {
- }
-
- ///
- /// Reads a number of bytes from the stream.
- ///
- /// The destination buffer.
- /// The start offset within the destination buffer.
- /// The number of bytes to read.
- /// The number of bytes read.
- public override int Read(byte[] buffer, int offset, int count)
- {
- if (!CanRead)
- {
- throw new IOException("Attempt to read from write-only stream");
- }
-
- Utilities.AssertBufferParameters(buffer, offset, count);
-
- int numRead = _buffer.Read(_position, buffer, offset, count);
- _position += numRead;
- return numRead;
- }
-
- ///
- /// Changes the current stream position.
- ///
- /// The origin-relative stream position.
- /// The origin for the stream position.
- /// The new stream position.
- public override long Seek(long offset, SeekOrigin origin)
- {
- long effectiveOffset = offset;
- if (origin == SeekOrigin.Current)
- {
- effectiveOffset += _position;
- }
- else if (origin == SeekOrigin.End)
- {
- effectiveOffset += _buffer.Capacity;
- }
-
- if (effectiveOffset < 0)
- {
- throw new IOException("Attempt to move before beginning of disk");
- }
- else
- {
- _position = effectiveOffset;
- return _position;
- }
- }
-
- ///
- /// Sets the length of the stream (the underlying buffer's capacity).
- ///
- /// The new length of the stream.
- public override void SetLength(long value)
- {
- _buffer.SetCapacity(value);
- }
-
- ///
- /// Writes a buffer to the stream.
- ///
- /// The buffer to write.
- /// The starting offset within buffer.
- /// The number of bytes to write.
- public override void Write(byte[] buffer, int offset, int count)
- {
- if (!CanWrite)
- {
- throw new IOException("Attempt to write to read-only stream");
- }
-
- Utilities.AssertBufferParameters(buffer, offset, count);
-
- _buffer.Write(_position, buffer, offset, count);
- _position += count;
- }
-
- ///
- /// Clears bytes from the stream.
- ///
- /// The number of bytes (from the current position) to clear.
- ///
- /// Logically equivalent to writing count null/zero bytes to the stream, some
- /// implementations determine that some (or all) of the range indicated is not actually
- /// stored. There is no direct, automatic, correspondence to clearing bytes and them
- /// not being represented as an 'extent' - for example, the implementation of the underlying
- /// stream may not permit fine-grained extent storage.
- /// It is always safe to call this method to 'zero-out' a section of a stream, regardless of
- /// the underlying stream implementation.
- ///
- public override void Clear(int count)
- {
- if (!CanWrite)
- {
- throw new IOException("Attempt to erase bytes in a read-only stream");
- }
-
- _buffer.Clear(_position, count);
- _position += count;
- }
-
- ///
- /// Gets the parts of a stream that are stored, within a specified range.
- ///
- /// The offset of the first byte of interest.
- /// The number of bytes of interest.
- /// An enumeration of stream extents, indicating stored bytes.
- public override IEnumerable GetExtentsInRange(long start, long count)
- {
- return _buffer.GetExtentsInRange(start, count);
- }
- }
-}
diff --git a/DiscUtils/BuilderBufferExtent.cs b/DiscUtils/BuilderBufferExtent.cs
deleted file mode 100644
index 0d43f62..0000000
--- a/DiscUtils/BuilderBufferExtent.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- using System;
-
- internal class BuilderBufferExtent : BuilderExtent
- {
- private bool _fixedBuffer;
- private byte[] _buffer;
-
- public BuilderBufferExtent(long start, long length)
- : base(start, length)
- {
- }
-
- public BuilderBufferExtent(long start, byte[] buffer)
- : base(start, buffer.Length)
- {
- _fixedBuffer = true;
- _buffer = buffer;
- }
-
- public override void Dispose()
- {
- }
-
- internal override void PrepareForRead()
- {
- if (!_fixedBuffer)
- {
- _buffer = GetBuffer();
- }
- }
-
- internal override int Read(long diskOffset, byte[] block, int offset, int count)
- {
- int startOffset = (int)(diskOffset - Start);
- int numBytes = (int)Math.Min(Length - startOffset, count);
- Array.Copy(_buffer, startOffset, block, offset, numBytes);
- return numBytes;
- }
-
- internal override void DisposeReadState()
- {
- if (!_fixedBuffer)
- {
- _buffer = null;
- }
- }
-
- protected virtual byte[] GetBuffer()
- {
- throw new NotSupportedException("Derived class should implement");
- }
- }
-}
diff --git a/DiscUtils/BuilderExtent.cs b/DiscUtils/BuilderExtent.cs
deleted file mode 100644
index a6e6a44..0000000
--- a/DiscUtils/BuilderExtent.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- using System;
- using System.Collections.Generic;
-
- internal abstract class BuilderExtent : IDisposable
- {
- private long _start;
- private long _length;
-
- public BuilderExtent(long start, long length)
- {
- _start = start;
- _length = length;
- }
-
- ///
- /// Gets the parts of the stream that are stored.
- ///
- /// This may be an empty enumeration if all bytes are zero.
- public virtual IEnumerable StreamExtents
- {
- get
- {
- return new StreamExtent[] { new StreamExtent(Start, Length) };
- }
- }
-
- internal long Start
- {
- get { return _start; }
- }
-
- internal long Length
- {
- get { return _length; }
- }
-
- public abstract void Dispose();
-
- internal abstract void PrepareForRead();
-
- internal abstract int Read(long diskOffset, byte[] block, int offset, int count);
-
- internal abstract void DisposeReadState();
- }
-}
diff --git a/DiscUtils/BuilderSparseStreamExtent.cs b/DiscUtils/BuilderSparseStreamExtent.cs
deleted file mode 100644
index 416bf3d..0000000
--- a/DiscUtils/BuilderSparseStreamExtent.cs
+++ /dev/null
@@ -1,72 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- using System.Collections.Generic;
-
- internal class BuilderSparseStreamExtent : BuilderExtent
- {
- private SparseStream _stream;
- private Ownership _ownership;
-
- public BuilderSparseStreamExtent(long start, SparseStream stream)
- : this(start, stream, Ownership.None)
- {
- }
-
- public BuilderSparseStreamExtent(long start, SparseStream stream, Ownership ownership)
- : base(start, stream.Length)
- {
- _stream = stream;
- _ownership = ownership;
- }
-
- public override IEnumerable StreamExtents
- {
- get { return StreamExtent.Offset(_stream.Extents, Start); }
- }
-
- public override void Dispose()
- {
- if (_stream != null && _ownership == Ownership.Dispose)
- {
- _stream.Dispose();
- _stream = null;
- }
- }
-
- internal override void PrepareForRead()
- {
- }
-
- internal override int Read(long diskOffset, byte[] block, int offset, int count)
- {
- _stream.Position = diskOffset - Start;
- return _stream.Read(block, offset, count);
- }
-
- internal override void DisposeReadState()
- {
- }
- }
-}
diff --git a/DiscUtils/BuiltStream.cs b/DiscUtils/BuiltStream.cs
deleted file mode 100644
index 33eef09..0000000
--- a/DiscUtils/BuiltStream.cs
+++ /dev/null
@@ -1,327 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- using System;
- using System.Collections.Generic;
- using System.IO;
-
- internal class BuiltStream : SparseStream
- {
- private Stream _baseStream;
- private long _length;
- private List _extents;
-
- private BuilderExtent _currentExtent;
- private long _position;
-
- public BuiltStream(long length, List extents)
- {
- _baseStream = new ZeroStream(length);
- _length = length;
- _extents = extents;
-
- // Make sure the extents are sorted, so binary searches will work.
- _extents.Sort(new ExtentStartComparer());
- }
-
- public override bool CanRead
- {
- get { return true; }
- }
-
- public override bool CanSeek
- {
- get { return true; }
- }
-
- public override bool CanWrite
- {
- get { return false; }
- }
-
- public override long Length
- {
- get { return _length; }
- }
-
- public override long Position
- {
- get { return _position; }
- set { _position = value; }
- }
-
- public override IEnumerable Extents
- {
- get
- {
- foreach (var extent in _extents)
- {
- foreach (var streamExtent in extent.StreamExtents)
- {
- yield return streamExtent;
- }
- }
- }
- }
-
- public override void Flush()
- {
- return;
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- if (_position >= _length)
- {
- return 0;
- }
-
- int totalRead = 0;
- while (totalRead < count && _position < _length)
- {
- // If current region is outside the area of interest, clean it up
- if (_currentExtent != null && (_position < _currentExtent.Start || _position >= _currentExtent.Start + _currentExtent.Length))
- {
- _currentExtent.DisposeReadState();
- _currentExtent = null;
- }
-
- // If we need to find a new region, look for it
- if (_currentExtent == null)
- {
- using (SearchExtent searchExtent = new SearchExtent(_position))
- {
- int idx = _extents.BinarySearch(searchExtent, new ExtentRangeComparer());
- if (idx >= 0)
- {
- BuilderExtent extent = _extents[idx];
- extent.PrepareForRead();
- _currentExtent = extent;
- }
- }
- }
-
- int numRead = 0;
-
- // If the block is outside any known extent, defer to base stream.
- if (_currentExtent == null)
- {
- _baseStream.Position = _position;
- BuilderExtent nextExtent = FindNext(_position);
- if (nextExtent != null)
- {
- numRead = _baseStream.Read(buffer, offset + totalRead, (int)Math.Min(count - totalRead, nextExtent.Start - _position));
- }
- else
- {
- numRead = _baseStream.Read(buffer, offset + totalRead, count - totalRead);
- }
- }
- else
- {
- numRead = _currentExtent.Read(_position, buffer, offset + totalRead, count - totalRead);
- }
-
- _position += numRead;
- totalRead += numRead;
- }
-
- return totalRead;
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- long newPos = offset;
- if (origin == SeekOrigin.Current)
- {
- newPos += _position;
- }
- else if (origin == SeekOrigin.End)
- {
- newPos += _length;
- }
-
- _position = newPos;
- return newPos;
- }
-
- public override void SetLength(long value)
- {
- throw new NotSupportedException();
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- throw new NotSupportedException();
- }
-
- protected override void Dispose(bool disposing)
- {
- try
- {
- if (disposing)
- {
- if (_currentExtent != null)
- {
- _currentExtent.DisposeReadState();
- _currentExtent = null;
- }
-
- if (_baseStream != null)
- {
- _baseStream.Dispose();
- _baseStream = null;
- }
- }
- }
- finally
- {
- base.Dispose(disposing);
- }
- }
-
- private BuilderExtent FindNext(long pos)
- {
- int min = 0;
- int max = _extents.Count - 1;
-
- if (_extents.Count == 0 || (_extents[_extents.Count - 1].Start + _extents[_extents.Count - 1].Length) <= pos)
- {
- return null;
- }
-
- while (true)
- {
- if (min >= max)
- {
- return _extents[min];
- }
-
- int mid = (max + min) / 2;
- if (_extents[mid].Start < pos)
- {
- min = mid + 1;
- }
- else if (_extents[mid].Start > pos)
- {
- max = mid;
- }
- else
- {
- return _extents[mid];
- }
- }
- }
-
- private class SearchExtent : BuilderExtent
- {
- public SearchExtent(long pos)
- : base(pos, 1)
- {
- }
-
- public override void Dispose()
- {
- }
-
- internal override void PrepareForRead()
- {
- // Not valid to use this 'dummy' extent for actual construction
- throw new NotSupportedException();
- }
-
- internal override int Read(long diskOffset, byte[] block, int offset, int count)
- {
- // Not valid to use this 'dummy' extent for actual construction
- throw new NotSupportedException();
- }
-
- internal override void DisposeReadState()
- {
- // Not valid to use this 'dummy' extent for actual construction
- throw new NotSupportedException();
- }
- }
-
- private class ExtentRangeComparer : IComparer
- {
- public int Compare(BuilderExtent x, BuilderExtent y)
- {
- if (x == null)
- {
- throw new ArgumentNullException("x");
- }
-
- if (y == null)
- {
- throw new ArgumentNullException("y");
- }
-
- if (x.Start + x.Length <= y.Start)
- {
- // x < y, with no intersection
- return -1;
- }
- else if (x.Start >= y.Start + y.Length)
- {
- // x > y, with no intersection
- return 1;
- }
-
- // x intersects y
- return 0;
- }
- }
-
- private class ExtentStartComparer : IComparer
- {
- public int Compare(BuilderExtent x, BuilderExtent y)
- {
- if (x == null)
- {
- throw new ArgumentNullException("x");
- }
-
- if (y == null)
- {
- throw new ArgumentNullException("y");
- }
-
- long val = x.Start - y.Start;
- if (val < 0)
- {
- return -1;
- }
- else if (val > 0)
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
- }
- }
-}
diff --git a/DiscUtils/ChsAddress.cs b/DiscUtils/ChsAddress.cs
deleted file mode 100644
index 126fa4f..0000000
--- a/DiscUtils/ChsAddress.cs
+++ /dev/null
@@ -1,112 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- ///
- /// Class whose instances represent a CHS (Cylinder, Head, Sector) address on a disk.
- ///
- /// Instances of this class are immutable.
- public sealed class ChsAddress
- {
- ///
- /// The address of the first sector on any disk.
- ///
- public static readonly ChsAddress First = new ChsAddress(0, 0, 1);
-
- private int _cylinder;
- private int _head;
- private int _sector;
-
- ///
- /// Initializes a new instance of the ChsAddress class.
- ///
- /// The number of cylinders of the disk.
- /// The number of heads (aka platters) of the disk.
- /// The number of sectors per track/cylinder of the disk.
- public ChsAddress(int cylinder, int head, int sector)
- {
- _cylinder = cylinder;
- _head = head;
- _sector = sector;
- }
-
- ///
- /// Gets the cylinder number (zero-based).
- ///
- public int Cylinder
- {
- get { return _cylinder; }
- }
-
- ///
- /// Gets the head (zero-based).
- ///
- public int Head
- {
- get { return _head; }
- }
-
- ///
- /// Gets the sector number (one-based).
- ///
- public int Sector
- {
- get { return _sector; }
- }
-
- ///
- /// Determines if this object is equivalent to another.
- ///
- /// The object to test against.
- /// true if the is equivalent, else false.
- public override bool Equals(object obj)
- {
- if (obj == null || obj.GetType() != GetType())
- {
- return false;
- }
-
- ChsAddress other = (ChsAddress)obj;
-
- return _cylinder == other._cylinder && _head == other._head && _sector == other._sector;
- }
-
- ///
- /// Calculates the hash code for this object.
- ///
- /// The hash code.
- public override int GetHashCode()
- {
- return _cylinder.GetHashCode() ^ _head.GetHashCode() ^ _sector.GetHashCode();
- }
-
- ///
- /// Gets a string representation of this object, in the form (C/H/S).
- ///
- /// The string representation.
- public override string ToString()
- {
- return "(" + _cylinder + "/" + _head + "/" + _sector + ")";
- }
- }
-}
diff --git a/DiscUtils/ClusterMap.cs b/DiscUtils/ClusterMap.cs
deleted file mode 100644
index 845e9a1..0000000
--- a/DiscUtils/ClusterMap.cs
+++ /dev/null
@@ -1,127 +0,0 @@
-//
-// Copyright (c) 2008-2011, Kenneth Bell
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the "Software"),
-// to deal in the Software without restriction, including without limitation
-// the rights to use, copy, modify, merge, publish, distribute, sublicense,
-// and/or sell copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-// DEALINGS IN THE SOFTWARE.
-//
-
-namespace DiscUtils
-{
- using System;
- using System.Collections.Generic;
-
- ///
- /// Enumeration of possible cluster roles.
- ///
- /// A cluster may be in more than one role.
- [Flags]
- public enum ClusterRoles
- {
- ///
- /// Unknown, or unspecified role.
- ///
- None = 0x00,
-
- ///
- /// Cluster is free.
- ///
- Free = 0x01,
-
- ///
- /// Cluster is in use by a normal file.
- ///
- DataFile = 0x02,
-
- ///
- /// Cluster is in use by a system file.
- ///
- /// This isn't a file marked with the 'system' attribute,
- /// rather files that form part of the file system namespace but also
- /// form part of the file system meta-data.
- SystemFile = 0x04,
-
- ///
- /// Cluster is in use for meta-data.
- ///
- Metadata = 0x08,
-
- ///
- /// Cluster contains the boot region.
- ///
- BootArea = 0x10,
-
- ///
- /// Cluster is marked bad.
- ///
- Bad = 0x20,
- }
-
- ///
- /// Class that identifies the role of each cluster in a file system.
- ///
- public sealed class ClusterMap
- {
- private ClusterRoles[] _clusterToRole;
- private object[] _clusterToFileId;
- private Dictionary