Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
829bb94
Marshal.SizeOf/OffsetOf of structs with fixed-size buffers
filipnavara Nov 9, 2026
d8f86a6
[DynamicallyAccessedMembers] on properties and fields keeps the membe…
filipnavara Nov 10, 2026
89fe75a
Uri: relative references and implicit file paths with spaces
filipnavara Nov 10, 2026
b3811fe
Renumber sample 1304 to 1340 (upstream has its own 1304 now)
filipnavara Nov 10, 2026
2b02244
Renumber sample 1307 to 1343 (upstream has its own 1307 now)
filipnavara Nov 10, 2026
584359e
Renumber sample 1308 to 1344 (upstream has its own 1308 now)
filipnavara Nov 10, 2026
85c60a9
Merge remote-tracking branch 'origin/main' into pr-291
jonathanperis Nov 27, 2026
740c8a0
Merge remote-tracking branch 'origin/main' into pr-279
jonathanperis Nov 27, 2026
348a4e6
Merge remote-tracking branch 'origin/main' into pr-284
jonathanperis Nov 27, 2026
2be9b73
Merge branch 'feat/preserialized-bytes-stream' into pr-291
jonathanperis Nov 27, 2026
605cbff
Merge branch 'pr-291' into pr-279
jonathanperis Nov 27, 2026
96db974
Merge branch 'pr-279' into pr-284
jonathanperis Nov 27, 2026
bc9be68
Merge branch 'feat/preserialized-bytes-stream' into pr-291
jonathanperis Nov 27, 2026
7dbd2bc
Merge branch 'pr-291' into pr-279
jonathanperis Nov 27, 2026
ab99772
Merge branch 'pr-279' into pr-284
jonathanperis Nov 27, 2026
da0d90f
Keep backslashes in relative URIs; such references are not well formed
jonathanperis Nov 27, 2026
b9a398e
Merge branch 'pr-291' into pr-279
jonathanperis Nov 27, 2026
4e7a5c1
Merge branch 'pr-279' into pr-284
jonathanperis Nov 27, 2026
e01bcd5
Merge remote-tracking branch 'origin/main' into pr-284
jonathanperis Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/Csharpc/CodeGen/FunctionCodeGen.Expressions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,21 @@ private LLVMValueRef FieldAddress(IFieldReferenceOperation f)
private LLVMValueRef EmitSimpleAssignment(ISimpleAssignmentOperation a)
{
if (a.IsRef) return EmitRefAssignment(a);
if (a.Target is IPropertyReferenceOperation { Property.RefKind: RefKind.None } p) return EmitPropertySet(p, () => EmitValue(a.Value), TypeOf(a.Value));
if (a.Target is IPropertyReferenceOperation { Property.RefKind: RefKind.None } p)
{
// An assignment is the setter's call: an annotated value parameter (or property) keeps the assigned typeof's members.
if (p.Property.SetMethod is { } setter && KnownTypeofValues(a.Value) is { Count: > 0 } assigned)
foreach (var known in assigned)
_m.NoteDynamicallyAccessedArguments(S(setter), i => i == setter.Parameters.Length - 1 ? S(known) : null);
return EmitPropertySet(p, () => EmitValue(a.Value), TypeOf(a.Value));
}
if (a.Target is IFlowCaptureReferenceOperation r && _cfg!.PropertyCaptures.TryGetValue(r.Id, out var pc))
return SetCapturedProperty(pc, Coerce(EmitValue(a.Value), TypeOf(a.Value), pc.Property.Type));
// `[DynamicallyAccessedMembers(K)] Type field = typeof(X)` (an initializer or an assignment): X keeps its members of
// kinds K, as the IL front-end's NoteDynamicallyAccessedField does.
if (a.Target is IFieldReferenceOperation { Field: var annotatedField } && IsSystemType(annotatedField.Type)
&& ModuleCodeGen.DamKindsOf(annotatedField.OriginalDefinition.GetAttributes()) is var fieldKinds and not 0)
foreach (var known in KnownTypeofValues(a.Value)) _m.MarkDynamicallyAccessed(S(known), fieldKinds);

var targetType = TypeOf(a.Target)!;
var address = StoreAddress(a.Target, out var covariant); // C#: target sub-expressions are evaluated first
Expand Down
25 changes: 22 additions & 3 deletions src/Csharpc/CodeGen/FunctionCodeGen.MarshalLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ private sealed class NativeLayout(ITypeSymbol type, NativeKind kind)
public int BoolSize { get; set; } = 4;
public List<NativeField> Fields { get; } = [];
public bool IsClass { get; set; }
/// <summary>A fixed-size buffer anywhere in the layout: sizes and offsets are known, element conversion is not modelled.</summary>
public bool HasFixedBuffer { get; set; }
}

/// <summary>What the marshaller would refuse (an ArgumentException at run time) versus what csharpc can't do yet.</summary>
Expand Down Expand Up @@ -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;
}

/// <summary>A field or element of a primitive, native-int, enum, bool, char or opaque (decimal, Guid) type; null for anything else.</summary>
Expand Down Expand Up @@ -159,14 +165,27 @@ private NativeLayout BuildNativeLayout(INamedTypeSymbol type, NativeLayoutExcept
var align = 1;
foreach (var field in type.GetMembers().OfType<IFieldSymbol>().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 <name>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;
Expand Down
5 changes: 5 additions & 0 deletions src/Csharpc/CodeGen/ModuleCodeGen.Reflection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,11 @@ internal void NoteDynamicallyAccessedArguments(IMethodSymbol method, Func<int, I
{
if (typeofArgument(i) is not { } type) continue;
var kinds = DamKindsOf(method.OriginalDefinition.Parameters[i].GetAttributes());
// A property's [DynamicallyAccessedMembers] covers its setter's value, as ILLink applies it
// (`info.BoxType = typeof(Box)`, later Activator.CreateInstance(info.BoxType)).
if (kinds == 0 && i == method.Parameters.Length - 1
&& method.OriginalDefinition is { MethodKind: MethodKind.PropertySet, AssociatedSymbol: IPropertySymbol property })
kinds = DamKindsOf(property.GetAttributes());
if (type is INamedTypeSymbol { IsGenericType: true } open && (open.IsUnboundGenericType || open.IsDefinition))
{
if (kinds != 0 && openAnnotated is null) openAnnotated = (open.OriginalDefinition, kinds);
Expand Down
15 changes: 11 additions & 4 deletions src/Csharpc/corelib/Net/Uri.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +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.
if (s.Length != 0 && (s.Trim().Length == 0 || !IsPlain(s.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");
}

/// <summary>
Expand Down Expand Up @@ -183,8 +186,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;
}
Expand Down Expand Up @@ -486,7 +493,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.
Expand Down
6 changes: 3 additions & 3 deletions src/Csharpc/corelib/Net/UriRelative.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
43 changes: 43 additions & 0 deletions tests/samples/1340_marshal_sizeof_fixed_buffer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#:property AllowUnsafeBlocks=true
// Marshal.SizeOf and OffsetOf of structs with fixed-size buffers: the compiler's <name>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<Checkpoint>()} {sizeof(Checkpoint)} {Marshal.OffsetOf<Checkpoint>(nameof(Checkpoint.AccountIdBuffer))} {Marshal.OffsetOf<Checkpoint>(nameof(Checkpoint.HandlerIdLength))} {Marshal.OffsetOf<Checkpoint>(nameof(Checkpoint.HandlerIdBuffer))}");
Console.WriteLine($"Ints {Marshal.SizeOf<Ints>()} {sizeof(Ints)} {Marshal.OffsetOf<Ints>("B")} {Marshal.OffsetOf<Ints>("C")}");
Console.WriteLine($"Wide {Marshal.SizeOf<Wide>()} {sizeof(Wide)} {Marshal.OffsetOf<Wide>("B")} {Marshal.OffsetOf<Wide>("C")}");
Console.WriteLine($"Narrow {Marshal.SizeOf<Narrow>()} {sizeof(Narrow)} {Marshal.OffsetOf<Narrow>("B")} {Marshal.OffsetOf<Narrow>("C")}");
Console.WriteLine($"Longs {Marshal.SizeOf<Longs>()} {sizeof(Longs)} {Marshal.OffsetOf<Longs>("B")} {Marshal.OffsetOf<Longs>("C")}");
Console.WriteLine($"Bools {Marshal.SizeOf<Bools>()} {sizeof(Bools)} {Marshal.OffsetOf<Bools>("B")} {Marshal.OffsetOf<Bools>("C")}");
Console.WriteLine($"Outer {Marshal.SizeOf<Outer>()} {Marshal.OffsetOf<Outer>("Inner")}");
Console.WriteLine($"typeof {Marshal.SizeOf(typeof(Checkpoint))}");
}
}
8 changes: 8 additions & 0 deletions tests/samples/1340_marshal_sizeof_fixed_buffer.expected
Original file line number Diff line number Diff line change
@@ -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
34 changes: 34 additions & 0 deletions tests/samples/1343_reflection_dam_property_setter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// [DynamicallyAccessedMembers] on a property applies to the values its setter receives, as ILLink applies it: a typeof
// assigned to the property (directly or in an object initializer) keeps the members Activator.CreateInstance needs,
// for types the program never constructs itself.
using System;
using System.Diagnostics.CodeAnalysis;

abstract class Box { public abstract string Name { get; } }
sealed class MailBox : Box { public override string Name => "mail"; }
sealed class CalendarBox : Box { public override string Name => "calendar"; }
sealed class TaskBox : Box { public TaskBox() { Console.WriteLine("TaskBox()"); } public override string Name => "tasks"; }

sealed class BoxInfo
{
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
private Type boxType = typeof(MailBox);

[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
public Type BoxType { get => boxType; set => boxType = value; }

public Box Create() => (Box)Activator.CreateInstance(BoxType)!;
}

static class Program
{
static void Main()
{
var info = new BoxInfo();
Console.WriteLine(info.Create().Name);
info.BoxType = typeof(CalendarBox);
Console.WriteLine(info.Create().Name);
var other = new BoxInfo { BoxType = typeof(TaskBox) };
Console.WriteLine(other.Create().Name);
}
}
4 changes: 4 additions & 0 deletions tests/samples/1343_reflection_dam_property_setter.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
mail
calendar
TaskBox()
tasks
50 changes: 50 additions & 0 deletions tests/samples/1344_uri_paths_with_spaces.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// 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");
// 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");
Directory.CreateDirectory(dir);
try
{
var file = Path.Combine(dir, "p.xml");
File.WriteAllText(file, "<root a=\"1\"><x>hi</x></root>");

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);
}
}
}
15 changes: 15 additions & 0 deletions tests/samples/1344_uri_paths_with_spaces.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
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
True
True
dir%20with%20space/p.xml
root 1 <x>hi</x>
True