-
Notifications
You must be signed in to change notification settings - Fork 317
fix: validate byte array length in RegisterFunctions converters (#38) #216
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JoshuaVlantis
wants to merge
1
commit into
NModbus:master
Choose a base branch
from
JoshuaVlantis:fix/issue-38-readintholdingregisters-wordsize
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+124
−2
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
100 changes: 100 additions & 0 deletions
100
NModbus.UnitTests/Extensions/ModbusMasterEnhancedFixture.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| using System; | ||
| using Moq; | ||
| using NModbus.Extensions; | ||
| using NModbus.Extensions.Functions; | ||
| using Xunit; | ||
|
|
||
| namespace NModbus.UnitTests.Extensions | ||
| { | ||
| /// <summary> | ||
| /// Regression coverage for issue #38: <see cref="ModbusMasterEnhanced.ReadIntHoldingRegisters"/> | ||
| /// (and the other Read*HoldingRegisters helpers) crashed with a confusing | ||
| /// "Destination array is not long enough" exception when the configured | ||
| /// <c>wordSize</c> was smaller than the requested numeric type. | ||
| /// </summary> | ||
| public class ModbusMasterEnhancedFixture | ||
| { | ||
| private static Mock<IModbusMaster> BuildMaster(ushort[] response) | ||
| { | ||
| var master = new Mock<IModbusMaster>(MockBehavior.Strict); | ||
| master | ||
| .Setup(m => m.ReadHoldingRegisters(It.IsAny<byte>(), It.IsAny<ushort>(), It.IsAny<ushort>())) | ||
| .Returns(response); | ||
| return master; | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ReadIntHoldingRegisters_WordSize16_ThrowsClearArgumentException() | ||
| { | ||
| // Arrange: wordSize=16 means a "value" is a single 16-bit register, | ||
| // which is too small to hold a 32-bit int. The library should reject | ||
| // the call with an actionable error rather than crashing inside | ||
| // BitConverter with "Destination array is not long enough" (issue #38). | ||
| var master = BuildMaster(new ushort[] { 0x1234 }); | ||
| var enhanced = new ModbusMasterEnhanced(master.Object, wordSize: 16); | ||
|
|
||
| // Act + Assert | ||
| var ex = Assert.Throws<ArgumentException>(() => enhanced.ReadIntHoldingRegisters(1, 10, 1)); | ||
| Assert.Contains("wordSize", ex.Message, StringComparison.OrdinalIgnoreCase); | ||
| Assert.Contains("32", ex.Message); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ReadUintHoldingRegisters_WordSize16_ThrowsClearArgumentException() | ||
| { | ||
| var master = BuildMaster(new ushort[] { 0x1234 }); | ||
| var enhanced = new ModbusMasterEnhanced(master.Object, wordSize: 16); | ||
|
|
||
| var ex = Assert.Throws<ArgumentException>(() => enhanced.ReadUintHoldingRegisters(1, 10, 1)); | ||
| Assert.Contains("wordSize", ex.Message, StringComparison.OrdinalIgnoreCase); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ReadFloatHoldingRegisters_WordSize16_ThrowsClearArgumentException() | ||
| { | ||
| var master = BuildMaster(new ushort[] { 0x1234 }); | ||
| var enhanced = new ModbusMasterEnhanced(master.Object, wordSize: 16); | ||
|
|
||
| var ex = Assert.Throws<ArgumentException>(() => enhanced.ReadFloatHoldingRegisters(1, 10, 1)); | ||
| Assert.Contains("wordSize", ex.Message, StringComparison.OrdinalIgnoreCase); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ReadShortHoldingRegisters_WordSize16_StillWorks() | ||
| { | ||
| // 16-bit values fit in a 16-bit word, so this should succeed and not regress. | ||
| var master = BuildMaster(new ushort[] { 0x1234 }); | ||
| var enhanced = new ModbusMasterEnhanced(master.Object, wordSize: 16); | ||
|
|
||
| short[] result = enhanced.ReadShortHoldingRegisters(1, 10, 1); | ||
| Assert.Single(result); | ||
| Assert.Equal(unchecked((short)0x1234), result[0]); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ReadIntHoldingRegisters_WordSize32_StillWorks() | ||
| { | ||
| // Sanity check that the wordSize=32 path is unchanged by the validation guard. | ||
| // We don't pin the exact byte order here, that's already covered by the | ||
| // existing extension tests and depends on host endianness. | ||
| var master = BuildMaster(new ushort[] { 0x1234, 0x5678 }); | ||
| var enhanced = new ModbusMasterEnhanced(master.Object, wordSize: 32); | ||
|
|
||
| int[] result = enhanced.ReadIntHoldingRegisters(1, 10, 1); | ||
| Assert.Single(result); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ByteValueArraysToInts_FrontPaddingWithSmallArray_ThrowsClearArgumentException() | ||
| { | ||
| // Direct coverage on the low-level helper: passing 2-byte arrays | ||
| // would previously throw ArgumentOutOfRangeException from BitConverter | ||
| // with "index" name and a confusing "Destination array is not long enough" | ||
| // chain. We now throw ArgumentException up front with a clearer message. | ||
| byte[][] tooSmall = { new byte[] { 0x12, 0x34 } }; | ||
|
|
||
| var ex = Assert.Throws<ArgumentException>(() => RegisterFunctions.ByteValueArraysToInts(tooSmall)); | ||
| Assert.Contains("4 bytes", ex.Message); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -67,25 +67,48 @@ public static ushort[] ByteValueArraysToUShorts(byte[][] data, bool frontPadding | |
|
|
||
| public static int[] ByteValueArraysToInts(byte[][] data, bool frontPadding = true) | ||
| { | ||
| RequireMinimumByteLength(data, 4, nameof(ByteValueArraysToInts)); | ||
| return frontPadding | ||
| ? data.Select(e => BitConverter.ToInt32(e, e.Length - 4)).ToArray() | ||
| : data.Select(e => BitConverter.ToInt32(e, 0)).ToArray(); | ||
| } | ||
|
|
||
| public static uint[] ByteValueArraysToUInts(byte[][] data, bool frontPadding = true) | ||
| { | ||
| RequireMinimumByteLength(data, 4, nameof(ByteValueArraysToUInts)); | ||
| return frontPadding | ||
| ? data.Select(e => BitConverter.ToUInt32(e, e.Length - 4)).ToArray() | ||
| : data.Select(e => BitConverter.ToUInt32(e, 0)).ToArray(); | ||
| } | ||
|
|
||
| public static float[] ByteValueArraysToFloats(byte[][] data, bool frontPadding = true) | ||
| { | ||
| RequireMinimumByteLength(data, 4, nameof(ByteValueArraysToFloats)); | ||
| return frontPadding | ||
| ? data.Select(e => BitConverter.ToSingle(e, e.Length - 4)).ToArray() | ||
| : data.Select(e => BitConverter.ToSingle(e, 0)).ToArray(); | ||
| } | ||
|
|
||
| private static void RequireMinimumByteLength(byte[][] data, int minBytes, string operation) | ||
| { | ||
| // Issue #38: previously, supplying byte arrays narrower than the target | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can remove long comment, code is nice and clear already and there does not seem to be a convention with references to specific issues in this code base. |
||
| // numeric type leaked through to BitConverter and raised an opaque | ||
| // ArgumentOutOfRangeException about "startIndex". Validate up front so | ||
| // callers configuring ModbusMasterEnhanced with too small a wordSize | ||
| // see an actionable message instead. | ||
| if (data == null) throw new ArgumentNullException(nameof(data)); | ||
| for (int i = 0; i < data.Length; i++) | ||
| { | ||
| if (data[i] == null || data[i].Length < minBytes) | ||
| { | ||
| throw new ArgumentException( | ||
| $"{operation} requires each byte array to be at least {minBytes} bytes; element {i} has {data[i]?.Length ?? 0}. " + | ||
| "When using ModbusMasterEnhanced, set wordSize to at least the size of the value being read (e.g. 32 for int/uint/float).", | ||
| nameof(data)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| public static byte[][] CharsToByteValueArrays(char[] data, uint wordSize, bool frontPadding = true, bool singleCharPerRegister = true) | ||
| { | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's remove this change here and handle it in #218