Skip to content

Commit

Permalink
third bug fix: don't cast bytes to booleans
Browse files Browse the repository at this point in the history
  • Loading branch information
adamsitnik committed Sep 12, 2024
1 parent 61a9b14 commit fcb3c8a
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,18 @@ internal static IReadOnlyList<T> DecodePrimitiveTypes(BinaryReader reader, int c
}
}

if (typeof(T) == typeof(bool))
{
// See DontCastBytesToBooleans test to see what could go wrong.
bool[] booleans = (bool[])(object)result;
for (int i = 0; i < booleans.Length; i++)
{
if (booleans[i]) // it can be any byte different than 0
{
booleans[i] = true; // set it to 1 in explicit way
}
}
}
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;

namespace System.Formats.Nrbf.Tests;
Expand All @@ -24,6 +25,33 @@ public static IEnumerable<object[]> GetCanReadArrayOfAnySizeArgs()
}
}

[Fact]
public void DontCastBytesToBooleans()
{
using MemoryStream stream = new();
BinaryWriter writer = new(stream, Encoding.UTF8);

WriteSerializedStreamHeader(writer);
writer.Write((byte)SerializationRecordType.ArraySinglePrimitive);
writer.Write(1); // object ID
writer.Write(2); // length
writer.Write((byte)PrimitiveType.Boolean); // element type
writer.Write((byte)0x01);
writer.Write((byte)0x02);
writer.Write((byte)SerializationRecordType.MessageEnd);
stream.Position = 0;

SZArrayRecord<bool> serializationRecord = (SZArrayRecord<bool>)NrbfDecoder.Decode(stream);

bool[] bools = serializationRecord.GetArray();
bool a = bools[0];
Assert.True(a);
bool b = bools[1];
Assert.True(b);
bool c = a && b;
Assert.True(c);
}

[Theory]
[MemberData(nameof(GetCanReadArrayOfAnySizeArgs))]
public void CanReadArrayOfAnySize_Bool(int size, bool canSeek) => Test<bool>(size, canSeek);
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Formats.Nrbf/tests/AttackTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public void ArraysOfBytesAreNotBeingPreAllocated()
writer.Write((byte)SerializationRecordType.ArraySinglePrimitive);
writer.Write(1); // object ID
writer.Write(Array.MaxLength); // length
writer.Write((byte)2); // PrimitiveType.Byte
writer.Write((byte)PrimitiveType.Byte);
writer.Write((byte)SerializationRecordType.MessageEnd);

stream.Position = 0;
Expand Down

0 comments on commit fcb3c8a

Please sign in to comment.