| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Runtime.InteropServices; |
| | | 7 | | |
| | | 8 | | namespace System.IO.Compression |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Provides a wrapper around the ZLib decompression API. |
| | | 12 | | /// </summary> |
| | | 13 | | internal sealed class Inflater : IDisposable |
| | | 14 | | { |
| | | 15 | | private const int MinWindowBits = -15; // WindowBits must be between -8..-15 to ignore the |
| | | 16 | | private const int MaxWindowBits = 47; // zlib headers, 24..31 for GZip headers, or 40..47 |
| | | 17 | | |
| | | 18 | | private bool _nonEmptyInput; // Whether there is any non empty input |
| | | 19 | | private bool _finished; // Whether the end of the stream has been reached |
| | | 20 | | private bool _isDisposed; // Prevents multiple disposals |
| | | 21 | | private readonly int _windowBits; // The WindowBits parameter passed to Inflater const |
| | | 22 | | private readonly ZLibNative.ZLibStreamHandle _zlibStream; // The handle to the primary underlying zlib stream |
| | | 23 | | private MemoryHandle _inputBufferHandle; // The handle to the buffer that provides input to _ |
| | | 24 | | private readonly long _uncompressedSize; |
| | | 25 | | private long _currentInflatedCount; |
| | | 26 | | |
| | 0 | 27 | | private object SyncLock => this; // Used to make writing to unmanaged structures atomic |
| | | 28 | | |
| | 0 | 29 | | private Inflater(int windowBits, long uncompressedSize, ZLibNative.ZLibStreamHandle zlibStream) |
| | 0 | 30 | | { |
| | 0 | 31 | | _finished = false; |
| | 0 | 32 | | _nonEmptyInput = false; |
| | 0 | 33 | | _isDisposed = false; |
| | 0 | 34 | | _windowBits = windowBits; |
| | 0 | 35 | | _uncompressedSize = uncompressedSize; |
| | 0 | 36 | | _zlibStream = zlibStream; |
| | 0 | 37 | | } |
| | | 38 | | |
| | | 39 | | public int AvailableOutput => (int)_zlibStream.AvailOut; |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Returns true if the end of the stream has been reached. |
| | | 43 | | /// </summary> |
| | 0 | 44 | | public bool Finished() => _finished; |
| | | 45 | | |
| | | 46 | | public unsafe bool Inflate(out byte b) |
| | 0 | 47 | | { |
| | 0 | 48 | | fixed (byte* bufPtr = &b) |
| | 0 | 49 | | { |
| | 0 | 50 | | int bytesRead = InflateVerified(bufPtr, 1); |
| | 0 | 51 | | Debug.Assert(bytesRead == 0 || bytesRead == 1); |
| | 0 | 52 | | return bytesRead != 0; |
| | | 53 | | } |
| | 0 | 54 | | } |
| | | 55 | | |
| | | 56 | | public unsafe int Inflate(byte[] bytes, int offset, int length) |
| | 0 | 57 | | { |
| | | 58 | | // If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read. |
| | 0 | 59 | | if (length == 0) |
| | 0 | 60 | | return 0; |
| | | 61 | | |
| | 0 | 62 | | Debug.Assert(null != bytes, "Can't pass in a null output buffer!"); |
| | 0 | 63 | | fixed (byte* bufPtr = bytes) |
| | 0 | 64 | | { |
| | 0 | 65 | | return InflateVerified(bufPtr + offset, length); |
| | | 66 | | } |
| | 0 | 67 | | } |
| | | 68 | | |
| | | 69 | | public unsafe int Inflate(Span<byte> destination) |
| | 0 | 70 | | { |
| | | 71 | | // If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read. |
| | 0 | 72 | | if (destination.Length == 0) |
| | 0 | 73 | | return 0; |
| | | 74 | | |
| | 0 | 75 | | fixed (byte* bufPtr = &MemoryMarshal.GetReference(destination)) |
| | 0 | 76 | | { |
| | 0 | 77 | | return InflateVerified(bufPtr, destination.Length); |
| | | 78 | | } |
| | 0 | 79 | | } |
| | | 80 | | |
| | | 81 | | public unsafe int InflateVerified(byte* bufPtr, int length) |
| | 0 | 82 | | { |
| | | 83 | | // State is valid; attempt inflation |
| | | 84 | | try |
| | 0 | 85 | | { |
| | 0 | 86 | | int bytesRead = 0; |
| | 0 | 87 | | if (_uncompressedSize == -1) |
| | 0 | 88 | | { |
| | 0 | 89 | | ReadOutput(bufPtr, length, out bytesRead); |
| | 0 | 90 | | } |
| | | 91 | | else |
| | 0 | 92 | | { |
| | 0 | 93 | | if (_uncompressedSize > _currentInflatedCount) |
| | 0 | 94 | | { |
| | 0 | 95 | | length = (int)Math.Min(length, _uncompressedSize - _currentInflatedCount); |
| | 0 | 96 | | ReadOutput(bufPtr, length, out bytesRead); |
| | 0 | 97 | | _currentInflatedCount += bytesRead; |
| | 0 | 98 | | } |
| | | 99 | | else |
| | 0 | 100 | | { |
| | 0 | 101 | | _finished = true; |
| | 0 | 102 | | _zlibStream.AvailIn = 0; |
| | 0 | 103 | | } |
| | 0 | 104 | | } |
| | 0 | 105 | | return bytesRead; |
| | | 106 | | } |
| | | 107 | | finally |
| | 0 | 108 | | { |
| | | 109 | | // Before returning, make sure to release input buffer if necessary: |
| | 0 | 110 | | if (0 == _zlibStream.AvailIn && IsInputBufferHandleAllocated) |
| | 0 | 111 | | { |
| | 0 | 112 | | DeallocateInputBufferHandle(resetStreamHandle: true); |
| | 0 | 113 | | } |
| | 0 | 114 | | } |
| | 0 | 115 | | } |
| | | 116 | | |
| | | 117 | | private unsafe void ReadOutput(byte* bufPtr, int length, out int bytesRead) |
| | 0 | 118 | | { |
| | 0 | 119 | | if (ReadInflateOutput(bufPtr, length, ZLibNative.FlushCode.NoFlush, out bytesRead) == ZLibNative.ErrorCode.S |
| | 0 | 120 | | { |
| | 0 | 121 | | if (!NeedsInput() && IsGzipStream() && IsInputBufferHandleAllocated) |
| | 0 | 122 | | { |
| | 0 | 123 | | _finished = ResetStreamForLeftoverInput(); |
| | 0 | 124 | | } |
| | | 125 | | else |
| | 0 | 126 | | { |
| | 0 | 127 | | _finished = true; |
| | 0 | 128 | | } |
| | 0 | 129 | | } |
| | 0 | 130 | | } |
| | | 131 | | |
| | | 132 | | /// <summary> |
| | | 133 | | /// If this stream has some input leftover that hasn't been processed then we should |
| | | 134 | | /// check if it is another GZip file concatenated with this one. |
| | | 135 | | /// |
| | | 136 | | /// Returns false if the leftover input is another GZip data stream. |
| | | 137 | | /// </summary> |
| | | 138 | | private unsafe bool ResetStreamForLeftoverInput() |
| | 0 | 139 | | { |
| | 0 | 140 | | Debug.Assert(!NeedsInput()); |
| | 0 | 141 | | Debug.Assert(IsGzipStream()); |
| | 0 | 142 | | Debug.Assert(IsInputBufferHandleAllocated); |
| | | 143 | | |
| | 0 | 144 | | lock (SyncLock) |
| | 0 | 145 | | { |
| | 0 | 146 | | byte* nextInPointer = (byte*)_zlibStream.NextIn; |
| | 0 | 147 | | uint nextAvailIn = _zlibStream.AvailIn; |
| | | 148 | | |
| | | 149 | | // Check the leftover bytes to see if they start with the gzip header ID bytes |
| | 0 | 150 | | if (*nextInPointer != ZLibNative.GZip_Header_ID1 || (nextAvailIn > 1 && *(nextInPointer + 1) != ZLibNati |
| | 0 | 151 | | { |
| | 0 | 152 | | return true; |
| | | 153 | | } |
| | | 154 | | |
| | | 155 | | // Reset our existing zstream. |
| | 0 | 156 | | _zlibStream.InflateReset2_(_windowBits); |
| | | 157 | | |
| | 0 | 158 | | _finished = false; |
| | 0 | 159 | | } |
| | | 160 | | |
| | 0 | 161 | | return false; |
| | 0 | 162 | | } |
| | | 163 | | |
| | 0 | 164 | | internal bool IsGzipStream() => _windowBits >= 24 && _windowBits <= 31; |
| | | 165 | | |
| | 0 | 166 | | public bool NeedsInput() => _zlibStream.AvailIn == 0; |
| | | 167 | | |
| | 0 | 168 | | public bool NonEmptyInput() => _nonEmptyInput; |
| | | 169 | | |
| | 0 | 170 | | internal int GetAvailableInput() => (int)_zlibStream.AvailIn; |
| | | 171 | | |
| | | 172 | | public void SetInput(byte[] inputBuffer, int startIndex, int count) |
| | 0 | 173 | | { |
| | 0 | 174 | | Debug.Assert(NeedsInput(), "We have something left in previous input!"); |
| | 0 | 175 | | Debug.Assert(inputBuffer != null); |
| | 0 | 176 | | Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length); |
| | 0 | 177 | | Debug.Assert(!IsInputBufferHandleAllocated); |
| | | 178 | | |
| | 0 | 179 | | SetInput(inputBuffer.AsMemory(startIndex, count)); |
| | 0 | 180 | | } |
| | | 181 | | |
| | | 182 | | public unsafe void SetInput(ReadOnlyMemory<byte> inputBuffer) |
| | 0 | 183 | | { |
| | 0 | 184 | | Debug.Assert(NeedsInput(), "We have something left in previous input!"); |
| | 0 | 185 | | Debug.Assert(!IsInputBufferHandleAllocated); |
| | | 186 | | |
| | 0 | 187 | | if (inputBuffer.IsEmpty) |
| | 0 | 188 | | return; |
| | | 189 | | |
| | 0 | 190 | | lock (SyncLock) |
| | 0 | 191 | | { |
| | 0 | 192 | | _inputBufferHandle = inputBuffer.Pin(); |
| | 0 | 193 | | _zlibStream.NextIn = (IntPtr)_inputBufferHandle.Pointer; |
| | 0 | 194 | | _zlibStream.AvailIn = (uint)inputBuffer.Length; |
| | 0 | 195 | | _finished = false; |
| | 0 | 196 | | _nonEmptyInput = true; |
| | 0 | 197 | | } |
| | 0 | 198 | | } |
| | | 199 | | |
| | | 200 | | private void Dispose(bool disposing) |
| | 0 | 201 | | { |
| | 0 | 202 | | if (!_isDisposed) |
| | 0 | 203 | | { |
| | 0 | 204 | | if (disposing) |
| | 0 | 205 | | { |
| | 0 | 206 | | _zlibStream.Dispose(); |
| | 0 | 207 | | } |
| | | 208 | | |
| | 0 | 209 | | if (IsInputBufferHandleAllocated) |
| | 0 | 210 | | { |
| | | 211 | | // Unpin the input buffer, but avoid modifying the ZLibStreamHandle (which may have been disposed of |
| | 0 | 212 | | DeallocateInputBufferHandle(resetStreamHandle: false); |
| | 0 | 213 | | } |
| | | 214 | | |
| | 0 | 215 | | _isDisposed = true; |
| | 0 | 216 | | } |
| | 0 | 217 | | } |
| | | 218 | | |
| | | 219 | | public void Dispose() |
| | 0 | 220 | | { |
| | 0 | 221 | | Dispose(true); |
| | 0 | 222 | | GC.SuppressFinalize(this); |
| | 0 | 223 | | } |
| | | 224 | | |
| | | 225 | | ~Inflater() |
| | 0 | 226 | | { |
| | 0 | 227 | | Dispose(false); |
| | 0 | 228 | | } |
| | | 229 | | |
| | | 230 | | /// <summary> |
| | | 231 | | /// Wrapper around the ZLib inflate function, configuring the stream appropriately. |
| | | 232 | | /// </summary> |
| | | 233 | | private unsafe ZLibNative.ErrorCode ReadInflateOutput(byte* bufPtr, int length, ZLibNative.FlushCode flushCode, |
| | 0 | 234 | | { |
| | 0 | 235 | | lock (SyncLock) |
| | 0 | 236 | | { |
| | 0 | 237 | | _zlibStream.NextOut = (IntPtr)bufPtr; |
| | 0 | 238 | | _zlibStream.AvailOut = (uint)length; |
| | | 239 | | |
| | 0 | 240 | | ZLibNative.ErrorCode errC = Inflate(flushCode); |
| | 0 | 241 | | bytesRead = length - (int)_zlibStream.AvailOut; |
| | | 242 | | |
| | 0 | 243 | | return errC; |
| | | 244 | | } |
| | 0 | 245 | | } |
| | | 246 | | |
| | | 247 | | /// <summary> |
| | | 248 | | /// Wrapper around the ZLib inflate function |
| | | 249 | | /// </summary> |
| | | 250 | | private ZLibNative.ErrorCode Inflate(ZLibNative.FlushCode flushCode) |
| | 0 | 251 | | { |
| | | 252 | | ZLibNative.ErrorCode errC; |
| | | 253 | | try |
| | 0 | 254 | | { |
| | 0 | 255 | | errC = _zlibStream.Inflate(flushCode); |
| | 0 | 256 | | } |
| | 0 | 257 | | catch (Exception cause) // could not load the Zlib DLL correctly |
| | 0 | 258 | | { |
| | 0 | 259 | | throw new ZLibException(SR.ZLibErrorDLLLoadError, cause); |
| | | 260 | | } |
| | 0 | 261 | | switch (errC) |
| | | 262 | | { |
| | | 263 | | case ZLibNative.ErrorCode.Ok: // progress has been made inflating |
| | | 264 | | case ZLibNative.ErrorCode.StreamEnd: // The end of the input stream has been reached |
| | 0 | 265 | | return errC; |
| | | 266 | | |
| | | 267 | | case ZLibNative.ErrorCode.BufError: // No room in the output buffer - inflate() can be called again |
| | 0 | 268 | | return errC; |
| | | 269 | | |
| | | 270 | | case ZLibNative.ErrorCode.MemError: // Not enough memory to complete the operation |
| | 0 | 271 | | throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "inflate_", (int)errC, _zlibStream.GetErrorMess |
| | | 272 | | |
| | | 273 | | case ZLibNative.ErrorCode.DataError: // The input data was corrupted (input stream not conforming to |
| | 0 | 274 | | throw new InvalidDataException(SR.UnsupportedCompression); |
| | | 275 | | |
| | | 276 | | case ZLibNative.ErrorCode.StreamError: //the stream structure was inconsistent (for example if next_in |
| | 0 | 277 | | throw new ZLibException(SR.ZLibErrorInconsistentStream, "inflate_", (int)errC, _zlibStream.GetErrorM |
| | | 278 | | |
| | | 279 | | default: |
| | 0 | 280 | | throw new ZLibException(SR.ZLibErrorUnexpected, "inflate_", (int)errC, _zlibStream.GetErrorMessage() |
| | | 281 | | } |
| | 0 | 282 | | } |
| | | 283 | | |
| | | 284 | | /// <summary> |
| | | 285 | | /// Frees the GCHandle being used to store the input buffer |
| | | 286 | | /// </summary> |
| | | 287 | | private void DeallocateInputBufferHandle(bool resetStreamHandle) |
| | 0 | 288 | | { |
| | 0 | 289 | | Debug.Assert(IsInputBufferHandleAllocated); |
| | | 290 | | |
| | 0 | 291 | | lock (SyncLock) |
| | 0 | 292 | | { |
| | 0 | 293 | | if (resetStreamHandle) |
| | 0 | 294 | | { |
| | 0 | 295 | | _zlibStream.AvailIn = 0; |
| | 0 | 296 | | _zlibStream.NextIn = ZLibNative.ZNullPtr; |
| | 0 | 297 | | } |
| | | 298 | | |
| | 0 | 299 | | _inputBufferHandle.Dispose(); |
| | 0 | 300 | | } |
| | 0 | 301 | | } |
| | | 302 | | |
| | | 303 | | public static Inflater CreateInflater(int windowBits, long uncompressedSize = -1) |
| | 0 | 304 | | { |
| | 0 | 305 | | Debug.Assert(windowBits >= MinWindowBits && windowBits <= MaxWindowBits); |
| | | 306 | | |
| | 0 | 307 | | ZLibNative.ZLibStreamHandle zlibStream = ZLibNative.ZLibStreamHandle.CreateForInflate(windowBits); |
| | | 308 | | |
| | 0 | 309 | | return new Inflater(windowBits, uncompressedSize, zlibStream); |
| | 0 | 310 | | } |
| | | 311 | | |
| | 0 | 312 | | private unsafe bool IsInputBufferHandleAllocated => _inputBufferHandle.Pointer != default; |
| | | 313 | | } |
| | | 314 | | } |