From 829bb948981ee1bffaeb75fd0cff363193d2846a Mon Sep 17 00:00:00 2001 From: Filip Navara Date: Tue, 10 Nov 2026 00:59:22 +0100 Subject: [PATCH 1/5] Marshal.SizeOf/OffsetOf of structs with fixed-size buffers A fixed-size buffer field is the compiler's e__FixedBuffer struct: one element field and StructLayout.Size = FixedSize * sizeof(element). The marshaller lays it out as at least that large, aligned as one element marshalled with the container's CharSet (an ANSI char is one byte, so a fixed char buffer of a default struct is byte-aligned; CharSet.Unicode keeps it 2-byte aligned). SizeOf and OffsetOf now compute that layout instead of refusing the struct. Copying such a struct (PtrToStructure, StructureToPtr, DestroyStructure) stays an explicit diagnostic: .NET's marshaller converts only the buffer's first element and zeroes the rest, which is not modelled. Sample 1304 is recorded from .NET. --- .../CodeGen/FunctionCodeGen.MarshalLayout.cs | 25 +++++++++-- .../1304_marshal_sizeof_fixed_buffer.cs | 43 +++++++++++++++++++ .../1304_marshal_sizeof_fixed_buffer.expected | 8 ++++ 3 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 tests/samples/1304_marshal_sizeof_fixed_buffer.cs create mode 100644 tests/samples/1304_marshal_sizeof_fixed_buffer.expected diff --git a/src/Csharpc/CodeGen/FunctionCodeGen.MarshalLayout.cs b/src/Csharpc/CodeGen/FunctionCodeGen.MarshalLayout.cs index 58bbfbac..f21eaf56 100644 --- a/src/Csharpc/CodeGen/FunctionCodeGen.MarshalLayout.cs +++ b/src/Csharpc/CodeGen/FunctionCodeGen.MarshalLayout.cs @@ -28,6 +28,8 @@ private sealed class NativeLayout(ITypeSymbol type, NativeKind kind) public int BoolSize { get; set; } = 4; public List Fields { get; } = []; public bool IsClass { get; set; } + /// A fixed-size buffer anywhere in the layout: sizes and offsets are known, element conversion is not modelled. + public bool HasFixedBuffer { get; set; } } /// What the marshaller would refuse (an ArgumentException at run time) versus what csharpc can't do yet. @@ -106,7 +108,11 @@ private NativeLayout NativeLayoutOfType(ITypeSymbol type, bool sizeOf) if (type is not INamedTypeSymbol { TypeKind: TypeKind.Struct or TypeKind.Class } structure) throw notMarshalable; if (!_m.IsUserType(structure)) throw new NativeLayoutException(false, $"Marshal layout of library type '{name}'"); - return BuildNativeLayout(structure, notMarshalable); + var layout = BuildNativeLayout(structure, notMarshalable); + // .NET's marshaller converts only a fixed-size buffer's first element (the generated struct's one field) and + // zeroes the rest: SizeOf/OffsetOf are exact, copying such a struct is left unsupported rather than approximated. + if (!sizeOf && layout.HasFixedBuffer) throw new NativeLayoutException(false, $"marshalling the contents of a fixed-size buffer in '{name}'"); + return layout; } /// A field or element of a primitive, native-int, enum, bool, char or opaque (decimal, Guid) type; null for anything else. @@ -159,14 +165,27 @@ private NativeLayout BuildNativeLayout(INamedTypeSymbol type, NativeLayoutExcept var align = 1; foreach (var field in type.GetMembers().OfType().Where(f => !f.IsStatic && !f.IsConst)) { - if (field.IsFixedSizeBuffer) throw new NativeLayoutException(false, $"Marshal layout of fixed-size buffer '{field.Name}'"); var fieldType = S(field.Type); - var leaf = NativeScalarLayout(fieldType, field, charSet, notMarshalable); + NativeLayout? leaf; + if (field.IsFixedSizeBuffer) + { + // The compiler's e__FixedBuffer struct: one element field (marshalled with the container's CharSet) + // and StructLayout.Size = FixedSize elements of managed size, so it is at least that large and aligned as its element. + var element = fieldType is IPointerTypeSymbol { PointedAtType: var pointed } ? S(pointed) + : throw new NativeLayoutException(false, $"Marshal layout of fixed-size buffer '{field.Name}'"); + var elementLeaf = NativeScalarLayout(element, null, charSet, notMarshalable) + ?? throw new NativeLayoutException(false, $"Marshal layout of fixed-size buffer '{field.Name}' of '{element}'"); + var managedBytes = field.FixedSize * (int)T.Target.SizeOf(T.Storage(element)); + leaf = new NativeLayout(fieldType, NativeKind.Opaque) { Size = Math.Max(elementLeaf.Size, managedBytes), Align = elementLeaf.Align }; + layout.HasFixedBuffer = true; + } + else leaf = NativeScalarLayout(fieldType, field, charSet, notMarshalable); if (leaf is null) { if (fieldType is not INamedTypeSymbol { TypeKind: TypeKind.Struct } nestedType || !_m.IsUserType(nestedType) ) throw new NativeLayoutException(false, $"Marshal layout of field '{field.Name}' of type '{fieldType}'"); leaf = BuildNativeLayout(nestedType, notMarshalable); + layout.HasFixedBuffer |= leaf.HasFixedBuffer; } var fieldAlign = pack == 0 ? leaf.Align : Math.Min(leaf.Align, pack); long offset; diff --git a/tests/samples/1304_marshal_sizeof_fixed_buffer.cs b/tests/samples/1304_marshal_sizeof_fixed_buffer.cs new file mode 100644 index 00000000..d8e52928 --- /dev/null +++ b/tests/samples/1304_marshal_sizeof_fixed_buffer.cs @@ -0,0 +1,43 @@ +#:property AllowUnsafeBlocks=true +// Marshal.SizeOf and OffsetOf of structs with fixed-size buffers: the compiler's e__FixedBuffer struct is as large as +// its elements (StructLayout.Size) and aligned as one element marshalled with the container's CharSet. +using System; +using System.Runtime.InteropServices; + +unsafe struct Checkpoint +{ + public ulong ItemId; + public short AccountIdLength; + public fixed char AccountIdBuffer[40]; + public short HandlerIdLength; + public fixed char HandlerIdBuffer[8]; +} + +unsafe struct Ints { public byte A; public fixed int B[3]; public byte C; } + +[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] +unsafe struct Wide { public byte A; public fixed char B[5]; public byte C; } + +unsafe struct Narrow { public byte A; public fixed char B[5]; public byte C; } + +unsafe struct Longs { public byte A; public fixed long B[2]; public byte C; } + +// bool marshals as a 4-byte BOOL: the buffer is the larger of one marshalled element and its managed size. +unsafe struct Bools { public byte A; public fixed bool B[3]; public int C; } + +struct Outer { public byte Tag; public Ints Inner; } + +static unsafe class Program +{ + static void Main() + { + Console.WriteLine($"Checkpoint {Marshal.SizeOf()} {sizeof(Checkpoint)} {Marshal.OffsetOf(nameof(Checkpoint.AccountIdBuffer))} {Marshal.OffsetOf(nameof(Checkpoint.HandlerIdLength))} {Marshal.OffsetOf(nameof(Checkpoint.HandlerIdBuffer))}"); + Console.WriteLine($"Ints {Marshal.SizeOf()} {sizeof(Ints)} {Marshal.OffsetOf("B")} {Marshal.OffsetOf("C")}"); + Console.WriteLine($"Wide {Marshal.SizeOf()} {sizeof(Wide)} {Marshal.OffsetOf("B")} {Marshal.OffsetOf("C")}"); + Console.WriteLine($"Narrow {Marshal.SizeOf()} {sizeof(Narrow)} {Marshal.OffsetOf("B")} {Marshal.OffsetOf("C")}"); + Console.WriteLine($"Longs {Marshal.SizeOf()} {sizeof(Longs)} {Marshal.OffsetOf("B")} {Marshal.OffsetOf("C")}"); + Console.WriteLine($"Bools {Marshal.SizeOf()} {sizeof(Bools)} {Marshal.OffsetOf("B")} {Marshal.OffsetOf("C")}"); + Console.WriteLine($"Outer {Marshal.SizeOf()} {Marshal.OffsetOf("Inner")}"); + Console.WriteLine($"typeof {Marshal.SizeOf(typeof(Checkpoint))}"); + } +} diff --git a/tests/samples/1304_marshal_sizeof_fixed_buffer.expected b/tests/samples/1304_marshal_sizeof_fixed_buffer.expected new file mode 100644 index 00000000..10eec986 --- /dev/null +++ b/tests/samples/1304_marshal_sizeof_fixed_buffer.expected @@ -0,0 +1,8 @@ +Checkpoint 112 112 10 90 92 +Ints 20 20 4 16 +Wide 14 14 2 12 +Narrow 12 14 1 11 +Longs 32 32 8 24 +Bools 12 8 4 8 +Outer 24 4 +typeof 112 From 89fe75a62f5aace42638487b55d8b8844ac8d063 Mon Sep 17 00:00:00 2001 From: Filip Navara Date: Tue, 10 Nov 2026 07:36:11 +0100 Subject: [PATCH 2/5] Uri: relative references and implicit file paths with spaces csharpc's Uri refused a relative reference with any character .NET would escape, and an implicit file path likewise, so XmlReader.Create(path) failed for any path with a space (XmlUrlResolver makes a relative Uri of it, then an absolute one from Path.GetFullPath): on macOS that is every file in an "X Y.app" bundle. Spaces are now accepted in both: a relative reference keeps them as they are in OriginalString and ToString(), as .NET does; an implicit file path escapes them to %20 in the URI's path (AbsoluteUri, AbsolutePath, Segments) and keeps them in LocalPath and ToString(). '%' stays refused, so unescaping %20 for ToString() is exact; explicit file: URIs are unchanged. Sample 1308 is recorded from .NET. --- src/Csharpc/corelib/Net/Uri.cs | 14 ++++-- tests/samples/1308_uri_paths_with_spaces.cs | 44 +++++++++++++++++++ .../1308_uri_paths_with_spaces.expected | 10 +++++ 3 files changed, 64 insertions(+), 4 deletions(-) create mode 100644 tests/samples/1308_uri_paths_with_spaces.cs create mode 100644 tests/samples/1308_uri_paths_with_spaces.expected diff --git a/src/Csharpc/corelib/Net/Uri.cs b/src/Csharpc/corelib/Net/Uri.cs index 509eae37..bb4029eb 100644 --- a/src/Csharpc/corelib/Net/Uri.cs +++ b/src/Csharpc/corelib/Net/Uri.cs @@ -146,7 +146,9 @@ private static bool IsWindowsRootedPath(string s) => private static void CheckRelative(string s) { // '#' starts a fragment: .NET keeps it as it is, but calls such a reference not well formed. - if (s.Length != 0 && (s.Trim().Length == 0 || !IsPlain(s.Replace('#', '/'), 0, true))) throw Unsupported("this relative URI"); + // Spaces too: .NET keeps them as they are in OriginalString and ToString() of a relative reference (a path such as + // ".../eM Client.app/Contents/...", which XmlResolver then makes absolute with Path.GetFullPath). + if (s.Length != 0 && (s.Trim().Length == 0 || !IsPlain(s.Replace('#', '/').Replace(' ', '/'), 0, true))) throw Unsupported("this relative URI"); } /// @@ -183,8 +185,12 @@ private static bool TryParseFile(string s, out string path, out string localPath } #endif string slashed = drive ? rest.Replace('\\', '/') : rest; - if (!IsPlain(slashed, 0, false) || HasDotSegment(slashed) || slashed.Contains("//")) throw Unsupported("file paths .NET escapes or rewrites"); - path = drive ? "/" + slashed : slashed; + // Spaces in an implicit path (".../eM Client.app/..."): .NET escapes them to %20 in the URI's path and AbsoluteUri, + // and keeps them in LocalPath and ToString(). No other character that .NET escapes is modelled ('%' stays refused, + // so ToString's unescaping of %20 is exact). + string checkedPath = explicitScheme ? slashed : slashed.Replace(' ', '/'); + if (!IsPlain(checkedPath, 0, false) || HasDotSegment(slashed) || slashed.Contains("//")) throw Unsupported("file paths .NET escapes or rewrites"); + path = (drive ? "/" + slashed : slashed).Replace(" ", "%20"); localPath = drive ? slashed.Replace('/', '\\') : slashed; return true; } @@ -486,7 +492,7 @@ public string GetLeftPart(UriPartial part) private static int DefaultPort(string scheme) => scheme switch { "http" => 80, "https" => 443, "ftp" => 21, "ws" => 80, "wss" => 443, _ => -1 }; - public override string ToString() => _relative ? _original : AbsoluteUri; + public override string ToString() => _relative ? _original : _file ? AbsoluteUri.Replace("%20", " ") : AbsoluteUri; // .NET compares the scheme, host, port, path and query (the scheme and host case-insensitively, // which the lowercased fields already are) and ignores the fragment; a string is parsed first. diff --git a/tests/samples/1308_uri_paths_with_spaces.cs b/tests/samples/1308_uri_paths_with_spaces.cs new file mode 100644 index 00000000..b8e5c2e3 --- /dev/null +++ b/tests/samples/1308_uri_paths_with_spaces.cs @@ -0,0 +1,44 @@ +// Paths with spaces as URIs: a relative reference keeps them as they are (OriginalString, ToString); an implicit file +// path escapes them to %20 in AbsoluteUri/AbsolutePath and keeps them in LocalPath and ToString(). XmlReader.Create(path) +// goes through both (XmlUrlResolver: a relative Uri, then Path.GetFullPath). +using System; +using System.IO; +using System.Xml; + +static class Program +{ + static void Main() + { + var relative = new Uri("dir with space/p.xml", UriKind.RelativeOrAbsolute); + Console.WriteLine($"{relative.IsAbsoluteUri} [{relative.OriginalString}] [{relative}]"); + Console.WriteLine(Uri.TryCreate("a b/c", UriKind.Relative, out var tried) ? $"relative [{tried}]" : "not relative"); + + var root = Path.Combine(Path.GetTempPath(), "csharpc uri sample " + Environment.ProcessId); + var dir = Path.Combine(root, "dir with space"); + Directory.CreateDirectory(dir); + try + { + var file = Path.Combine(dir, "p.xml"); + File.WriteAllText(file, "hi"); + + var absolute = new Uri(file); + Console.WriteLine(absolute.IsAbsoluteUri + " " + absolute.IsFile + " " + absolute.Scheme); + Console.WriteLine(absolute.AbsoluteUri.EndsWith("/dir%20with%20space/p.xml", StringComparison.Ordinal)); + Console.WriteLine(absolute.AbsolutePath.EndsWith("/dir%20with%20space/p.xml", StringComparison.Ordinal)); + Console.WriteLine(absolute.LocalPath == file); + Console.WriteLine(absolute.ToString().EndsWith("/dir with space/p.xml", StringComparison.Ordinal)); + Console.WriteLine(absolute.Segments[^2] + absolute.Segments[^1]); + + Directory.SetCurrentDirectory(root); + using var reader = XmlReader.Create(Path.Combine("dir with space", "p.xml")); + reader.MoveToContent(); + Console.WriteLine($"{reader.Name} {reader.GetAttribute("a")} {reader.ReadInnerXml()}"); + Console.WriteLine(reader.BaseURI.EndsWith("/dir with space/p.xml", StringComparison.Ordinal)); + } + finally + { + Directory.SetCurrentDirectory(Path.GetTempPath()); + Directory.Delete(root, true); + } + } +} diff --git a/tests/samples/1308_uri_paths_with_spaces.expected b/tests/samples/1308_uri_paths_with_spaces.expected new file mode 100644 index 00000000..e7f43101 --- /dev/null +++ b/tests/samples/1308_uri_paths_with_spaces.expected @@ -0,0 +1,10 @@ +False [dir with space/p.xml] [dir with space/p.xml] +relative [a b/c] +True True file +True +True +True +True +dir%20with%20space/p.xml +root 1 hi +True From b3811fe5e76ec9b978766361c49324fde2180dec Mon Sep 17 00:00:00 2001 From: Filip Navara Date: Tue, 10 Nov 2026 09:19:15 +0100 Subject: [PATCH 3/5] Renumber sample 1304 to 1340 (upstream has its own 1304 now) --- ...sizeof_fixed_buffer.cs => 1340_marshal_sizeof_fixed_buffer.cs} | 0 ..._buffer.expected => 1340_marshal_sizeof_fixed_buffer.expected} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename tests/samples/{1304_marshal_sizeof_fixed_buffer.cs => 1340_marshal_sizeof_fixed_buffer.cs} (100%) rename tests/samples/{1304_marshal_sizeof_fixed_buffer.expected => 1340_marshal_sizeof_fixed_buffer.expected} (100%) diff --git a/tests/samples/1304_marshal_sizeof_fixed_buffer.cs b/tests/samples/1340_marshal_sizeof_fixed_buffer.cs similarity index 100% rename from tests/samples/1304_marshal_sizeof_fixed_buffer.cs rename to tests/samples/1340_marshal_sizeof_fixed_buffer.cs diff --git a/tests/samples/1304_marshal_sizeof_fixed_buffer.expected b/tests/samples/1340_marshal_sizeof_fixed_buffer.expected similarity index 100% rename from tests/samples/1304_marshal_sizeof_fixed_buffer.expected rename to tests/samples/1340_marshal_sizeof_fixed_buffer.expected From 584359e48258233c3cd10fdc8b3616710d10da5a Mon Sep 17 00:00:00 2001 From: Filip Navara Date: Tue, 10 Nov 2026 09:19:33 +0100 Subject: [PATCH 4/5] Renumber sample 1308 to 1344 (upstream has its own 1308 now) --- ...308_uri_paths_with_spaces.cs => 1344_uri_paths_with_spaces.cs} | 0 ...s_with_spaces.expected => 1344_uri_paths_with_spaces.expected} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename tests/samples/{1308_uri_paths_with_spaces.cs => 1344_uri_paths_with_spaces.cs} (100%) rename tests/samples/{1308_uri_paths_with_spaces.expected => 1344_uri_paths_with_spaces.expected} (100%) diff --git a/tests/samples/1308_uri_paths_with_spaces.cs b/tests/samples/1344_uri_paths_with_spaces.cs similarity index 100% rename from tests/samples/1308_uri_paths_with_spaces.cs rename to tests/samples/1344_uri_paths_with_spaces.cs diff --git a/tests/samples/1308_uri_paths_with_spaces.expected b/tests/samples/1344_uri_paths_with_spaces.expected similarity index 100% rename from tests/samples/1308_uri_paths_with_spaces.expected rename to tests/samples/1344_uri_paths_with_spaces.expected From da0d90f49b18d87ebc61347fbd9fd9f1f8fc75bb Mon Sep 17 00:00:00 2001 From: Jonathan Peris Date: Fri, 27 Nov 2026 15:50:38 -0300 Subject: [PATCH 5/5] Keep backslashes in relative URIs; such references are not well formed On Windows, XmlReader.Create(Path.Combine("dir with space", "p.xml")) makes a relative Uri of "dir with space\p.xml", which the space-only change still refused. .NET keeps backslashes as they are in a relative reference's OriginalString and ToString(), as it does spaces. IsWellFormedOriginalString / IsWellFormedUriString now return false for a relative reference with a space or a backslash, as .NET does (characters it would have to escape); they returned true once spaces were accepted. Resolving such a reference against a base stays NotSupportedException. --- src/Csharpc/corelib/Net/Uri.cs | 7 ++++--- src/Csharpc/corelib/Net/UriRelative.cs | 6 +++--- tests/samples/1344_uri_paths_with_spaces.cs | 6 ++++++ tests/samples/1344_uri_paths_with_spaces.expected | 5 +++++ 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/Csharpc/corelib/Net/Uri.cs b/src/Csharpc/corelib/Net/Uri.cs index bb4029eb..7914e3d0 100644 --- a/src/Csharpc/corelib/Net/Uri.cs +++ b/src/Csharpc/corelib/Net/Uri.cs @@ -146,9 +146,10 @@ private static bool IsWindowsRootedPath(string s) => private static void CheckRelative(string s) { // '#' starts a fragment: .NET keeps it as it is, but calls such a reference not well formed. - // Spaces too: .NET keeps them as they are in OriginalString and ToString() of a relative reference (a path such as - // ".../eM Client.app/Contents/...", which XmlResolver then makes absolute with Path.GetFullPath). - if (s.Length != 0 && (s.Trim().Length == 0 || !IsPlain(s.Replace('#', '/').Replace(' ', '/'), 0, true))) throw Unsupported("this relative URI"); + // Spaces and backslashes too: .NET keeps them as they are in OriginalString and ToString() of a relative reference + // (a path such as ".../eM Client.app/Contents/..." or Windows' "dir with space\p.xml", which XmlResolver then makes + // absolute with Path.GetFullPath). Resolving such a reference against a base stays unsupported. + if (s.Length != 0 && (s.Trim().Length == 0 || !IsPlain(s.Replace('#', '/').Replace(' ', '/').Replace('\\', '/'), 0, true))) throw Unsupported("this relative URI"); } /// diff --git a/src/Csharpc/corelib/Net/UriRelative.cs b/src/Csharpc/corelib/Net/UriRelative.cs index 422aaa01..5033d208 100644 --- a/src/Csharpc/corelib/Net/UriRelative.cs +++ b/src/Csharpc/corelib/Net/UriRelative.cs @@ -276,9 +276,9 @@ public static int Compare(Uri uri1, Uri uri2, UriComponents partsToCompare, UriF // ---- well-formedness, formatting, host names ---- - // For this subset a reference is well formed unless it is an implicit file path or a relative reference - // with a fragment. - public bool IsWellFormedOriginalString() => _relative ? _original.IndexOf('#') < 0 : !_implicitFile; + // For this subset a reference is well formed unless it is an implicit file path or a relative reference with a + // fragment, a space or a backslash (characters .NET would have to escape; Uri.cs keeps them only in relative references). + public bool IsWellFormedOriginalString() => _relative ? _original.AsSpan().IndexOfAny('#', ' ', '\\') < 0 : !_implicitFile; public static bool IsWellFormedUriString(string uriString, UriKind uriKind) { diff --git a/tests/samples/1344_uri_paths_with_spaces.cs b/tests/samples/1344_uri_paths_with_spaces.cs index b8e5c2e3..7097a3fc 100644 --- a/tests/samples/1344_uri_paths_with_spaces.cs +++ b/tests/samples/1344_uri_paths_with_spaces.cs @@ -12,6 +12,12 @@ static void Main() var relative = new Uri("dir with space/p.xml", UriKind.RelativeOrAbsolute); Console.WriteLine($"{relative.IsAbsoluteUri} [{relative.OriginalString}] [{relative}]"); Console.WriteLine(Uri.TryCreate("a b/c", UriKind.Relative, out var tried) ? $"relative [{tried}]" : "not relative"); + // Windows' Path.Combine gives backslashes: kept as they are too. Spaces, backslashes and '#' make a relative + // reference not well formed (characters .NET would have to escape). + var backslashed = new Uri("dir with space\\p.xml", UriKind.RelativeOrAbsolute); + Console.WriteLine($"{backslashed.IsAbsoluteUri} [{backslashed.OriginalString}] [{backslashed}]"); + foreach (var text in new[] { "a b", "a#b", "a/b", "a\\b" }) + Console.WriteLine($"{text}: {Uri.IsWellFormedUriString(text, UriKind.Relative)} {Uri.IsWellFormedUriString(text, UriKind.RelativeOrAbsolute)} {new Uri(text, UriKind.Relative).IsWellFormedOriginalString()}"); var root = Path.Combine(Path.GetTempPath(), "csharpc uri sample " + Environment.ProcessId); var dir = Path.Combine(root, "dir with space"); diff --git a/tests/samples/1344_uri_paths_with_spaces.expected b/tests/samples/1344_uri_paths_with_spaces.expected index e7f43101..9781fd1a 100644 --- a/tests/samples/1344_uri_paths_with_spaces.expected +++ b/tests/samples/1344_uri_paths_with_spaces.expected @@ -1,5 +1,10 @@ False [dir with space/p.xml] [dir with space/p.xml] relative [a b/c] +False [dir with space\p.xml] [dir with space\p.xml] +a b: False False False +a#b: False False False +a/b: True True True +a\b: False False False True True file True True