Avoid Marshal.SizeOf in EventSource (#47521)
authorMichal Strehovský <MichalStrehovsky@users.noreply.github.com>
Fri, 29 Jan 2021 14:42:04 +0000 (15:42 +0100)
committerGitHub <noreply@github.com>
Fri, 29 Jan 2021 14:42:04 +0000 (09:42 -0500)
* Avoid Marshal.SizeOf in EventSource

We're getting the marshalling size of an enum underlying type - there are not that many of those. I chose not to treat `char` and `bool`, but we could (the only other remaining options).

Calling into `Marshal.SizeOf` increases the risk that `EventSource` is going call itself recursively - see the comment at the beginning of the method.

This was originally introduced in https://github.com/dotnet/coreclr/pull/19205.

* Update src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs

* Update src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs

* Update src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs

src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs

index c6913ba..9d9fa34 100644 (file)
@@ -1696,9 +1696,16 @@ namespace System.Diagnostics.Tracing
                     {
                         dataType = Enum.GetUnderlyingType(dataType);
 
-                        int dataTypeSize = System.Runtime.InteropServices.Marshal.SizeOf(dataType);
-                        if (dataTypeSize < sizeof(int))
-                            dataType = typeof(int);
+                        // Enums less than 4 bytes in size should be treated as int.
+                        switch (Type.GetTypeCode(dataType))
+                        {
+                            case TypeCode.Byte:
+                            case TypeCode.SByte:
+                            case TypeCode.Int16:
+                            case TypeCode.UInt16:
+                                dataType = typeof(int);
+                                break;
+                        }
                         goto Again;
                     }