diff --git a/src/Csharpc/CodeGen/BclValueTypes.Reflection.cs b/src/Csharpc/CodeGen/BclValueTypes.Reflection.cs index f9507822..5aefc0db 100644 --- a/src/Csharpc/CodeGen/BclValueTypes.Reflection.cs +++ b/src/Csharpc/CodeGen/BclValueTypes.Reflection.cs @@ -258,7 +258,7 @@ BclHandler frameworkTypeAttributes(string method, string frameworkMethod) => (g, // isn't constructed. .NET's argument checks are corelib C# (ReflectionRuntime.GetUninitializedObject). t["System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(System.Type)"] = (g, _, _, a, at) => { - if (at is Microsoft.CodeAnalysis.Operations.IInvocationOperation { Arguments: [var argument] } && FunctionCodeGen.TypeOfOperand(argument.Value) is { } created) + if (at is Microsoft.CodeAnalysis.Operations.IInvocationOperation { Arguments: [var argument] } && g.ExactTypeOf(argument.Value) is { } created) g.NoteConstructedType(created is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T, TypeArguments: [var underlying] } ? underlying : created); return g.CallCoreLib("ReflectionRuntime", "GetUninitializedObject", a[0]); }; diff --git a/src/Csharpc/CodeGen/FunctionCodeGen.Enums.cs b/src/Csharpc/CodeGen/FunctionCodeGen.Enums.cs index 79b7532f..9f927d4d 100644 --- a/src/Csharpc/CodeGen/FunctionCodeGen.Enums.cs +++ b/src/Csharpc/CodeGen/FunctionCodeGen.Enums.cs @@ -21,7 +21,7 @@ public sealed partial class FunctionCodeGen // The Type overloads (Enum.GetValues(typeof(Color))): with a typeof operand they are the // generic ones in disguise; the leading Type argument is dropped. if (target.Parameters.FirstOrDefault()?.Type is not { Name: "Type", ContainingNamespace.Name: "System" }) return null; - if (TypeOfOperand(args[0].Value) is not { } typeOperand || S(typeOperand) is not INamedTypeSymbol { TypeKind: TypeKind.Enum } named) + if (ExactTypeOf(args[0].Value) is not { } typeOperand || S(typeOperand) is not INamedTypeSymbol { TypeKind: TypeKind.Enum } named) { // Configuration.Binder and similar pass a run-time Type into Enum.Parse/IsDefined: // lower to a corelib helper (NotSupportedException until a full run-time enum table exists) diff --git a/src/Csharpc/CodeGen/FunctionCodeGen.Expressions.cs b/src/Csharpc/CodeGen/FunctionCodeGen.Expressions.cs index 84203bc5..3682bd86 100644 --- a/src/Csharpc/CodeGen/FunctionCodeGen.Expressions.cs +++ b/src/Csharpc/CodeGen/FunctionCodeGen.Expressions.cs @@ -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 diff --git a/src/Csharpc/CodeGen/FunctionCodeGen.IlInstructions.cs b/src/Csharpc/CodeGen/FunctionCodeGen.IlInstructions.cs index 2ec86ee5..c36918ae 100644 --- a/src/Csharpc/CodeGen/FunctionCodeGen.IlInstructions.cs +++ b/src/Csharpc/CodeGen/FunctionCodeGen.IlInstructions.cs @@ -914,7 +914,7 @@ private IlValueOperation IlOperand(IlEntry e, ITypeSymbol type, bool lvalue = fa return new IlValueOperation(il.Syntax, type, () => IlTyped(e, type), nonNull: e.NonNull || e.IsThis) { Constant = e.Constant is null ? default : TypedConstant(e.Constant, type), - TypeOfOperand = e is { Kind: IlKind.Ref, Symbol: ITypeSymbol known } ? known : null, + TypeOfOperand = e is { Kind: IlKind.Ref, Symbol: ITypeSymbol known } ? known : e is { Kind: IlKind.Ref, FromLocal: { } local } ? IlExactTypeofLocal(local) : null, BoxedFrom = e is { Kind: IlKind.Ref, Unboxed: { Type: { } boxedType } boxed } && !boxed.Value.IsNull ? IlOperand(boxed, boxedType) : null, IsNullLiteral = e is { Kind: IlKind.Ref, Type: null } && !e.Value.IsNull && Native.LLVMIsNull(e.Value) != 0, EntryType = e.Type, diff --git a/src/Csharpc/CodeGen/FunctionCodeGen.MarshalLayout.cs b/src/Csharpc/CodeGen/FunctionCodeGen.MarshalLayout.cs index ca565687..f374773b 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; @@ -221,7 +240,7 @@ private NativeLayout BuildNativeLayout(INamedTypeSymbol type, NativeLayoutExcept /// The type an argument of type Type (typeof(X)) or object (the structure) stands for, when it is known statically. private ITypeSymbol? MarshalTypeOf(IOperation argument, bool structure) { - if (!structure) return TypeOfOperand(argument) is { } typeOf ? S(typeOf) : null; + if (!structure) return ExactTypeOf(argument) is { } typeOf ? S(typeOf) : null; var value = argument; while (value is IConversionOperation { Operand: var operand } conversion && !conversion.Conversion.IsUserDefined && !conversion.Conversion.IsNumeric && !conversion.Conversion.IsNullable) value = operand; diff --git a/src/Csharpc/CodeGen/FunctionCodeGen.TypeofLocals.cs b/src/Csharpc/CodeGen/FunctionCodeGen.TypeofLocals.cs index da5f8694..9f2d887c 100644 --- a/src/Csharpc/CodeGen/FunctionCodeGen.TypeofLocals.cs +++ b/src/Csharpc/CodeGen/FunctionCodeGen.TypeofLocals.cs @@ -107,4 +107,68 @@ private IReadOnlyList IlTypeofStoredIn(int local) } return _ilTypeofLocals.TryGetValue(local, out var known) ? known : []; } + + // ---- exact values: a local that holds `typeof(T)` wherever it is read ---- + // Unlike the flow-insensitive lists above (metadata: extra types are harmless), these feed lowerings that need the one + // type an argument is (Assembly.GetCustomAttributes(t), Enum.GetName(t, v), Marshal.SizeOf(t)): a local qualifies only + // when its single store is a typeof and nothing else can change it (`Type t = typeof(A); asm.GetCustomAttributes(t, false)`, + // as the Mono-derived WinForms' Control.ProductName does). + + /// T when is `typeof(T)`, in source or in IL, or a local that is exactly `typeof(T)`; null otherwise. + internal ITypeSymbol? ExactTypeOf(IOperation operation) + { + if (TypeOfOperand(operation) is { } known) return known; + while (operation is IConversionOperation { Operand: { } inner }) operation = inner; + return operation is ILocalReferenceOperation { Local: { IsConst: false, RefKind: RefKind.None } local } ? ExactTypeofLocal(local) : null; + } + + private readonly Dictionary _exactTypeofLocals = new(SymbolEqualityComparer.Default); + + /// + /// T when a source local is declared `= typeof(T)` and never written again: no assignment (deconstructions included), + /// no ref/out argument, no `ref` to it, anywhere in its member (lambdas and local functions too). + /// + private ITypeSymbol? ExactTypeofLocal(ILocalSymbol local) + { + if (_exactTypeofLocals.TryGetValue(local, out var cached)) return cached; + ITypeSymbol? result = null; + if (IsSystemType(local.Type) + && local.DeclaringSyntaxReferences is [var reference] && reference.GetSyntax() is VariableDeclaratorSyntax { Initializer: { } initializer } declarator + && _m.Compilation.ContainsSyntaxTree(declarator.SyntaxTree)) + { + var model = _m.Compilation.GetSemanticModel(declarator.SyntaxTree); + IOperation? value = model.GetOperation(initializer.Value); + while (value is IConversionOperation { Operand: { } inner }) value = inner; + SyntaxNode scope = declarator.Ancestors().FirstOrDefault(n => n is MemberDeclarationSyntax and not GlobalStatementSyntax) + ?? declarator.SyntaxTree.GetRoot(); + if (value is ITypeOfOperation typeOf && !scope.DescendantNodes().OfType().Any(id => + id.Identifier.ValueText == local.Name && IsWrite(id) && SymbolEqualityComparer.Default.Equals(model.GetSymbolInfo(id).Symbol, local))) + result = typeOf.TypeOperand; + } + return _exactTypeofLocals[local] = result; + + static bool IsWrite(IdentifierNameSyntax id) => + id.Ancestors().OfType().Any(a => a.Left.Span.Contains(id.Span)) + || id.Parent is ArgumentSyntax { RefKindKeyword.RawKind: (int)SyntaxKind.RefKeyword or (int)SyntaxKind.OutKeyword } + || id.Parent is RefExpressionSyntax; + } + + /// + /// T when IL local is exactly `typeof(T)` wherever it is read: its one store is + /// `ldtoken T; call Type.GetTypeFromHandle` and its address is never taken. + /// + private ITypeSymbol? IlExactTypeofLocal(int local) + { + if (IlTypeofStoredIn(local) is not [var type]) return null; + var stores = 0; + foreach (var instruction in IlBody.Instructions) + { + var op = instruction.OpCode; + int? index = op is ILOpCode.Stloc_0 or ILOpCode.Stloc_1 or ILOpCode.Stloc_2 or ILOpCode.Stloc_3 ? op - ILOpCode.Stloc_0 + : op is ILOpCode.Stloc_s or ILOpCode.Stloc or ILOpCode.Ldloca_s or ILOpCode.Ldloca ? (int)instruction.Int : null; + if (index != local) continue; + if (op is ILOpCode.Ldloca_s or ILOpCode.Ldloca || ++stores > 1) return null; + } + return type; + } } diff --git a/src/Csharpc/CodeGen/Intrinsics.cs b/src/Csharpc/CodeGen/Intrinsics.cs index 45087f1f..8c97ebbc 100644 --- a/src/Csharpc/CodeGen/Intrinsics.cs +++ b/src/Csharpc/CodeGen/Intrinsics.cs @@ -202,7 +202,7 @@ private static FrozenDictionary BuildMethods() { var self = g.EmitValue(inv.Instance!); Arg(g, inv, 1); // `inherit`: evaluated, no effect for assemblies - return FunctionCodeGen.TypeOfOperand(inv.Arguments.First(a => a.Parameter!.Ordinal == 0).Value) is INamedTypeSymbol attributeType + return g.ExactTypeOf(inv.Arguments.First(a => a.Parameter!.Ordinal == 0).Value) is INamedTypeSymbol attributeType ? g.AssemblyCustomAttributes((INamedTypeSymbol)g.Substitution.Apply(attributeType), self, inv) : throw CompileError.Unsupported("Assembly.GetCustomAttributes with a Type that is not typeof(an attribute)", inv); }; @@ -238,7 +238,7 @@ private static FrozenDictionary BuildMethods() }; t["System.Enum.GetName(System.Type, object)"] = (g, inv) => { - if (FunctionCodeGen.TypeOfOperand(inv.Arguments.First(a => a.Parameter!.Ordinal == 0).Value) is not INamedTypeSymbol { TypeKind: TypeKind.Enum } enumType) + if (g.ExactTypeOf(inv.Arguments.First(a => a.Parameter!.Ordinal == 0).Value) is not INamedTypeSymbol { TypeKind: TypeKind.Enum } enumType) throw CompileError.Unsupported("Enum.GetName with a non-constant Type", inv); var raw = UnboxEnum(inv.Arguments.First(a => a.Parameter!.Ordinal == 1).Value); var value = g.Coerce(g.EmitValue(raw), raw.Type, enumType.EnumUnderlyingType!); diff --git a/src/Csharpc/CodeGen/ModuleCodeGen.PInvoke.cs b/src/Csharpc/CodeGen/ModuleCodeGen.PInvoke.cs index 7af8f543..1f299a66 100644 --- a/src/Csharpc/CodeGen/ModuleCodeGen.PInvoke.cs +++ b/src/Csharpc/CodeGen/ModuleCodeGen.PInvoke.cs @@ -42,7 +42,7 @@ public sealed partial class ModuleCodeGen public static bool IsPInvoke(IMethodSymbol method) => method.OriginalDefinition.GetDllImportData() is not null; - private enum ParamKind { Direct, Bool, Char, String, Array, ByRef, Struct, StructByVal } + private enum ParamKind { Direct, Bool, Char, String, Array, ByRef, Struct, StructByVal, SafeHandle, Delegate } /// /// Native string encodings (csrt_pinvoke_string_to/from_native): Ansi is the system ANSI code page @@ -199,8 +199,17 @@ public LoweredFunction PInvokeStub(IMethodSymbol method) } // ---- marshal arguments ---- + // SafeHandles first, in parameter order, before anything is allocated or add-ref'ed: a null or closed handle throws + // .NET's exception (ArgumentNullException "pHandle", ObjectDisposedException) and nothing needs undoing. + for (var i = 0; i < parameters.Count; i++) + if (parameters[i].Kind == ParamKind.SafeHandle) + { + var check = SafeHandleMarshalling("Check"); + b.Call(check.Type, check.Fn, [stub.Param((uint)i)]); + } List args = []; List temps = []; + List addRefed = []; LLVMValueRef sretSlot = default; if (sret) { @@ -230,6 +239,26 @@ public LoweredFunction PInvokeStub(IMethodSymbol method) args.Add(nativeString); break; } + case ParamKind.SafeHandle: + { + // As .NET's marshaller: DangerousAddRef for the call, the handle's value, DangerousRelease after it. + var addRef = SafeHandleMarshalling("AddRef"); + args.Add(b.Call(addRef.Type, addRef.Fn, [value])); + addRefed.Add(value); + break; + } + case ParamKind.Delegate: + { + // One of the delegate type's reverse thunks, the pointer Marshal.GetFunctionPointerForDelegate hands out; null + // stays null. The argument keeps the delegate alive for the call, as .NET's marshaller does; a callback kept + // past the call is the caller's to keep alive, as in .NET. + var thunks = Compilation.GetTypeByMetadataName(CoreLib.Namespace + ".DelegateThunks")! + .GetMembers("GetPointerOrNull").OfType().Single(); + var getPointer = GetFunction(thunks); + var table = b.Cast(LLVMOpcode.PtrToInt, ReverseThunkTable((INamedTypeSymbol)p.Type, null!), Types.NativeInt); + args.Add(b.Cast(LLVMOpcode.IntToPtr, b.Call(getPointer.Type, getPointer.Fn, [value, table]), Llvm.Ptr)); + break; + } case ParamKind.Array: { // Blittable element arrays are passed by reference to element 0 (the GC never moves objects). @@ -315,6 +344,11 @@ public LoweredFunction PInvokeStub(IMethodSymbol method) var free = Runtime("csrt_pinvoke_free", Llvm.Void, Llvm.Ptr); b.Call(free.Type, free.Fn, [temp]); } + foreach (var handle in addRefed) + { + var release = SafeHandleMarshalling("Release"); + b.Call(release.Type, release.Fn, [handle]); + } if (msgSendKind >= 0) { // The exception ObjectiveCMarshal.SetMessageSendPendingException stored while the call ran is thrown here. @@ -435,8 +469,14 @@ private NativeParam ClassifyParameter(IParameterSymbol p, bool unicodeDefault) ? new NativeParam(ParamKind.Struct, type, eightbytes, StructType: llvmType) : new NativeParam(ParamKind.StructByVal, type, [Llvm.Ptr], StructType: llvmType); } + // A SafeHandle by value: its handle value, add-ref'ed for the call (returning one or passing it by ref stays unsupported). + case INamedTypeSymbol { TypeKind: TypeKind.Class } handleType when IsSafeHandle(handleType): + return new NativeParam(ParamKind.SafeHandle, type, [Types.NativeInt]); + // A delegate is passed as a native-callable pointer to it (ModuleCodeGen.ReverseThunks.cs). + case INamedTypeSymbol { TypeKind: TypeKind.Delegate } marshalled when CanMarshalDelegate(marshalled): + return new NativeParam(ParamKind.Delegate, type, [Llvm.Ptr]); case INamedTypeSymbol { TypeKind: TypeKind.Delegate }: - throw CompileError.Unsupported("delegate P/Invoke parameters (use [UnmanagedCallersOnly] + function pointers)", p); + throw CompileError.Unsupported("generic delegate P/Invoke parameters (use [UnmanagedCallersOnly] + function pointers)", p); default: if (type.IsReferenceType && type.SpecialType != SpecialType.None) throw CompileError.Unsupported($"P/Invoke parameter of type '{type}'", p); @@ -540,6 +580,16 @@ private bool IsByteOffsetStruct(INamedTypeSymbol s) => IsUserType(s) && (GetStructLayout(s).ByteOffset is not null || InstanceFields(s).Any(f => f.Type is INamedTypeSymbol { TypeKind: TypeKind.Struct } inner && !IsPrimitiveLike(inner) && IsByteOffsetStruct(inner))); + private static bool IsSafeHandle(INamedTypeSymbol type) + { + for (INamedTypeSymbol? t = type; t is not null; t = t.BaseType) + if (t is { Name: "SafeHandle", ContainingNamespace: { Name: "InteropServices", ContainingNamespace: { Name: "Runtime", ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true } } } }) return true; + return false; + } + + private LoweredFunction SafeHandleMarshalling(string name) => + GetFunction(Compilation.GetTypeByMetadataName(CoreLib.Namespace + ".SafeHandleMarshalling")!.GetMembers(name).OfType().Single()); + private bool IsBlittable(ITypeSymbol type) => type switch { IPointerTypeSymbol or IFunctionPointerTypeSymbol => true, diff --git a/src/Csharpc/CodeGen/ModuleCodeGen.Reflection.cs b/src/Csharpc/CodeGen/ModuleCodeGen.Reflection.cs index 2d477234..5ab63ff1 100644 --- a/src/Csharpc/CodeGen/ModuleCodeGen.Reflection.cs +++ b/src/Csharpc/CodeGen/ModuleCodeGen.Reflection.cs @@ -283,6 +283,11 @@ internal void NoteDynamicallyAccessedArguments(IMethodSymbol method, Func g.EmitReverseThunk(type, shape, table, slot, syntax)); - AddNativeAbiAttributes(thunk, shape); - thunks.Add(thunk); + if (abi is null) + { + AddNativeAbiAttributes(thunk, shape); + thunks.Add(thunk); + } + else thunks.Add(CAbiAdapter(abi, invoke, thunk, fnType, $"{name}.cabi{i}")); } var zeros = Enumerable.Repeat(LlvmContext.Null(entry), ReverseThunkSlots).ToArray(); Native.LLVMSetInitializer(table, Llvm.ConstStruct(Llvm.ConstInt(Types.NativeInt, ReverseThunkSlots), @@ -68,6 +75,7 @@ internal LLVMValueRef NativeInvokeThunk(INamedTypeSymbol type, IOperation at) if (_nativeInvokeThunks.TryGetValue(type, out var existing)) return existing; var invoke = type.DelegateInvokeMethod!; var shape = MarshalledSignature(invoke, type, at); + if (HasStructByValue(invoke)) return _nativeInvokeThunks[type] = StructNativeInvokeThunk(type, invoke); // The managed side calls delegates as fn(target, managed args...): the managed parameter types, not the C ones. List managed = [Llvm.Ptr]; foreach (var p in invoke.Parameters) managed.Add(p.RefKind == RefKind.None ? Types.Value(p.Type) : Llvm.Ptr); @@ -101,7 +109,7 @@ private MarshalledShape MarshalledSignature(IMethodSymbol invoke, INamedTypeSymb } else { - if (!IsBlittable(p.Type) || p.Type is INamedTypeSymbol { TypeKind: TypeKind.Struct } ps && !IsPrimitiveLike(ps)) + if (!IsBlittable(p.Type)) throw CompileError.Unsupported($"delegate '{type}' marshalled to native code: parameter '{p.Name}' of type '{p.Type}'", at); native.Add(Types.Value(p.Type)); bools.Add(false); @@ -114,13 +122,103 @@ private MarshalledShape MarshalledSignature(IMethodSymbol invoke, INamedTypeSymb else if (invoke.ReturnType.SpecialType == SpecialType.System_Boolean) { ret = Llvm.I32; boolReturn = true; } else { - if (!IsBlittable(invoke.ReturnType) || invoke.ReturnType is INamedTypeSymbol { TypeKind: TypeKind.Struct } rs && !IsPrimitiveLike(rs)) + if (!IsBlittable(invoke.ReturnType)) throw CompileError.Unsupported($"delegate '{type}' marshalled to native code: return type '{invoke.ReturnType}'", at); ret = Types.Value(invoke.ReturnType); } return new MarshalledShape([.. native], ret, [.. bools], boolReturn, invoke); } + private static bool HasStructByValue(IMethodSymbol invoke) => + IsStructByValue(invoke.ReturnType) || invoke.Parameters.Any(p => p.RefKind == RefKind.None && IsStructByValue(p.Type)); + + /// + /// The native-ABI function in front of a slot's thunk whose signature has a struct by value: it rebuilds the structs from + /// their registers (or byval copies), calls the thunk with them, and returns the result the C way (registers or sret), + /// as an [UnmanagedCallersOnly] method's entry thunk does. BOOLs stay 4-byte ints, which the slot's thunk takes. + /// + private LLVMValueRef CAbiAdapter(NativeShape abi, IMethodSymbol invoke, LLVMValueRef inner, LLVMTypeRef innerType, string name) + { + var adapter = Module.AddFunction(name, NativeFunctionType(abi)); + Native.LLVMSetLinkage(adapter, LLVMLinkage.Internal); + foreach (var (index, attribute) in NativeAttributes(abi, invoke)) Native.LLVMAddAttributeAtIndex(adapter, index, attribute); + using var b = new IrBuilder(Llvm); + b.PositionAtEnd(b.AppendBlock(adapter, "entry")); + var next = abi.Sret ? 1u : 0u; + List args = []; + foreach (var p in abi.Parameters) + { + switch (p.Kind) + { + case ParamKind.Direct or ParamKind.ByRef or ParamKind.Bool: + args.Add(adapter.Param(next)); + break; + case ParamKind.Struct: + { + var coerced = CoercedStruct(p.NativeTypes); + var slot = b.Alloca(LargerOf(p.StructType, coerced), "abi"); + for (var k = 0; k < p.NativeTypes.Length; k++) b.Store(adapter.Param(next + (uint)k), b.StructGep(coerced, slot, (uint)k)); + args.Add(b.Load(p.StructType, slot)); + break; + } + case ParamKind.StructByVal: + args.Add(b.Load(p.StructType, adapter.Param(next))); + break; + default: + throw CompileError.Unsupported($"'{p.Type}' in the signature of a delegate marshalled to native code", invoke); + } + next += (uint)p.NativeTypes.Length; + } + var result = b.Call(innerType, inner, [.. args]); + switch (abi.ReturnKind) + { + case ParamKind.Direct when invoke.ReturnsVoid: + b.RetVoid(); + break; + case ParamKind.Direct or ParamKind.Bool: + b.Ret(result); + break; + case ParamKind.Struct: + { + var slot = b.Alloca(LargerOf(abi.ReturnStruct, abi.NativeReturn), "ret"); + b.Store(result, slot); + b.Ret(b.Load(abi.NativeReturn, slot)); + break; + } + case ParamKind.StructByVal: + b.Store(result, adapter.Param(0)); + b.RetVoid(); + break; + default: + throw CompileError.Unsupported($"'{invoke.ReturnType}' returned by a delegate marshalled to native code", invoke); + } + return adapter; + } + + /// + /// `R thunk(ptr box, managed args...)` of a delegate wrapping a native function pointer whose signature has a struct by + /// value: the unmanaged function pointer call stub (NativeCallStub) does the C ABI. + /// + private LLVMValueRef StructNativeInvokeThunk(INamedTypeSymbol type, IMethodSymbol invoke) + { + var stub = NativeCallStub(invoke) ?? throw new InvalidOperationException("a struct signature always has a call stub"); + List managed = [Llvm.Ptr]; + foreach (var p in invoke.Parameters) managed.Add(p.RefKind == RefKind.None ? Types.Value(p.Type) : Llvm.Ptr); + var fnType = Llvm.FunctionType(invoke.ReturnsVoid ? Llvm.Void : Types.Value(invoke.ReturnType), [.. managed]); + var thunk = Module.AddFunction("csharpc.nativeinvoke." + Mangler.MetadataName(type), fnType); + Native.LLVMSetLinkage(thunk, LLVMLinkage.Internal); + using var b = new IrBuilder(Llvm); + b.PositionAtEnd(b.AppendBlock(thunk, "entry")); + // The box holds the native pointer after its method-table word (see EmitNativeInvokeThunk). + var native = b.Load(Llvm.Ptr, b.InBoundsGep(Llvm.I8, thunk.Param(0), [Llvm.ConstInt(Llvm.I64, 8)]), "native"); + List args = [native]; + for (var i = 0; i < invoke.Parameters.Length; i++) args.Add(thunk.Param((uint)i + 1)); + var result = b.Call(stub.Type, stub.Fn, [.. args]); + if (invoke.ReturnsVoid) b.RetVoid(); + else b.Ret(result); + return thunk; + } + /// Sub-int arguments and results are extended by the caller (zeroext/signext), as clang declares them. private void AddNativeAbiAttributes(LLVMValueRef fn, MarshalledShape shape) { diff --git a/src/Csharpc/corelib/DelegateThunks.cs b/src/Csharpc/corelib/DelegateThunks.cs index b9e7377d..4c9d7984 100644 --- a/src/Csharpc/corelib/DelegateThunks.cs +++ b/src/Csharpc/corelib/DelegateThunks.cs @@ -61,6 +61,9 @@ public static IntPtr GetPointer(Delegate d, IntPtr table) + " (Marshal.GetFunctionPointerForDelegate), and a collected delegate frees its thunk."); } + /// A delegate passed to a P/Invoke: its thunk, or null for null (ModuleCodeGen.PInvoke.cs). + public static IntPtr GetPointerOrNull(Delegate d, IntPtr table) => d == null ? IntPtr.Zero : GetPointer(d, table); + public static IntPtr GetPointerUntyped(Delegate d) { if (d == null) throw new ArgumentNullException("d"); diff --git a/src/Csharpc/corelib/Net/Uri.cs b/src/Csharpc/corelib/Net/Uri.cs index 509eae37..7914e3d0 100644 --- a/src/Csharpc/corelib/Net/Uri.cs +++ b/src/Csharpc/corelib/Net/Uri.cs @@ -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"); } /// @@ -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; } @@ -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. 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/src/Csharpc/corelib/SafeHandles.cs b/src/Csharpc/corelib/SafeHandles.cs index b32dfedf..8ba37705 100644 --- a/src/Csharpc/corelib/SafeHandles.cs +++ b/src/Csharpc/corelib/SafeHandles.cs @@ -247,4 +247,24 @@ public void Dispose() _pointer = null; } } + + /// SafeHandle P/Invoke parameters (ModuleCodeGen.PInvoke.cs), as .NET's marshaller passes them. + internal static class SafeHandleMarshalling + { + /// Every SafeHandle argument, before the call is marshalled: .NET's exceptions for null and closed handles. + public static void Check(System.Runtime.InteropServices.SafeHandle handle) + { + if (handle == null) throw new ArgumentNullException("pHandle", "SafeHandle cannot be null."); + if (handle.IsClosed) throw new ObjectDisposedException(handle.GetType().FullName); + } + + public static IntPtr AddRef(System.Runtime.InteropServices.SafeHandle handle) + { + bool success = false; + handle.DangerousAddRef(ref success); + return handle.DangerousGetHandle(); + } + + public static void Release(System.Runtime.InteropServices.SafeHandle handle) => handle.DangerousRelease(); + } } diff --git a/tests/platform-skips.txt b/tests/platform-skips.txt index ca65f658..2ed1abb2 100644 --- a/tests/platform-skips.txt +++ b/tests/platform-skips.txt @@ -40,6 +40,8 @@ windows 729_dllimport_resolver live: .NET names the library kind "DLL" windows 731_process_start runs a POSIX sh; csharpc's Process.Start on Windows is an explicit NotSupportedException (not implemented yet) windows 860_console_autoflush_pipe starts itself with Process.Start, an explicit NotSupportedException on Windows in csharpc (not implemented yet); SIGPIPE is POSIX windows 286_pinvoke_portable_abi live: imports from "libc", which doesn't exist on Windows +windows 1348_pinvoke_safehandle_parameters live: imports from "libc", which doesn't exist on Windows +windows 1347_pinvoke_delegate_parameters live: imports from "libc", which doesn't exist on Windows windows 295_regex_charclass live: prints matched text that contains a bare "\n" (from the input string) windows 303_regex_options live: prints matched text that contains a bare "\n" (from the input string) windows 194_marshal_strings live: GetPInvokeErrorMessage is the Win32 FormatMessage text, not strerror @@ -111,6 +113,7 @@ wasi 84_misc_bcl prints IntPtr.Size: 4 on wasm32 wasi 160_pinvoke_dllimport Linux LP64 signatures (C long as C# long; 32-bit on wasm32) and a libc symbol that doesn't exist (a link error with wasi-libc) wasi 176_pinvoke_struct_abi Linux LP64 signatures: ldiv takes C long, 32-bit on wasm32 wasi 286_pinvoke_portable_abi Linux LP64 signatures: ldiv takes C long, 32-bit on wasm32 +wasi 1348_pinvoke_safehandle_parameters opens /dev/null, which the WASI sandbox (no preopened /dev) does not have wasi 162_pinvoke_libraryimport prints an errno value (ENOENT is 2 on Linux, 44 in WASI) wasi 729_dllimport_resolver loads a shared library with NativeLibrary.Load: WASI has no dynamic libraries wasi 730_pinvoke_static_constructor loads a shared library with NativeLibrary.Load: WASI has no dynamic libraries diff --git a/tests/samples/1340_marshal_sizeof_fixed_buffer.cs b/tests/samples/1340_marshal_sizeof_fixed_buffer.cs new file mode 100644 index 00000000..d8e52928 --- /dev/null +++ b/tests/samples/1340_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/1340_marshal_sizeof_fixed_buffer.expected b/tests/samples/1340_marshal_sizeof_fixed_buffer.expected new file mode 100644 index 00000000..10eec986 --- /dev/null +++ b/tests/samples/1340_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 diff --git a/tests/samples/1342_reflection_typeof_local_exact.cs b/tests/samples/1342_reflection_typeof_local_exact.cs new file mode 100644 index 00000000..ed040455 --- /dev/null +++ b/tests/samples/1342_reflection_typeof_local_exact.cs @@ -0,0 +1,50 @@ +// A Type local that holds typeof(T) wherever it is read stands for T in the calls lowered per type: +// Assembly.GetCustomAttributes(t, inherit), Enum.GetName(t, value), Marshal.SizeOf(t), RuntimeHelpers.GetUninitializedObject(t) +// (`Type t = typeof(AssemblyProductAttribute); assembly.GetCustomAttributes(t, false)`, as WinForms' Control.ProductName does). +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: Tag("first")] +[assembly: Tag("second")] + +[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] +sealed class TagAttribute(string name) : Attribute { public string Name { get; } = name; } + +enum Color { Red, Green, Blue } + +[StructLayout(LayoutKind.Sequential)] +struct Pair { public int A; public long B; } + +sealed class Widget { public int Count = 42; public override string ToString() => "Widget " + Count; } + +static class Program +{ + static string Tags() + { + Type t = typeof(TagAttribute); + Assembly assembly = typeof(Program).Module.Assembly; + object[] attrs = assembly.GetCustomAttributes(t, false); + var names = new string[attrs.Length]; + for (int i = 0; i < attrs.Length; i++) names[i] = ((TagAttribute)attrs[i]).Name; + Array.Sort(names, StringComparer.Ordinal); + return attrs.Length + ": " + string.Join(", ", names); + } + + static void Main() + { + Console.WriteLine(Tags()); + + var colors = typeof(Color); + Console.WriteLine(Enum.GetName(colors, 2)); + Console.WriteLine(Enum.GetName(colors, 7) ?? "(none)"); + + Type pair = typeof(Pair); + Console.WriteLine(Marshal.SizeOf(pair)); + + Type widget = typeof(Widget); + var raw = (Widget)RuntimeHelpers.GetUninitializedObject(widget); + Console.WriteLine(raw.Count); + } +} diff --git a/tests/samples/1342_reflection_typeof_local_exact.expected b/tests/samples/1342_reflection_typeof_local_exact.expected new file mode 100644 index 00000000..12d76593 --- /dev/null +++ b/tests/samples/1342_reflection_typeof_local_exact.expected @@ -0,0 +1,5 @@ +2: first, second +Blue +(none) +16 +0 diff --git a/tests/samples/1343_reflection_dam_property_setter.cs b/tests/samples/1343_reflection_dam_property_setter.cs new file mode 100644 index 00000000..1748a380 --- /dev/null +++ b/tests/samples/1343_reflection_dam_property_setter.cs @@ -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); + } +} diff --git a/tests/samples/1343_reflection_dam_property_setter.expected b/tests/samples/1343_reflection_dam_property_setter.expected new file mode 100644 index 00000000..31bc43d3 --- /dev/null +++ b/tests/samples/1343_reflection_dam_property_setter.expected @@ -0,0 +1,4 @@ +mail +calendar +TaskBox() +tasks diff --git a/tests/samples/1344_uri_paths_with_spaces.cs b/tests/samples/1344_uri_paths_with_spaces.cs new file mode 100644 index 00000000..7097a3fc --- /dev/null +++ b/tests/samples/1344_uri_paths_with_spaces.cs @@ -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, "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/1344_uri_paths_with_spaces.expected b/tests/samples/1344_uri_paths_with_spaces.expected new file mode 100644 index 00000000..9781fd1a --- /dev/null +++ b/tests/samples/1344_uri_paths_with_spaces.expected @@ -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 hi +True diff --git a/tests/samples/1347_pinvoke_delegate_parameters.cs b/tests/samples/1347_pinvoke_delegate_parameters.cs new file mode 100644 index 00000000..9cac847b --- /dev/null +++ b/tests/samples/1347_pinvoke_delegate_parameters.cs @@ -0,0 +1,52 @@ +#:property AllowUnsafeBlocks=true +// Delegates passed to P/Invokes: libc's qsort and bsearch call back into managed code through the pointer the marshaller +// makes for the delegate (a lambda, a method group, a stored delegate, a closure), during the call. +using System; +using System.Runtime.InteropServices; + +unsafe +{ + int[] values = { 5, -3, 9, 0, 2, 7 }; + fixed (int* p = values) Native.qsort(p, (nuint)values.Length, sizeof(int), (a, b) => (*(int*)a).CompareTo(*(int*)b)); + Console.WriteLine(string.Join(",", values)); + + Native.Compare descending = (a, b) => (*(int*)b).CompareTo(*(int*)a); + fixed (int* p = values) Native.qsort(p, (nuint)values.Length, sizeof(int), descending); + Console.WriteLine(string.Join(",", values)); + + fixed (int* p = values) Native.qsort(p, (nuint)values.Length, sizeof(int), Ordering.ByAbsoluteValue); + Console.WriteLine(string.Join(",", values)); + + // A closure: the order comes from captured state. + string[] words = { "pear", "fig", "apple", "kiwi", "banana", "cherry" }; + var indexes = new int[] { 0, 1, 2, 3, 4, 5 }; + fixed (int* p = indexes) Native.qsort(p, (nuint)indexes.Length, sizeof(int), (a, b) => string.CompareOrdinal(words[*(int*)a], words[*(int*)b])); + Console.WriteLine(string.Join(",", Array.ConvertAll(indexes, i => words[i]))); + + int[] sorted = { -4, -1, 0, 3, 8, 21 }; + fixed (int* p = sorted) + { + int key = 8, missing = 5; + var found = (int*)Native.bsearch(&key, p, (nuint)sorted.Length, sizeof(int), Ordering.Ascending); + var notFound = Native.bsearch(&missing, p, (nuint)sorted.Length, sizeof(int), Ordering.Ascending); + Console.WriteLine($"bsearch 8 at {found - p}, 5 {(notFound == null ? "not found" : "found")}"); + } +} + +static unsafe class Ordering +{ + public static int Ascending(void* a, void* b) => (*(int*)a).CompareTo(*(int*)b); + public static int ByAbsoluteValue(void* a, void* b) + { + int x = *(int*)a, y = *(int*)b; + int byAbs = Math.Abs(x).CompareTo(Math.Abs(y)); + return byAbs != 0 ? byAbs : x.CompareTo(y); + } +} + +static unsafe class Native +{ + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int Compare(void* a, void* b); + [DllImport("libc")] public static extern void qsort(void* items, nuint count, nuint size, Compare compare); + [DllImport("libc")] public static extern void* bsearch(void* key, void* items, nuint count, nuint size, Compare compare); +} diff --git a/tests/samples/1347_pinvoke_delegate_parameters.expected b/tests/samples/1347_pinvoke_delegate_parameters.expected new file mode 100644 index 00000000..33a8cbf0 --- /dev/null +++ b/tests/samples/1347_pinvoke_delegate_parameters.expected @@ -0,0 +1,5 @@ +-3,0,2,5,7,9 +9,7,5,2,0,-3 +0,2,-3,5,7,9 +apple,banana,cherry,fig,kiwi,pear +bsearch 8 at 4, 5 not found diff --git a/tests/samples/1348_pinvoke_safehandle_parameters.cs b/tests/samples/1348_pinvoke_safehandle_parameters.cs new file mode 100644 index 00000000..d39ddb6f --- /dev/null +++ b/tests/samples/1348_pinvoke_safehandle_parameters.cs @@ -0,0 +1,54 @@ +#:property AllowUnsafeBlocks=true +// SafeHandle arguments of P/Invokes, as .NET's marshaller passes them: the handle's value, add-ref'ed for the call and +// released after it; a null handle is an ArgumentNullException ("pHandle") and a closed one an ObjectDisposedException, +// thrown before the call, and a handle that already got through is not left add-ref'ed. +using System; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +unsafe +{ + var handle = new FdHandle(Native.open("/dev/null", 0)); + Console.WriteLine($"invalid {handle.IsInvalid} closed {handle.IsClosed}"); + byte b; + Console.WriteLine($"read {Native.read(handle, &b, 1)} lseek {Native.lseek(handle, 0, 1)}"); + + // The calls released what they add-ref'ed: the handle is still open and takes another reference. + bool added = false; + handle.DangerousAddRef(ref added); + handle.DangerousRelease(); + Console.WriteLine($"add-ref after calls {added}"); + + try { Native.read(null!, &b, 1); } catch (Exception e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); } + + handle.Dispose(); + Console.WriteLine($"closed {handle.IsClosed} released {FdHandle.Released}"); + try { Native.read(handle, &b, 1); } catch (Exception e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); } + + var first = new FdHandle(Native.open("/dev/null", 0)); + try { Native.lseek2(first, null!); } catch (Exception e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); } + first.Dispose(); + Console.WriteLine($"first closed {first.IsClosed} released {FdHandle.Released}"); + + var missing = new FdHandle(Native.open("/nonexistent/csharpc", 0)); + Console.WriteLine($"missing invalid {missing.IsInvalid}"); + missing.Dispose(); + Console.WriteLine($"released {FdHandle.Released}"); +} + +sealed class FdHandle : SafeHandleMinusOneIsInvalid +{ + public static int Released; + public FdHandle(int fd) : base(true) { SetHandle(fd); } + protected override bool ReleaseHandle() { Released++; return Native.close((int)handle) == 0; } +} + +static unsafe class Native +{ + [DllImport("libc")] public static extern int open([MarshalAs(UnmanagedType.LPUTF8Str)] string path, int flags); + [DllImport("libc")] public static extern nint read(FdHandle fd, byte* buffer, nuint count); + [DllImport("libc")] public static extern long lseek(FdHandle fd, long offset, int whence); + // lseek's signature with two handles, only to show the second one's null check after the first got through. + [DllImport("libc", EntryPoint = "lseek")] public static extern long lseek2(FdHandle fd, FdHandle other); + [DllImport("libc")] public static extern int close(int fd); +} diff --git a/tests/samples/1348_pinvoke_safehandle_parameters.expected b/tests/samples/1348_pinvoke_safehandle_parameters.expected new file mode 100644 index 00000000..b91340de --- /dev/null +++ b/tests/samples/1348_pinvoke_safehandle_parameters.expected @@ -0,0 +1,11 @@ +invalid False closed False +read 0 lseek 0 +add-ref after calls True +ArgumentNullException: SafeHandle cannot be null. (Parameter 'pHandle') +closed True released 1 +ObjectDisposedException: Cannot access a disposed object. +Object name: 'FdHandle'. +ArgumentNullException: SafeHandle cannot be null. (Parameter 'pHandle') +first closed True released 2 +missing invalid True +released 2 diff --git a/tests/samples/1349_delegate_thunk_structs.cs b/tests/samples/1349_delegate_thunk_structs.cs new file mode 100644 index 00000000..63830fb1 --- /dev/null +++ b/tests/samples/1349_delegate_thunk_structs.cs @@ -0,0 +1,73 @@ +#:property AllowUnsafeBlocks=true +// Structs by value in delegates marshalled to native code: Marshal.GetFunctionPointerForDelegate's pointer takes and returns +// them with the platform's C ABI (two and four doubles, two floats, one pointer-sized integer, an int and a double mixed, +// a 24-byte struct of ints that goes through memory, three bytes), and so does a delegate made with +// GetDelegateForFunctionPointer over an [UnmanagedCallersOnly] method; BOOLs mixed in stay 4-byte ints. +using System; +using System.Globalization; +using System.Runtime.InteropServices; + +unsafe +{ + var inv = CultureInfo.InvariantCulture; + + var mid = (delegate* unmanaged)Marshal.GetFunctionPointerForDelegate(new Mid((a, b) => new Point { X = (a.X + b.X) / 2, Y = (a.Y + b.Y) / 2 })); + var m = mid(new Point { X = 1, Y = 2 }, new Point { X = 3, Y = 6 }); + Console.WriteLine($"mid {m.X.ToString(inv)} {m.Y.ToString(inv)}"); + + var grow = (delegate* unmanaged)Marshal.GetFunctionPointerForDelegate(new Grow((r, by) => new Rect { X = r.X - by, Y = r.Y - by, W = r.W + 2 * by, H = r.H + 2 * by })); + var g = grow(new Rect { X = 10, Y = 20, W = 30, H = 40 }, 5); + Console.WriteLine($"grow {g.X.ToString(inv)} {g.Y.ToString(inv)} {g.W.ToString(inv)} {g.H.ToString(inv)}"); + + var next = (delegate* unmanaged)Marshal.GetFunctionPointerForDelegate(new Next(h => new Handle { Value = h.Value + 1 })); + Console.WriteLine($"next {next(new Handle { Value = 41 }).Value}"); + + var swap = (delegate* unmanaged)Marshal.GetFunctionPointerForDelegate(new Swap(p => new Pair { A = p.B, B = p.A })); + var s = swap(new Pair { A = 1.5f, B = -2.5f }); + Console.WriteLine($"swap {s.A.ToString(inv)} {s.B.ToString(inv)}"); + + var scale = (delegate* unmanaged)Marshal.GetFunctionPointerForDelegate(new Scale((x, by, check) => new Mixed { Count = x.Count * by, Weight = check != 0 ? x.Weight * by : -1 })); + var x = scale(new Mixed { Count = 7, Weight = 0.5 }, 3, 1); + Console.WriteLine($"scale {x.Count} {x.Weight.ToString(inv)}"); + + var sum = (delegate* unmanaged)Marshal.GetFunctionPointerForDelegate(new Sum(t => t.A + t.B + t.C + t.D + t.E + t.F)); + Console.WriteLine($"sum {sum(new Triple { A = 1, B = 2, C = 3, D = 4, E = 5, F = 6 })}"); + + var shift = (delegate* unmanaged)Marshal.GetFunctionPointerForDelegate(new Shift(c => new Rgb { R = c.G, G = c.B, B = c.R })); + var c = shift(new Rgb { R = 1, G = 2, B = 3 }); + Console.WriteLine($"shift {c.R} {c.G} {c.B}"); + + var inside = (delegate* unmanaged)Marshal.GetFunctionPointerForDelegate(new Inside((p, r) => p.X >= r.X && p.X < r.X + r.W && p.Y >= r.Y && p.Y < r.Y + r.H)); + Console.WriteLine($"inside {inside(new Point { X = 15, Y = 25 }, g)} {inside(new Point { X = 0, Y = 0 }, g)}"); + + // The other direction: a delegate over a native function pointer. + var wrapped = Marshal.GetDelegateForFunctionPointer((IntPtr)(delegate* unmanaged)&Native.Shrink); + var w = wrapped(new Rect { X = 0, Y = 0, W = 10, H = 8 }, 1); + Console.WriteLine($"wrapped {w.X.ToString(inv)} {w.Y.ToString(inv)} {w.W.ToString(inv)} {w.H.ToString(inv)}"); + var midAgain = Marshal.GetDelegateForFunctionPointer((IntPtr)(delegate* unmanaged)&Native.Sum2); + var ma = midAgain(new Point { X = 1, Y = 2 }, new Point { X = 10, Y = 20 }); + Console.WriteLine($"midAgain {ma.X.ToString(inv)} {ma.Y.ToString(inv)}"); +} + +struct Point { public double X, Y; } +struct Rect { public double X, Y, W, H; } +struct Handle { public nint Value; } +struct Pair { public float A, B; } +struct Mixed { public int Count; public double Weight; } +struct Triple { public int A, B, C, D, E, F; } +struct Rgb { public byte R, G, B; } + +delegate Point Mid(Point a, Point b); +delegate Rect Grow(Rect r, double by); +delegate Handle Next(Handle h); +delegate Pair Swap(Pair p); +delegate Mixed Scale(Mixed x, int by, int check); +delegate int Sum(Triple t); +delegate Rgb Shift(Rgb c); +delegate bool Inside(Point p, Rect r); + +static class Native +{ + [UnmanagedCallersOnly] public static Rect Shrink(Rect r, double by) => new Rect { X = r.X + by, Y = r.Y + by, W = r.W - 2 * by, H = r.H - 2 * by }; + [UnmanagedCallersOnly] public static Point Sum2(Point a, Point b) => new Point { X = a.X + b.X, Y = a.Y + b.Y }; +} diff --git a/tests/samples/1349_delegate_thunk_structs.expected b/tests/samples/1349_delegate_thunk_structs.expected new file mode 100644 index 00000000..31b441d8 --- /dev/null +++ b/tests/samples/1349_delegate_thunk_structs.expected @@ -0,0 +1,10 @@ +mid 2 4 +grow 5 15 40 50 +next 42 +swap -2.5 1.5 +scale 21 1.5 +sum 21 +shift 2 3 1 +inside 1 0 +wrapped 1 1 8 6 +midAgain 11 22