From 0f2e213ae9796dea73f4bdb0878a5066e8b97cbd Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Fri, 2 Dec 2016 09:06:40 +1100 Subject: [PATCH] Add bounds checks. Fix #29 --- src/ImageSharp/Image/PixelAccessor.cs | 34 +++++++++++++++++-- .../Samplers/Processors/CropProcessor.cs | 5 +++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/ImageSharp/Image/PixelAccessor.cs b/src/ImageSharp/Image/PixelAccessor.cs index 0f8390677..255285c21 100644 --- a/src/ImageSharp/Image/PixelAccessor.cs +++ b/src/ImageSharp/Image/PixelAccessor.cs @@ -104,8 +104,38 @@ namespace ImageSharp /// The at the specified position. public TColor this[int x, int y] { - get { return Unsafe.Read(this.pixelsBase + (((y * this.Width) + x) * Unsafe.SizeOf())); } - set { Unsafe.Write(this.pixelsBase + (((y * this.Width) + x) * Unsafe.SizeOf()), value); } + get + { +#if DEBUG + if (x < 0 || x >= this.Width) + { + throw new ArgumentOutOfRangeException(nameof(x), x, $"{x} is outwith the image bounds."); + } + + if (y < 0 || y >= this.Height) + { + throw new ArgumentOutOfRangeException(nameof(y), y, $"{y} is outwith the image bounds."); + } +#endif + return Unsafe.Read(this.pixelsBase + (((y * this.Width) + x) * Unsafe.SizeOf())); + } + + set + { +#if DEBUG + if (x < 0 || x >= this.Width) + { + throw new ArgumentOutOfRangeException(nameof(x), x, $"{x} is outwith the image bounds."); + } + + if (y < 0 || y >= this.Height) + { + throw new ArgumentOutOfRangeException(nameof(y), y, $"{y} is outwith the image bounds."); + } +#endif + + Unsafe.Write(this.pixelsBase + (((y * this.Width) + x) * Unsafe.SizeOf()), value); + } } /// diff --git a/src/ImageSharp/Samplers/Processors/CropProcessor.cs b/src/ImageSharp/Samplers/Processors/CropProcessor.cs index 0e8510837..7d64e8868 100644 --- a/src/ImageSharp/Samplers/Processors/CropProcessor.cs +++ b/src/ImageSharp/Samplers/Processors/CropProcessor.cs @@ -24,6 +24,11 @@ namespace ImageSharp.Processors int sourceX = sourceRectangle.X; int sourceY = sourceRectangle.Y; + Guard.MustBeGreaterThanOrEqualTo(startX, sourceX, nameof(targetRectangle)); + Guard.MustBeGreaterThanOrEqualTo(startY, sourceY, nameof(targetRectangle)); + Guard.MustBeLessThanOrEqualTo(endX, sourceRectangle.Right, nameof(targetRectangle)); + Guard.MustBeLessThanOrEqualTo(endY, sourceRectangle.Bottom, nameof(targetRectangle)); + using (PixelAccessor sourcePixels = source.Lock()) using (PixelAccessor targetPixels = target.Lock()) {