jefffhaynes / BinarySerializer

A declarative serialization framework for controlling formatting of data at the byte and bit level using field bindings, converters, and code.
MIT License
292 stars 62 forks source link

BinarySerializer swallows exceptions, resulting in false-positive "successful" deserialization #159

Open sanek2k6 opened 4 years ago

sanek2k6 commented 4 years ago

Hello!

BinarySerializer seems to be swallowing some exceptions (at least IOException types) and just setting the current child object being deserialized to null without any indication of an error. As such, if we don't catch the error, the invalid data flows through the system. This is especially an issue with those objects where null could be a valid value (i.e. SerializeWhen case).

Reproduction: .NET Core 3.1

class InsideTest
{
    [FieldOrder(0)]
    [SerializeAs(SerializedType.UInt1)]
    public byte Value1 { get; set; }

    [FieldOrder(1)]
    [SerializeAs(SerializedType.UInt1)]
    public byte Value2 { get; set; }
}

class Test
{
    [FieldOrder(0)]
    [SerializeAs(SerializedType.UInt1)]
    public byte Value1 { get; set; }

    [FieldOrder(1)]
    public InsideTest Value2 { get; set; }
}

static void Main(string[] args)
{
    var serializer = new BinarySerializer();
    var testBytes = new byte[] {0x01, 0x02};
    var testObject = serializer.Deserialize<Test>(testBytes);

    // testObject.Value2 will be null, but no exception will be thrown as it will swallow the IOException
}

Visual Studio debugger sees that there was a System.IO.EndOfStreamException thrown from ValueValueNode.cs:600, but it gets caught in ObjectValueNode.cs:111 and current property/child value just gets set to null instead of rethrowing the exception.

If this behavior is intentional (Loose), is it possible to configure the serializer behavior to be Strict and throw on any deserialization error?