Skip to content

Commit

Permalink
Bounds-check Texture2D uploads (#393)
Browse files Browse the repository at this point in the history
Not all FNA3D backends can respond correctly if asked to upload more pixels than you give them.

Co-authored-by: Ethan Lee <flibitijibibo@gmail.com>
  • Loading branch information
kg and flibitijibibo committed Aug 1, 2022
1 parent 4a2b687 commit 31ff5cd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/Graphics/Texture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,42 @@ internal protected override void GraphicsDeviceResetting()

#region Static SurfaceFormat Size Methods

protected static int GetBlockSizeSquared(SurfaceFormat format)
{
switch (format)
{
case SurfaceFormat.Dxt1:
case SurfaceFormat.Dxt3:
case SurfaceFormat.Dxt5:
case SurfaceFormat.Dxt5SrgbEXT:
case SurfaceFormat.Bc7EXT:
case SurfaceFormat.Bc7SrgbEXT:
return 16;
case SurfaceFormat.Alpha8:
case SurfaceFormat.Bgr565:
case SurfaceFormat.Bgra4444:
case SurfaceFormat.Bgra5551:
case SurfaceFormat.HalfSingle:
case SurfaceFormat.NormalizedByte2:
case SurfaceFormat.Color:
case SurfaceFormat.Single:
case SurfaceFormat.Rg32:
case SurfaceFormat.HalfVector2:
case SurfaceFormat.NormalizedByte4:
case SurfaceFormat.Rgba1010102:
case SurfaceFormat.ColorBgraEXT:
case SurfaceFormat.ColorSrgbEXT:
case SurfaceFormat.HalfVector4:
case SurfaceFormat.Rgba64:
case SurfaceFormat.Vector2:
case SurfaceFormat.HdrBlendable:
case SurfaceFormat.Vector4:
return 1;
default:
throw new ArgumentException("Should be a value defined in SurfaceFormat", "Format");
}
}

internal static int GetFormatSize(SurfaceFormat format)
{
switch (format)
Expand Down
15 changes: 15 additions & 0 deletions src/Graphics/Texture2D.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,14 @@ int elementCount
{
throw new ArgumentNullException("data");
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException("startIndex");
}
if (data.Length < (elementCount + startIndex))
{
throw new ArgumentOutOfRangeException("elementCount");
}

int x, y, w, h;
if (rect.HasValue)
Expand All @@ -180,6 +188,13 @@ int elementCount
h = Math.Max(Height >> level, 1);
}
int elementSize = Marshal.SizeOf(typeof(T));
int requiredBytes = (w * h * GetFormatSize(Format)) / GetBlockSizeSquared(Format);
int availableBytes = elementCount * elementSize;
if (requiredBytes > availableBytes)
{
throw new ArgumentOutOfRangeException("rect", "The region you are trying to upload is larger than the amount of data you provided.");
}

GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
FNA3D.FNA3D_SetTextureData2D(
GraphicsDevice.GLDevice,
Expand Down

0 comments on commit 31ff5cd

Please sign in to comment.