Skip to content

[BUG] Blob FromStream is not GC safe #3472

@jeremy-visionaid

Description

@jeremy-visionaid

Description

If GC runs after the blob is created, the managed array memory might be moved resulting in a crash,

Code

By inspection:

	public static unsafe Blob FromStream (Stream stream)
	{
		// TODO: check to see if we can avoid the second copy (the ToArray)


		using var ms = new MemoryStream ();
		stream.CopyTo (ms);
		var data = ms.ToArray ();


		fixed (byte* dataPtr = data) {
			return new Blob ((IntPtr)dataPtr, data.Length, MemoryMode.ReadOnly, () => ms.Dispose ());
		}
	}

Expected Behavior

Should copy via an UnmanagedMemoryStream:

		public static unsafe Blob FromStream (Stream stream)
		{
			var length = (int)(stream.Length - stream.Position);

			var dataPtr = Marshal.AllocCoTaskMem (length);

			using var ums = new UnmanagedMemoryStream ((byte*)dataPtr, length, length, FileAccess.ReadWrite);
			stream.CopyTo (ums);

			return new Blob (dataPtr, length, MemoryMode.ReadOnly, () => Marshal.FreeCoTaskMem (dataPtr));
		}

Actual Behavior

No response

Version of SkiaSharp

3.116.0 (Current)

Last Known Good Version of SkiaSharp

2.88.9 (Previous)

IDE / Editor

Visual Studio (Windows)

Platform / Operating System

All

Platform / Operating System Version

No response

Devices

No response

Relevant Screenshots

No response

Relevant Log Output

Code of Conduct

  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/SkiaSharpIssues that relate to the C# binding of SkiaSharp.os/Windows-ClassicIssues running on Microsoft Windows using Win32 APIs (Windows.Forms or WPF)tenet/reliabilityIssues relating to crashes or unexpected behaviorstype/bug

    Type

    No type

    Projects

    Status

    New

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions