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.Calls.cs b/src/Csharpc/CodeGen/FunctionCodeGen.Calls.cs index 2f893d55..a09c332b 100644 --- a/src/Csharpc/CodeGen/FunctionCodeGen.Calls.cs +++ b/src/Csharpc/CodeGen/FunctionCodeGen.Calls.cs @@ -1089,7 +1089,7 @@ private LLVMValueRef EmitPropertyGet(IPropertyReferenceOperation p) return EmitInterfaceCall(property.GetMethod!, p.Instance!, p.Arguments, [], null); if (_m.IsUserType(property.ContainingType)) { - var getter = property.GetMethod ?? throw CompileError.Unsupported($"reading set-only property '{property.Name}'", p); + var getter = GetterOf(property) ?? throw CompileError.Unsupported($"reading set-only property '{property.Name}'", p); var self = property.IsStatic ? default : Receiver(p.Instance!, getter); return CallAccessor(p, getter, self, []); } @@ -1124,6 +1124,12 @@ private LLVMValueRef EmitPropertySet(IPropertyReferenceOperation p, Func type.ContainingAssembly is { } asm && Frontend.FrameworkIl.NotCompiledFromIl.TryGetValue(asm.Name, out var why) ? $" ({asm.Name} is not compiled from IL: {why})" : ""; + /// + /// The getter a read of calls: its own, or, for an override that only overrides the setter + /// (AnonymousPipeClientStream.ReadMode), the nearest overridden property's, called virtually as C# binds it. + /// + internal static IMethodSymbol? GetterOf(IPropertySymbol property) + { + for (var p = property; p is not null; p = p.OverriddenProperty) + if (p.GetMethod is { } getter) return getter; + return null; + } + + /// The setter a write of calls: its own, or the nearest overridden property's. + internal static IMethodSymbol? SetterOf(IPropertySymbol property) + { + for (var p = property; p is not null; p = p.OverriddenProperty) + if (p.SetMethod is { } setter) return setter; + return null; + } + /// /// `Dispose()` on the stack enumerator of a foreach over an array, also through implicit conversions (the finally's /// `((IDisposable)e).Dispose()` when the array is cast in the foreach header, #516): it does nothing. Shared with the finally diff --git a/src/Csharpc/CodeGen/FunctionCodeGen.CoreLib.cs b/src/Csharpc/CodeGen/FunctionCodeGen.CoreLib.cs index b1ebd712..9062e492 100644 --- a/src/Csharpc/CodeGen/FunctionCodeGen.CoreLib.cs +++ b/src/Csharpc/CodeGen/FunctionCodeGen.CoreLib.cs @@ -67,13 +67,15 @@ private LLVMValueRef CallAccessorDirect(IMethodSymbol accessor, LLVMValueRef[] a private LLVMValueRef GetCapturedProperty(PropertyCapture pc) { - var getter = pc.Property.GetMethod ?? throw CompileError.Unsupported($"reading set-only property '{pc.Property.Name}'", pc.Property); + var getter = GetterOf(pc.Property) ?? throw CompileError.Unsupported($"reading set-only property '{pc.Property.Name}'", pc.Property); return CallAccessorDirect(getter, CapturedAccessorArgs(pc, getter, [])); } private LLVMValueRef SetCapturedProperty(PropertyCapture pc, LLVMValueRef value) { - if (pc.Property.SetMethod is not { } setter) + // A getter-only override writes through the nearest overridden property's setter (as SetProperty does). + var setter = pc.Property.SetMethod ?? (pc.Property.IsOverride ? SetterOf(pc.Property) : null); + if (setter is null) { // Get-only auto-property assigned in a constructor: write its backing field. var field = BackingField(pc.Property); @@ -170,6 +172,8 @@ private LLVMValueRef EmitCoreIntrinsic(IMethodSymbol target, IInvocationOperatio "TryFaultAsyncTask" => CallRuntime("csrt_task_try_fault_async", L.I1, [L.Ptr, L.Ptr], args[0], args[1]), "CompareStringsWith" => CallRuntime("csrt_string_compare_with", L.I32, [L.Ptr, L.Ptr, L.I32], args[0], args[1], args[2]), "ResourceObjectHook" => ProgramHook("ResourceObject", target, args), + "ResourceObjectFromBytesHook" => ProgramHook("ResourceObjectFromBytes", target, args), + "ResourceObjectFromStreamHook" => ProgramHook("ResourceObjectFromStream", target, args), "HasConverterResources" => _m.HasConverterResources() ? L.True : L.False, "HasNonStringResources" => _m.HasNonStringResources() ? L.True : L.False, "NestedTypeTable" => _b.Call(_m.NestedTypesFunction().Type, _m.NestedTypesFunction().Fn, [args[0], args[1]]), 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.Exceptions.cs b/src/Csharpc/CodeGen/FunctionCodeGen.Exceptions.cs index 9993bd33..c291eaf3 100644 --- a/src/Csharpc/CodeGen/FunctionCodeGen.Exceptions.cs +++ b/src/Csharpc/CodeGen/FunctionCodeGen.Exceptions.cs @@ -459,12 +459,21 @@ private void EmitExceptionConstructor(IMethodSymbol constructor, LLVMValueRef ex } var value = EmitValue(argument.Value); var uriFormat = Mangler.MetadataName(constructor.ContainingType) == "System.UriFormatException"; + // The inner exception is the parameter typed System.Exception, whatever its name: "innerException" in most of the + // framework, "inner" in MissingMemberException, MissingMethodException, RegexMatchTimeoutException and others, "e" in + // UriFormatException and the SqlTypes exceptions. Matching only one name dropped the others' inner exception silently. + if (argument.Parameter?.Type is INamedTypeSymbol { Name: "Exception", ContainingNamespace: { Name: "System", ContainingNamespace.IsGlobalNamespace: true } }) + { + inner = value; + continue; + } switch (argument.Parameter?.Name) { case "message": message = value; break; case "textString" when uriFormat: message = value; break; // UriFormatException(string textString, Exception e) - case "e" when uriFormat: inner = value; break; - case "innerException": inner = value; break; + case "fullTypeName" when Mangler.MetadataName(constructor.ContainingType) == "System.TypeInitializationException": + message = CallCoreLib("ExceptionData", "TypeInitializerMessage", value); // its message names the type + break; case "paramName" or "parameterName": paramName = value; break; // parameterName: DuplicateWaitObjectException case "fileName": paramName = value; break; // FileNotFoundException.FileName (csrt keeps it in param_name) case "directoryPath": paramName = value; break; // DirectoryNotFoundException.DirectoryPath (.NET 11), likewise diff --git a/src/Csharpc/CodeGen/FunctionCodeGen.Expressions.cs b/src/Csharpc/CodeGen/FunctionCodeGen.Expressions.cs index 26dfe359..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 @@ -273,17 +285,21 @@ private LLVMValueRef ReadModifyWrite(IOperation target, Func(ReferenceEqualityComparer.Instance); - foreach (var argument in p.Arguments) _argumentCache[argument] = EmitArgument(argument, property.GetMethod!); + foreach (var argument in p.Arguments) _argumentCache[argument] = EmitArgument(argument, getter); } - var old = CallAccessor(p, property.GetMethod!, self, []); + var old = CallAccessor(p, getter, self, []); var (newValue, result) = modify(old); - CallAccessor(p, property.SetMethod ?? throw CompileError.Unsupported("compound assignment to a get-only property", p), self, [newValue]); + CallAccessor(p, setter, self, [newValue]); _argumentCache = savedArgs; return result; } 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.Structs.cs b/src/Csharpc/CodeGen/FunctionCodeGen.Structs.cs index 3907ff19..25018cf9 100644 --- a/src/Csharpc/CodeGen/FunctionCodeGen.Structs.cs +++ b/src/Csharpc/CodeGen/FunctionCodeGen.Structs.cs @@ -627,6 +627,11 @@ internal LLVMValueRef FormatValue(LLVMValueRef value, ITypeSymbol type, IOperati return ConcatStrings(ConcatStrings(prefix, count), _m.StringLiteral("]")); } } + // A library struct that does not override ToString formats as ValueType.ToString(): its full name, known here for a + // non-generic one (System.IO.Pipes interpolates a CancellationToken into a message). + if (type is INamedTypeSymbol { TypeKind: TypeKind.Struct, IsGenericType: false } plain + && !plain.GetMembers("ToString").OfType().Any(m => m.IsOverride && m.Parameters.IsEmpty)) + return _m.StringLiteral(Mangler.MetadataName(plain)); // (Outer+Inner, as Type.FullName) throw CompileError.Unsupported($"formatting '{type}'", at); } } 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.Devirtualization.cs b/src/Csharpc/CodeGen/ModuleCodeGen.Devirtualization.cs index 9f515692..a4da85cb 100644 --- a/src/Csharpc/CodeGen/ModuleCodeGen.Devirtualization.cs +++ b/src/Csharpc/CodeGen/ModuleCodeGen.Devirtualization.cs @@ -29,9 +29,9 @@ public sealed partial class ModuleCodeGen var root = ClassLayout.RootOf(target); IMethodSymbol? unique = null; - foreach (var type in HierarchyTypes) + foreach (var type in DescendantsServed(receiver)) { - if (type.TypeKind != TypeKind.Class || type.IsAbstract || type.IsStatic || !DerivesFromOrEqualsServed(type, receiver)) continue; + if (type.TypeKind != TypeKind.Class || type.IsAbstract || type.IsStatic) continue; if (type.IsGenericType || TypeSubstitution.IsGenericContext(type)) return null; var implementation = ResolveSlot(type, root); if (implementation is null) return null; @@ -76,10 +76,9 @@ internal bool InterfaceReimplementedBelow(INamedTypeSymbol type, INamedTypeSymbo var key = ((INamedTypeSymbol)type.OriginalDefinition, (INamedTypeSymbol)interfaceType.OriginalDefinition); if (_reimplemented.TryGetValue(key, out var known)) return known; var found = false; - foreach (var candidate in HierarchyTypes) + foreach (var candidate in DescendantsServed(key.Item1)) { - if (candidate.TypeKind != TypeKind.Class || SymbolEqualityComparer.Default.Equals(candidate.OriginalDefinition, key.Item1) - || !DerivesFromOrEqualsServed(candidate, key.Item1)) continue; + if (candidate.TypeKind != TypeKind.Class || SymbolEqualityComparer.Default.Equals(candidate.OriginalDefinition, key.Item1)) continue; foreach (var declared in candidate.Interfaces) if (SymbolEqualityComparer.Default.Equals(declared.OriginalDefinition, key.Item2) || declared.AllInterfaces.Any(i => SymbolEqualityComparer.Default.Equals(i.OriginalDefinition, key.Item2))) @@ -92,20 +91,39 @@ internal bool InterfaceReimplementedBelow(INamedTypeSymbol type, INamedTypeSymbo return _reimplemented[key] = found; } + private Dictionary>? _descendantsServed; + /// - /// through the types csharpc serves a library type with: a program class names the reference assembly's - /// base (`class L : EventListener`), while the framework's IL that makes the virtual call names the type that serves it (the slice's - /// EventListener). Without the mapping, the program's classes would be missing from the subtree, and a call whose only other override is - /// the framework's own (XplatEventLogger.OnEventSourceCreated) would be devirtualized to it. + /// The hierarchy's types deriving from or equal to , in HierarchyTypes order, through the types csharpc + /// serves a library type with: a program class names the reference assembly's base (`class L : EventListener`), while the + /// framework's IL that makes the virtual call names the type that serves it (the slice's EventListener). Without the mapping, the + /// program's classes would be missing from the subtree, and a call whose only other override is the framework's own + /// (XplatEventLogger.OnEventSourceCreated) would be devirtualized to it. Indexed once, since HierarchyTypes (the program's and the + /// IL's types) is complete before any method is lowered: each devirtualized method used to walk every type's base chain (#93). /// - private bool DerivesFromOrEqualsServed(INamedTypeSymbol type, INamedTypeSymbol baseType) + private List DescendantsServed(INamedTypeSymbol baseType) { - var wanted = baseType.OriginalDefinition; - for (var t = type; t is not null; t = t.BaseType) - if (SymbolEqualityComparer.Default.Equals(t.OriginalDefinition, wanted) - || CoreLib.TryMap(t) is { } served && SymbolEqualityComparer.Default.Equals(served.OriginalDefinition, wanted)) - return true; - return false; + if (_descendantsServed is null) + { + var index = new Dictionary>(SymbolEqualityComparer.Default); + var keys = new HashSet(SymbolEqualityComparer.Default); + foreach (var type in HierarchyTypes) + { + keys.Clear(); + for (var t = type; t is not null; t = t.BaseType) + { + keys.Add(t.OriginalDefinition); + if (CoreLib.TryMap(t) is { } served) keys.Add(served.OriginalDefinition); + } + foreach (var key in keys) + { + if (!index.TryGetValue(key, out var list)) index[key] = list = []; + list.Add(type); + } + } + _descendantsServed = index; + } + return _descendantsServed.TryGetValue(baseType.OriginalDefinition, out var found) ? found : []; } internal static bool DerivesFromOrEquals(INamedTypeSymbol type, INamedTypeSymbol baseType) 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 /// Which kinds of stored values the program's string resources include (corelib/Resources.cs): any non-string value ("\uFFFF\u0001type..."), - /// and any DeserializingResourceReader creates with a TypeConverter ("...\u00023\u0001text"). Constants for the corelib: without the first, + /// and any DeserializingResourceReader creates with a TypeConverter or a (Stream) constructor ("...\u00023\u0001text", formats 2 and 4 too). Constants for the corelib: without the first, /// ResourceManager's object creation (date, time-span, Guid parsing, the TypeConverters) is dead code, and without the second TypeDescriptor /// is, so a program that only constructs a ResourceManager (an EventSource's manifest builder takes one) does not link them. /// @@ -54,7 +54,9 @@ private static (bool, bool) Scan(IEnumerable values) if (v.StartsWith("\uFFFF\u0001", StringComparison.Ordinal)) { nonString = true; - if (v.Contains("\u00023\u0001", StringComparison.Ordinal)) { converter = true; break; } + // Formats 2 (the converter's byte array) and 4 (a stream for the constructor, #300) need the same machinery as 3. + if (v.Contains("\u00023\u0001", StringComparison.Ordinal) || v.Contains("\u00022\u0001", StringComparison.Ordinal) + || v.Contains("\u00024\u0001", StringComparison.Ordinal)) { converter = true; break; } } return (nonString, converter); } diff --git a/src/Csharpc/CodeGen/ModuleCodeGen.ReverseThunks.cs b/src/Csharpc/CodeGen/ModuleCodeGen.ReverseThunks.cs index 6c84a00e..3ad21db1 100644 --- a/src/Csharpc/CodeGen/ModuleCodeGen.ReverseThunks.cs +++ b/src/Csharpc/CodeGen/ModuleCodeGen.ReverseThunks.cs @@ -33,6 +33,9 @@ internal LLVMValueRef ReverseThunkTable(INamedTypeSymbol type, IOperation at) if (_reverseThunkTables.TryGetValue(type, out var existing)) return existing; var invoke = type.DelegateInvokeMethod!; var shape = MarshalledSignature(invoke, type, at); + // A struct by value needs the C ABI's classification: each slot's thunk takes the managed struct, and an adapter with + // the native signature ([UnmanagedCallersOnly]'s, ModuleCodeGen.NativeCalls.cs) rebuilds it and is what native code calls. + var abi = HasStructByValue(invoke) ? NativeShapeOf(invoke) : null; var entry = Llvm.Ptr; var tableType = Llvm.Struct(Types.NativeInt, LlvmContext.Array(entry, ReverseThunkSlots), LlvmContext.Array(entry, ReverseThunkSlots)); var name = "csharpc.reversethunks." + Mangler.MetadataName(type); @@ -46,8 +49,12 @@ internal LLVMValueRef ReverseThunkTable(INamedTypeSymbol type, IOperation at) { var slot = i; var thunk = SyntheticFunction($"{name}.thunk{i}", fnType, (g, syntax) => 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/CodeGen/ModuleCodeGen.VTables.cs b/src/Csharpc/CodeGen/ModuleCodeGen.VTables.cs index b4250402..f6447470 100644 --- a/src/Csharpc/CodeGen/ModuleCodeGen.VTables.cs +++ b/src/Csharpc/CodeGen/ModuleCodeGen.VTables.cs @@ -33,7 +33,55 @@ private sealed class PendingMethodTable private readonly Dictionary> _dispatchedInterfaceSlots = new(SymbolEqualityComparer.Default); // Slots waiting for their root / interface member to be dispatched. private readonly Dictionary> _slotsByRoot = new(SymbolEqualityComparer.Default); - private readonly Dictionary> _interfaceEntries = new(SymbolEqualityComparer.Default); + private readonly Dictionary _interfaceEntries = new(SymbolEqualityComparer.Default); + // Per generic definition: the dispatched slots, indexed like InterfaceEntries. + private readonly Dictionary> _dispatchedSlotsByKey = new(SymbolEqualityComparer.Default); + private readonly Dictionary _interfaceDispatchKeys = new(SymbolEqualityComparer.Default); + + /// + /// Items of one generic interface definition indexed by (#93: programs have thousands of + /// IEnumerable<T> method-table entries, and every new dispatch through one instantiation used to visit all of them, each + /// recomputing its key). Each item keeps its insertion number, so the reachable ones are merged back in insertion order, the + /// order the full scan enqueued them in, and the emitted module does not change. + /// + private sealed class Keyed + { + public List<(long Order, T Item)> All { get; } = []; + public List<(long Order, T Item)> AnyInstantiation { get; } = []; + public Dictionary> ByInstantiation { get; } = new(StringComparer.Ordinal); + + public void Add(long order, string? key, T item) + { + All.Add((order, item)); + if (key is null) AnyInstantiation.Add((order, item)); + else + { + if (!ByInstantiation.TryGetValue(key, out var list)) ByInstantiation[key] = list = []; + list.Add((order, item)); + } + } + + /// + /// The items a key reaches (DispatchReaches), in insertion order: every item for no key, else the keyless ones and the + /// key's own. + /// + public IEnumerable Reached(string? key) + { + if (key is null) { foreach (var (_, item) in All) yield return item; yield break; } + var any = AnyInstantiation; + var own = ByInstantiation.TryGetValue(key, out var list) ? list : []; + int i = 0, j = 0; + while (i < any.Count || j < own.Count) + yield return j >= own.Count || (i < any.Count && any[i].Order < own[j].Order) ? any[i++].Item : own[j++].Item; + } + } + + private sealed class InterfaceEntries + { + public Keyed<(PendingMethodTable Table, int Interface)> Entries { get; } = new(); + } + + private long _keyedOrder; // Slots to fill: (table, vtable slot, -1) or (table, interface member index, interface entry). private readonly Queue<(PendingMethodTable Table, int Slot, int Interface)> _slotRequests = new(); private bool _methodTablesFinished; @@ -54,9 +102,13 @@ internal void NoteVirtualDispatch(IMethodSymbol root) /// null, any of them (variance lets an IEnumerable<object> call use an IEnumerable<string> table; an /// open instantiation is conservatively any). Compared by .NET metadata name, which corelib shadows share. /// - private string? InterfaceDispatchKey(INamedTypeSymbol itf) => - itf.IsGenericType && !TypeSubstitution.IsOpen(itf) && itf.OriginalDefinition.TypeParameters.All(p => p.Variance == VarianceKind.None) + private string? InterfaceDispatchKey(INamedTypeSymbol itf) + { + if (_interfaceDispatchKeys.TryGetValue(itf, out var key)) return key; + key = itf.IsGenericType && !TypeSubstitution.IsOpen(itf) && itf.OriginalDefinition.TypeParameters.All(p => p.Variance == VarianceKind.None) ? Mangler.MetadataName(itf) : null; + return _interfaceDispatchKeys[itf] = key; + } private static bool DispatchReaches((int Slot, string? Instantiation) dispatch, string? table) => dispatch.Instantiation is null || table is null || dispatch.Instantiation == table; @@ -69,9 +121,10 @@ internal void NoteInterfaceDispatch(INamedTypeSymbol itf, int index) if (!_dispatchedInterfaceSlots.TryGetValue(definition, out var dispatched)) _dispatchedInterfaceSlots[definition] = dispatched = []; if (!dispatched.Add(dispatch)) return; CheckNotFinished(); + if (!_dispatchedSlotsByKey.TryGetValue(definition, out var slots)) _dispatchedSlotsByKey[definition] = slots = new Keyed(); + slots.Add(_keyedOrder++, dispatch.Item2, index); if (_interfaceEntries.TryGetValue(definition, out var entries)) - foreach (var (table, entry) in entries) - if (DispatchReaches(dispatch, InterfaceDispatchKey(table.Interfaces[entry].Interface))) _slotRequests.Enqueue((table, index, entry)); + foreach (var (table, entry) in entries.Entries.Reached(dispatch.Item2)) _slotRequests.Enqueue((table, index, entry)); NoteBuiltinInterfaceDispatch(definition, dispatch); } @@ -144,12 +197,11 @@ private void RegisterMethodTableSlots(PendingMethodTable table) for (var j = 0; j < table.Interfaces.Count; j++) { var definition = table.Interfaces[j].Interface.OriginalDefinition; - if (!_interfaceEntries.TryGetValue(definition, out var entries)) _interfaceEntries[definition] = entries = []; - entries.Add((table, j)); + if (!_interfaceEntries.TryGetValue(definition, out var entries)) _interfaceEntries[definition] = entries = new InterfaceEntries(); var key = InterfaceDispatchKey(table.Interfaces[j].Interface); - if (_dispatchedInterfaceSlots.TryGetValue(definition, out var dispatched)) - foreach (var dispatch in dispatched) - if (DispatchReaches(dispatch, key)) _slotRequests.Enqueue((table, dispatch.Slot, j)); + entries.Entries.Add(_keyedOrder++, key, (table, j)); + if (_dispatchedSlotsByKey.TryGetValue(definition, out var slots)) + foreach (var slot in slots.Reached(key)) _slotRequests.Enqueue((table, slot, j)); } } diff --git a/src/Csharpc/Frontend/Il/ResourcesFile.cs b/src/Csharpc/Frontend/Il/ResourcesFile.cs index 14b4b738..a75604ed 100644 --- a/src/Csharpc/Frontend/Il/ResourcesFile.cs +++ b/src/Csharpc/Frontend/Il/ResourcesFile.cs @@ -108,8 +108,15 @@ private static string FullName(string assemblyQualified) 14 => reader.ReadDecimal().ToString(invariant), 15 or 16 => reader.ReadInt64().ToString(invariant), // DateTime / TimeSpan: their ticks 32 or 33 => Convert.ToBase64String(reader.ReadBytes(reader.ReadInt32())), // byte[] and Stream: the bytes - // a preserialized user type: format 3 is "the type converter's string" (the text from the .resx) - >= StartOfUserTypes => format == 3 ? reader.ReadString() : null, + // a preserialized user type: format 3 is "the type converter's string" (the text from the .resx); formats 2 (the type + // converter's byte array) and 4 (the bytes of the stream for its constructor) are a 7-bit length and the bytes, as + // DeserializingResourceReader reads them (#300), kept as base64 + >= StartOfUserTypes => format switch + { + 3 => reader.ReadString(), + 2 or 4 => Convert.ToBase64String(reader.ReadBytes(Read7BitEncodedInt(reader))), + _ => null, + }, _ => null, }; } diff --git a/src/Csharpc/Frontend/ResourceConverters.cs b/src/Csharpc/Frontend/ResourceConverters.cs index 3f4793dc..34cbb913 100644 --- a/src/Csharpc/Frontend/ResourceConverters.cs +++ b/src/Csharpc/Frontend/ResourceConverters.cs @@ -70,7 +70,7 @@ public static IReadOnlyList TypeNames(IEnumerable resou try { foreach (var entry in Il.ResourcesFile.Read(File.ReadAllBytes(resource.Path))) - if (entry.Text is null && entry.Format == 3 && !s_primitives.Contains(entry.TypeName)) names.Add(entry.TypeName); + if (entry.Text is null && entry.Format is 2 or 3 or 4 && !s_primitives.Contains(entry.TypeName)) names.Add(entry.TypeName); } catch (Exception e) when (e is InvalidDataException or EndOfStreamException or IOException or ArgumentException or FormatException) { } } @@ -87,12 +87,40 @@ public static CSharpCompilation AddFromIl(CSharpCompilation compilation, CSharpC private static CSharpCompilation Add(CSharpCompilation target, CSharpCompilation compilation, IReadOnlyList typeNames, CSharpParseOptions parseOptions) { + // Format 3 (the converter's string) and 2 (its byte array, #300) go through the type's converter; format 4 (a stream) through + // the type's public (Stream) constructor, as DeserializingResourceReader's Activator.CreateInstance(type, stream). A type + // without one gets .NET's MissingMethodException. var resourceCases = new StringBuilder(); + var bytesCases = new StringBuilder(); + var streamCases = new StringBuilder(); foreach (var name in typeNames) - if (!name.Contains('`') && compilation.GetTypeByMetadataName(name) is { } type && Creation(compilation, type) is { } creation) + { + if (name.Contains('`') || compilation.GetTypeByMetadataName(name) is not { } type) continue; + if (Creation(compilation, type) is { } creation) + { resourceCases.AppendLine($" case {Literal(name)}: return new object[] {{ {creation}.ConvertFromInvariantString(text) }};"); + bytesCases.AppendLine($" case {Literal(name)}: return new object[] {{ {creation}.ConvertFrom(data) }};"); + } + // Activator.CreateInstance(type, stream): a public (Stream) constructor, whose exception comes wrapped in a + // TargetInvocationException; none is a MissingMethodException with .NET's inner one. A type (or constructor) the generated + // code can't name gets no case, so GetObject's explicit "not supported" error stays. + var streamConstructor = type.InstanceConstructors.FirstOrDefault(c => c.DeclaredAccessibility == Accessibility.Public && !type.IsAbstract + && c.Parameters is [{ Type: { Name: "Stream", ContainingNamespace: { Name: "IO", ContainingNamespace.Name: "System" } } }]); + if (!compilation.IsSymbolAccessibleWithin(type, compilation.Assembly)) continue; + var fullName = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + if (type.IsAbstract) continue; // (.NET's abstract-class error is not reproduced: GetObject's explicit error stays) + if (streamConstructor is null) + { + // .NET's binder adds "Member not found." only when some public constructor takes one argument but not a Stream. + var inner = type.InstanceConstructors.Any(c => c.DeclaredAccessibility == Accessibility.Public && c.Parameters.Length == 1) + ? ", new global::System.MissingMethodException(\"Member not found.\")" : ""; + streamCases.AppendLine($" case {Literal(name)}: throw new global::System.MissingMethodException({Literal($"Constructor on type '{name}' not found.")}{inner});"); + } + else if (compilation.IsSymbolAccessibleWithin(streamConstructor, compilation.Assembly)) + streamCases.AppendLine($" case {Literal(name)}: try {{ return new object[] {{ new {fullName}(data) }}; }} catch (global::System.Exception e) {{ throw new global::System.Reflection.TargetInvocationException(e); }}"); + } - if (resourceCases.Length == 0) return target; + if (resourceCases.Length == 0 && streamCases.Length == 0) return target; var source = new StringBuilder(); source.AppendLine("#pragma warning disable CS0612, CS0618, CS0619"); source.AppendLine("namespace CsharpcCoreLib"); @@ -107,6 +135,22 @@ private static CSharpCompilation Add(CSharpCompilation target, CSharpCompilation source.AppendLine(" }"); source.AppendLine(" return null;"); source.AppendLine(" }"); + source.AppendLine(" internal static object[] ResourceObjectFromBytes(string type, byte[] data)"); + source.AppendLine(" {"); + source.AppendLine(" switch (type)"); + source.AppendLine(" {"); + source.Append(bytesCases); + source.AppendLine(" }"); + source.AppendLine(" return null;"); + source.AppendLine(" }"); + source.AppendLine(" internal static object[] ResourceObjectFromStream(string type, System.IO.Stream data)"); + source.AppendLine(" {"); + source.AppendLine(" switch (type)"); + source.AppendLine(" {"); + source.Append(streamCases); + source.AppendLine(" }"); + source.AppendLine(" return null;"); + source.AppendLine(" }"); source.AppendLine(" }"); source.AppendLine("}"); return target.AddSyntaxTrees(CSharpSyntaxTree.ParseText(source.ToString(), parseOptions, path: TreePath)); @@ -132,7 +176,7 @@ public static IReadOnlyList TypeNamesOfAssemblies(IEnumerable pa if (!resource.Implementation.IsNil || !reader.GetString(resource.Name).EndsWith(".resources", StringComparison.Ordinal)) continue; var block = directory.GetReader((int)resource.Offset, directory.Length - (int)resource.Offset); foreach (var entry in ResourcesFile.Read(block.ReadBytes(block.ReadInt32()))) - if (entry.Text is null && entry.Format == 3 && !s_primitives.Contains(entry.TypeName)) names.Add(entry.TypeName); + if (entry.Text is null && entry.Format is 2 or 3 or 4 && !s_primitives.Contains(entry.TypeName)) names.Add(entry.TypeName); } } catch (Exception e) when (e is InvalidDataException or EndOfStreamException or IOException or ArgumentException or FormatException or BadImageFormatException) { } diff --git a/src/Csharpc/corelib/Core.cs b/src/Csharpc/corelib/Core.cs index d22f8e35..8f11dcb1 100644 --- a/src/Csharpc/corelib/Core.cs +++ b/src/Csharpc/corelib/Core.cs @@ -132,6 +132,9 @@ internal static class CoreIntrinsics /// type (Frontend/ResourceConverters.cs generates one for the types its .resources files hold). /// [MethodImpl(MethodImplOptions.InternalCall)] public static extern object[] ResourceObjectHook(string type, string text); + /// The program's preserialized resources stored as bytes (#300): format 2 through the type's converter, format 4 through its (Stream) constructor. + [MethodImpl(MethodImplOptions.InternalCall)] public static extern object[] ResourceObjectFromBytesHook(string type, byte[] data); + [MethodImpl(MethodImplOptions.InternalCall)] public static extern object[] ResourceObjectFromStreamHook(string type, System.IO.Stream data); /// Whether the program carries a resource value created with a TypeConverter (ModuleCodeGen.HasConverterResources): a compile-time constant. [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool HasConverterResources(); /// Whether the program carries any stored non-string resource value (ModuleCodeGen.HasNonStringResources): a compile-time constant. 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/ExceptionData.cs b/src/Csharpc/corelib/ExceptionData.cs index 89623bc7..18f1d5a1 100644 --- a/src/Csharpc/corelib/ExceptionData.cs +++ b/src/Csharpc/corelib/ExceptionData.cs @@ -17,6 +17,9 @@ internal static class ExceptionData private sealed class StringBox { public string Value; } + /// TypeInitializationException(fullTypeName, innerException)'s message (.NET's SR.TypeInitialization_Type). + public static string TypeInitializerMessage(string fullTypeName) => "The type initializer for '" + fullTypeName + "' threw an exception."; + public static string GetHelpLink(Exception exception) => s_helpLink.TryGetValue(exception, out StringBox box) ? box.Value : null; public static void SetHelpLink(Exception exception, string value) => s_helpLink.GetOrCreateValue(exception).Value = value; diff --git a/src/Csharpc/corelib/IO/MemoryMappedFiles.cs b/src/Csharpc/corelib/IO/MemoryMappedFiles.cs index 5d5f28be..a4356194 100644 --- a/src/Csharpc/corelib/IO/MemoryMappedFiles.cs +++ b/src/Csharpc/corelib/IO/MemoryMappedFiles.cs @@ -1,7 +1,8 @@ -// System.IO.MemoryMappedFiles: read-only views of files, the subset System.Reflection.Metadata (and -// so Roslyn's metadata references) use: MemoryMappedFile.CreateFromFile(FileStream, ...) with -// MemoryMappedFileAccess.Read, CreateViewAccessor, and the view's SafeBuffer pointer. Writable maps, -// named maps and views as streams are not implemented: they throw NotSupportedException. +// System.IO.MemoryMappedFiles: views of files, the subset System.Reflection.Metadata (and so Roslyn's +// metadata references) use: MemoryMappedFile.CreateFromFile(FileStream, ...) with MemoryMappedFileAccess.Read, +// CreateViewAccessor, and the view's SafeBuffer pointer; and (PROTOTYPE) read-write maps of a file with +// UnmanagedMemoryAccessor's typed Read/Write (eM Client's Spotlight checkpoint). Named maps, copy-on-write and +// execute access, and views as streams are not implemented: they throw NotSupportedException. #nullable disable using System; using System.IO; @@ -20,23 +21,27 @@ public unsafe class MemoryMappedFileImpl : IDisposable private readonly FileStream _stream; private readonly long _capacity; private readonly bool _leaveOpen; + private readonly bool _writable; private bool _disposed; - private MemoryMappedFileImpl(FileStream stream, long capacity, bool leaveOpen) + private MemoryMappedFileImpl(FileStream stream, long capacity, bool leaveOpen, bool writable) { _stream = stream; _capacity = capacity; _leaveOpen = leaveOpen; + _writable = writable; } + private static NotSupportedException UnsupportedAccess() => + new NotSupportedException("csharpc supports memory-mapped files with MemoryMappedFileAccess.Read or ReadWrite only yet."); + public static MemoryMappedFile CreateFromFile(FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { if (fileStream == null) throw new ArgumentNullException("fileStream", "fileStream cannot be null."); if (mapName != null && mapName.Length == 0) throw new ArgumentException("Map name cannot be an empty string."); if (capacity < 0) throw new ArgumentOutOfRangeException("capacity", "The capacity must be greater than or equal to 0 for a Memory Mapped File backed by a file."); - if (access != MemoryMappedFileAccess.Read) - throw new NotSupportedException("csharpc supports read-only memory-mapped files only (MemoryMappedFileAccess.Read) yet."); + if (access is not (MemoryMappedFileAccess.Read or MemoryMappedFileAccess.ReadWrite)) throw UnsupportedAccess(); if (mapName != null) throw new NotSupportedException("Named memory-mapped files are not supported by csharpc yet."); if (!Posix.CanMapFiles) throw new PlatformNotSupportedException("Memory-mapped files are not supported on this platform."); long length = fileStream.Length; @@ -44,31 +49,37 @@ public static MemoryMappedFile CreateFromFile(FileStream fileStream, string mapN throw new ArgumentException("A positive capacity must be specified for a Memory Mapped File backed by an empty file."); if (capacity != 0 && capacity < length) throw new ArgumentOutOfRangeException("capacity", "The capacity may not be smaller than the file size."); - if (capacity > length) + if (capacity > length && access == MemoryMappedFileAccess.Read) throw new ArgumentException("When specifying MemoryMappedFileAccess.Read access, the capacity must not be larger than the file size."); fileStream.Flush(); - return (MemoryMappedFile)(object)new MemoryMappedFileImpl(fileStream, capacity == 0 ? length : capacity, leaveOpen); + // A writable map larger than its file grows the file to the capacity first, as .NET does. + if (capacity > length) fileStream.SetLength(capacity); + return (MemoryMappedFile)(object)new MemoryMappedFileImpl(fileStream, capacity == 0 ? length : capacity, leaveOpen, + access == MemoryMappedFileAccess.ReadWrite); } - public MemoryMappedViewAccessor CreateViewAccessor() => CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); - public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size) => CreateViewAccessor(offset, size, MemoryMappedFileAccess.Read); + // .NET's default view access is ReadWrite, which a read-only map refuses; csharpc gives such a map a read view. + public MemoryMappedViewAccessor CreateViewAccessor() => CreateViewAccessor(0, 0, _writable ? MemoryMappedFileAccess.ReadWrite : MemoryMappedFileAccess.Read); + public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size) => + CreateViewAccessor(offset, size, _writable ? MemoryMappedFileAccess.ReadWrite : MemoryMappedFileAccess.Read); public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size, MemoryMappedFileAccess access) { if (offset < 0) throw new ArgumentOutOfRangeException("offset", "Non-negative number required."); if (size < 0) throw new ArgumentOutOfRangeException("size", "A positive number is required."); if (_disposed) throw new ObjectDisposedException("MemoryMappedFile", "Cannot access a disposed object."); - if (access != MemoryMappedFileAccess.Read) - throw new NotSupportedException("csharpc supports read-only memory-mapped files only (MemoryMappedFileAccess.Read) yet."); + if (access is not (MemoryMappedFileAccess.Read or MemoryMappedFileAccess.ReadWrite)) throw UnsupportedAccess(); + bool writable = access == MemoryMappedFileAccess.ReadWrite; + if (writable && !_writable) throw new UnauthorizedAccessException("Access to the path is denied."); if (size == 0) size = _capacity - offset; if (size <= 0 || offset + size > _capacity) throw new ArgumentOutOfRangeException("size", "The capacity may not be smaller than the file size."); long start = offset - offset % Granularity; long delta = offset - start; - byte* view = Posix.MapView(((FileStream)_stream).SafeFileHandle.DangerousGetHandle(), start, size + delta); + byte* view = Posix.MapView(((FileStream)_stream).SafeFileHandle.DangerousGetHandle(), start, size + delta, writable); if (view == null) throw Posix.IOError(Posix.Errno, null, false); var handle = new SafeMemoryMappedViewHandleImpl(view, size + delta); - return (MemoryMappedViewAccessor)(object)new MemoryMappedViewAccessorImpl(handle, delta, size); + return (MemoryMappedViewAccessor)(object)new MemoryMappedViewAccessorImpl(handle, delta, size, writable); } public void Dispose() @@ -85,28 +96,139 @@ protected virtual void Dispose(bool disposing) } [Shadows("System.IO.MemoryMappedFiles.MemoryMappedViewAccessor")] - public sealed class MemoryMappedViewAccessorImpl : IDisposable + public sealed class MemoryMappedViewAccessorImpl : UnmanagedMemoryAccessorImpl { private readonly SafeMemoryMappedViewHandleImpl _handle; - private readonly long _pointerOffset, _capacity; + private readonly long _pointerOffset; - internal MemoryMappedViewAccessorImpl(SafeMemoryMappedViewHandleImpl handle, long pointerOffset, long capacity) + internal MemoryMappedViewAccessorImpl(SafeMemoryMappedViewHandleImpl handle, long pointerOffset, long capacity, bool writable) + : base(handle, pointerOffset, capacity, writable) { _handle = handle; _pointerOffset = pointerOffset; - _capacity = capacity; } public SafeMemoryMappedViewHandle SafeMemoryMappedViewHandle => (SafeMemoryMappedViewHandle)(object)_handle; public long PointerOffset => _pointerOffset; + + // MAP_SHARED pages are the file's: other readers of the file see the writes already. + public void Flush() { } + } + + /// + /// UnmanagedMemoryAccessor (dotnet/runtime's UnmanagedMemoryAccessor.cs, the parts views use): bounds- and + /// access-checked reads and writes at a position of a SafeBuffer, which starts _start bytes into the buffer. + /// + [Shadows("System.IO.UnmanagedMemoryAccessor")] + public unsafe class UnmanagedMemoryAccessorImpl : IDisposable + { + private readonly SafeBufferImpl _buffer; + private readonly long _start, _capacity; + private readonly bool _canWrite; + private bool _open; + + internal UnmanagedMemoryAccessorImpl(SafeBufferImpl buffer, long start, long capacity, bool canWrite) + { + _buffer = buffer; + _start = start; + _capacity = capacity; + _canWrite = canWrite; + _open = true; + } + public long Capacity => _capacity; - public bool CanRead => !_handle.IsClosed; - public bool CanWrite => false; + public bool CanRead => _open; + public bool CanWrite => _open && _canWrite; public void Dispose() { - _handle.Dispose(); + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!_open) return; + _open = false; + _buffer.Dispose(); } + + // .NET's checks, in its order (UnmanagedMemoryAccessor.cs): closed, access, negative position, then room. + private void CheckOpen(bool write) + { + if (!_open) throw new ObjectDisposedException("UnmanagedMemoryAccessor", "Cannot access a closed accessor."); + if (write && !_canWrite) throw new NotSupportedException("Accessor does not support writing."); + } + + private static ArgumentOutOfRangeException PastCapacity() => + new ArgumentOutOfRangeException("position", "The position may not be greater or equal to the capacity of the accessor."); + + private ulong Checked(long position, int size, bool write) + { + CheckOpen(write); + ArgumentOutOfRangeException.ThrowIfNegative(position); + if (position > _capacity - size) + { + if (position >= _capacity) throw PastCapacity(); + throw new ArgumentException(write ? "There are not enough bytes remaining in the accessor to write at this position." + : "There are not enough bytes remaining in the accessor to read at this position.", "position"); + } + return (ulong)(_start + position); + } + +#pragma warning disable CS8500 // structs of unmanaged data only, as in .NET + public void Read(long position, out T structure) where T : struct => structure = _buffer.Read(Checked(position, sizeof(T), false)); + public void Write(long position, ref T structure) where T : struct => _buffer.Write(Checked(position, sizeof(T), true), structure); + + public int ReadArray(long position, T[] array, int offset, int count) where T : struct + { + ArrayArguments(array, offset, count); + CheckOpen(false); + ArgumentOutOfRangeException.ThrowIfNegative(position); + if (position >= _capacity) throw PastCapacity(); + int n = (int)Math.Min(count, (_capacity - position) / sizeof(T)); + if (n > 0) _buffer.ReadArray((ulong)(_start + position), array, offset, n); + return n; + } + + // Room is the SafeBuffer's check here, as in .NET ("Not enough space available in the buffer."): the view's buffer + // ends where the accessor does. + public void WriteArray(long position, T[] array, int offset, int count) where T : struct + { + ArrayArguments(array, offset, count); + CheckOpen(true); + ArgumentOutOfRangeException.ThrowIfNegative(position); + if (position >= _capacity) throw PastCapacity(); + _buffer.WriteArray((ulong)(_start + position), array, offset, count); + } +#pragma warning restore CS8500 + + private static void ArrayArguments(T[] array, int offset, int count) + { + ArgumentNullException.ThrowIfNull(array); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfNegative(count); + if (array.Length - offset < count) throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."); + } + + public byte ReadByte(long position) => _buffer.Read(Checked(position, 1, false)); + public bool ReadBoolean(long position) => ReadByte(position) != 0; + public short ReadInt16(long position) => _buffer.Read(Checked(position, 2, false)); + public int ReadInt32(long position) => _buffer.Read(Checked(position, 4, false)); + public long ReadInt64(long position) => _buffer.Read(Checked(position, 8, false)); + public ushort ReadUInt16(long position) => _buffer.Read(Checked(position, 2, false)); + public uint ReadUInt32(long position) => _buffer.Read(Checked(position, 4, false)); + public ulong ReadUInt64(long position) => _buffer.Read(Checked(position, 8, false)); + public double ReadDouble(long position) => _buffer.Read(Checked(position, 8, false)); + public void Write(long position, byte value) => _buffer.Write(Checked(position, 1, true), value); + public void Write(long position, bool value) => Write(position, (byte)(value ? 1 : 0)); + public void Write(long position, short value) => _buffer.Write(Checked(position, 2, true), value); + public void Write(long position, int value) => _buffer.Write(Checked(position, 4, true), value); + public void Write(long position, long value) => _buffer.Write(Checked(position, 8, true), value); + public void Write(long position, ushort value) => _buffer.Write(Checked(position, 2, true), value); + public void Write(long position, uint value) => _buffer.Write(Checked(position, 4, true), value); + public void Write(long position, ulong value) => _buffer.Write(Checked(position, 8, true), value); + public void Write(long position, double value) => _buffer.Write(Checked(position, 8, true), value); } /// diff --git a/src/Csharpc/corelib/IO/Pipes.cs b/src/Csharpc/corelib/IO/Pipes.cs index 01a11268..091d395e 100644 --- a/src/Csharpc/corelib/IO/Pipes.cs +++ b/src/Csharpc/corelib/IO/Pipes.cs @@ -1,5 +1,7 @@ -// System.IO.Pipes: not implemented by csharpc yet. The types exist so code that mentions them compiles -// (Kestrel's named-pipe transport, type tests); creating a pipe throws NotSupportedException. +#if CSHARPC_TARGET_WINDOWS +// System.IO.Pipes on Windows: not implemented by csharpc yet. The types exist so code that mentions them compiles +// (Kestrel's named-pipe transport, type tests); creating a pipe throws NotSupportedException. On Linux and macOS the +// framework's own System.IO.Pipes is compiled from IL over the libSystem.Native contract (#102). #nullable disable using System; using System.IO; @@ -50,3 +52,4 @@ public NamedPipeServerStreamImpl(string pipeName, PipeDirection direction, int m public void Disconnect() => throw NotSupported(); } } +#endif diff --git a/src/Csharpc/corelib/IO/Posix.cs b/src/Csharpc/corelib/IO/Posix.cs index 1c648837..8fc5e7b1 100644 --- a/src/Csharpc/corelib/IO/Posix.cs +++ b/src/Csharpc/corelib/IO/Posix.cs @@ -43,6 +43,7 @@ internal static unsafe class Posix #if CSHARPC_TARGET_WASI public const bool CanMapFiles = false; public static byte* MapView(nint handle, long offset, long length) => null; + public static byte* MapView(nint handle, long offset, long length, bool writable) => null; public static void UnmapView(byte* view, long length) { } #else public const bool CanMapFiles = true; @@ -51,9 +52,12 @@ public static void UnmapView(byte* view, long length) { } /// A read-only shared view of [offset, offset + length) of a file (offset aligned to 64 KiB by the caller); null with errno set on failure. /// A read-only view of [offset, offset + length) of a file; is its descriptor (SafeFileHandle's value). - public static byte* MapView(nint handle, long offset, long length) + public static byte* MapView(nint handle, long offset, long length) => MapView(handle, offset, length, writable: false); + + /// A shared view, writable (PROT_READ | PROT_WRITE) or read-only; null with errno set on failure. + public static byte* MapView(nint handle, long offset, long length, bool writable) { - void* p = mmap(null, (nuint)length, 1 /* PROT_READ */, 1 /* MAP_SHARED */, (int)handle, offset); + void* p = mmap(null, (nuint)length, writable ? 3 : 1 /* PROT_READ (| PROT_WRITE) */, 1 /* MAP_SHARED */, (int)handle, offset); return p == (void*)-1 ? null : (byte*)p; } diff --git a/src/Csharpc/corelib/IO/SystemNative.cs b/src/Csharpc/corelib/IO/SystemNative.cs index d2f5d279..cb8ee7ce 100644 --- a/src/Csharpc/corelib/IO/SystemNative.cs +++ b/src/Csharpc/corelib/IO/SystemNative.cs @@ -853,7 +853,62 @@ public static int GetPwUidR(uint uid, void* pwd, byte* buf, int buflen) Buffer.MemoryCopy(native, pwd, 48, 48); return 0; } +#elif CSHARPC_TARGET_MACOS + [DllImport("libc")] private static extern int getpwuid_r(uint uid, void* pwd, byte* buf, nuint buflen, void** result); + + // pal_uid.c on macOS: its struct passwd has pw_change and pw_class between pw_gid and pw_gecos, and pw_expire and the int + // pw_fields after pw_shell (: 76 bytes of fields, 80 with the tail padding getpwuid_r may write); the framework's Passwd + // is Name, Password, UserId, GroupId, UserInfo, HomeDirectory, Shell (48). + [RuntimeExport("SystemNative_GetPwUidR", Trigger + "SystemNative_GetPwUidR")] + public static int GetPwUidR(uint uid, void* pwd, byte* buf, int buflen) + { + if (buflen < 0) return 22; // EINVAL + byte* native = stackalloc byte[80]; // sizeof(struct passwd) on Darwin LP64 + void* result; + int error; + while ((error = getpwuid_r(uid, native, buf, (nuint)buflen, &result)) == 4 /* EINTR */) { } + byte* to = (byte*)pwd; + new Span(to, 48).Clear(); + if (error != 0 || result == null) return error != 0 ? error : -1; + Buffer.MemoryCopy(native, to, 24, 24); // pw_name, pw_passwd, pw_uid, pw_gid + *(void**)(to + 24) = *(void**)(native + 40); // pw_gecos + *(void**)(to + 32) = *(void**)(native + 48); // pw_dir + *(void**)(to + 40) = *(void**)(native + 56); // pw_shell + return 0; + } #endif + + [DllImport("libc")] private static extern int seteuid(uint euid); + + /// SystemNative_SetEUid (pal_uid.c): seteuid(2). NamedPipeServerStream.RunAsClient switches to the client's user with it. + [RuntimeExport("SystemNative_SetEUid", Trigger + "SystemNative_SetEUid")] + public static int SetEUid(uint euid) => seteuid(euid); + +#if CSHARPC_TARGET_MACOS + [DllImport("libc")] private static extern int getpeereid(int fd, uint* euid, uint* egid); +#else + [DllImport("libc", EntryPoint = "getsockopt")] private static extern int getsockopt_peer(int fd, int level, int name, void* value, uint* length); +#endif + + /// + /// SystemNative_GetPeerID (pal_io.c): the effective user of a Unix domain socket's peer, from SO_PEERCRED's ucred { pid, uid, gid } on + /// Linux and getpeereid on macOS; 0 on success, -1 (errno set) otherwise. A named pipe's server checks its client's user with it. + /// + [RuntimeExport("SystemNative_GetPeerID", Trigger + "SystemNative_GetPeerID")] + public static int GetPeerID(nint socket, uint* euid) + { +#if CSHARPC_TARGET_MACOS + uint egid; + return getpeereid(Fd(socket), euid, &egid); +#else + const int SOL_SOCKET = 1, SO_PEERCRED = 17; + uint* creds = stackalloc uint[3]; + uint length = 12; + if (getsockopt_peer(Fd(socket), SOL_SOCKET, SO_PEERCRED, creds, &length) != 0) return -1; + *euid = creds[1]; + return 0; +#endif + } #else // WASI has no users: everything is the one user's (pal_io.c's emscripten/WASI build answers 0). [RuntimeExport("SystemNative_GetEUid", Trigger + "SystemNative_GetEUid")] @@ -864,7 +919,94 @@ public static int GetPwUidR(uint uid, void* pwd, byte* buf, int buflen) [RuntimeExport("SystemNative_GetGroups", Trigger + "SystemNative_GetGroups")] public static int GetGroups(int count, uint* groups) => 0; + + [RuntimeExport("SystemNative_SetEUid", Trigger + "SystemNative_SetEUid")] + public static int SetEUid(uint euid) => Fail(ENOTSUP); + + [RuntimeExport("SystemNative_GetPeerID", Trigger + "SystemNative_GetPeerID")] + public static int GetPeerID(nint socket, uint* euid) => Fail(ENOTSUP); +#endif + + // ---- descriptor flags and pipe sizes (pal_io.c) --------------------------------------------------------- + /// + /// SystemNative_FcntlSetFD: fcntl(F_SETFD) with the flags converted as pal_io.c does, through ConvertOpenFlags (the framework passes + /// FD_CLOEXEC = 1, the value of PAL_O_WRONLY, which converts to O_WRONLY = 1 = FD_CLOEXEC), retried on EINTR. + /// + [RuntimeExport("SystemNative_FcntlSetFD", Trigger + "SystemNative_FcntlSetFD")] + public static int FcntlSetFD(nint fd, int flags) + { +#if CSHARPC_TARGET_WASI + return Fail(ENOTSUP); +#else + const int F_SETFD = 2; + int native = ConvertOpenFlags(flags); + int r; + while ((r = fcntl_int(Fd(fd), F_SETFD, native)) < 0 && Errno == EINTR) { } + return r; +#endif + } + + /// pal_io.c's ConvertOpenFlags: the PAL open flags as the target's, or -1 for an unknown one. + private static int ConvertOpenFlags(int flags) + { + const int PalKnown = 0xF | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 | 0x200 | 0x1000; + int native; + switch (flags & 0xF) + { + case 0: native = O_RDONLY; break; + case 1: native = O_WRONLY; break; + case 2: native = O_RDWR; break; + default: return -1; + } + if ((flags & ~PalKnown) != 0) return -1; + if ((flags & 0x10) != 0) native |= O_CLOEXEC; + if ((flags & 0x20) != 0) native |= O_CREAT; + if ((flags & 0x40) != 0) native |= O_EXCL; + if ((flags & 0x80) != 0) native |= O_TRUNC; + if ((flags & 0x100) != 0) native |= O_SYNC; + if ((flags & 0x200) != 0) native |= O_NOFOLLOW; + if ((flags & 0x1000) != 0) native |= O_DIRECTORY; + return native; + } + + /// SystemNative_FcntlCanGetSetPipeSz: whether F_GETPIPE_SZ/F_SETPIPE_SZ exist (Linux only). + [RuntimeExport("SystemNative_FcntlCanGetSetPipeSz", Trigger + "SystemNative_FcntlCanGetSetPipeSz")] + public static int FcntlCanGetSetPipeSz() + { +#if CSHARPC_TARGET_LINUX + return 1; +#else + return 0; +#endif + } + + /// SystemNative_FcntlGetPipeSz: fcntl(F_GETPIPE_SZ) on Linux, retried on EINTR; elsewhere -1 with ENOTSUP. + [RuntimeExport("SystemNative_FcntlGetPipeSz", Trigger + "SystemNative_FcntlGetPipeSz")] + public static int FcntlGetPipeSz(nint fd) + { +#if CSHARPC_TARGET_LINUX + const int F_GETPIPE_SZ = 1032; + int r; + while ((r = fcntl_int(Fd(fd), F_GETPIPE_SZ, 0)) < 0 && Errno == EINTR) { } + return r; +#else + return Fail(ENOTSUP); #endif + } + + /// SystemNative_FcntlSetPipeSz: fcntl(F_SETPIPE_SZ, size) on Linux, retried on EINTR; elsewhere -1 with ENOTSUP. + [RuntimeExport("SystemNative_FcntlSetPipeSz", Trigger + "SystemNative_FcntlSetPipeSz")] + public static int FcntlSetPipeSz(nint fd, int size) + { +#if CSHARPC_TARGET_LINUX + const int F_SETPIPE_SZ = 1031; + int r; + while ((r = fcntl_int(Fd(fd), F_SETPIPE_SZ, size)) < 0 && Errno == EINTR) { } + return r; +#else + return Fail(ENOTSUP); +#endif + } // ---- hidden flag (macOS UF_HIDDEN) ---------------------------------------------------------------------- [RuntimeExport("SystemNative_CanGetHiddenFlag", Trigger + "SystemNative_CanGetHiddenFlag")] diff --git a/src/Csharpc/corelib/IO/Win32.cs b/src/Csharpc/corelib/IO/Win32.cs index 7c39ede0..4098bdfd 100644 --- a/src/Csharpc/corelib/IO/Win32.cs +++ b/src/Csharpc/corelib/IO/Win32.cs @@ -345,11 +345,14 @@ public static int FileType(string path) /// is the file's OS handle (SafeFileHandle, from the framework's IL since the file-system flip, holds the /// Win32 HANDLE itself, not a C runtime descriptor). /// - public static byte* MapView(nint handle, long offset, long length) + public static byte* MapView(nint handle, long offset, long length) => MapView(handle, offset, length, writable: false); + + /// A view, writable (PAGE_READWRITE, FILE_MAP_WRITE) or read-only; null with errno set on failure. + public static byte* MapView(nint handle, long offset, long length, bool writable) { - nint mapping = CreateFileMappingW(handle, null, 0x02 /* PAGE_READONLY */, 0, 0, null); + nint mapping = CreateFileMappingW(handle, null, writable ? 0x04u /* PAGE_READWRITE */ : 0x02u /* PAGE_READONLY */, 0, 0, null); if (mapping == 0) { _set_errno(Win32Base + Marshal.GetLastPInvokeError()); return null; } - void* view = MapViewOfFile(mapping, 0x0004 /* FILE_MAP_READ */, (uint)(offset >> 32), (uint)offset, (nuint)length); + void* view = MapViewOfFile(mapping, writable ? 0x0002u /* FILE_MAP_WRITE */ : 0x0004u /* FILE_MAP_READ */, (uint)(offset >> 32), (uint)offset, (nuint)length); int error = Marshal.GetLastPInvokeError(); CloseHandle(mapping); // the view keeps the mapping alive if (view == null) { _set_errno(Win32Base + error); return null; } 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/Reflection/Members.cs b/src/Csharpc/corelib/Reflection/Members.cs index 7551f772..d1955d17 100644 --- a/src/Csharpc/corelib/Reflection/Members.cs +++ b/src/Csharpc/corelib/Reflection/Members.cs @@ -1782,10 +1782,12 @@ public static object ActivatorCreateInstanceWith(Type type, BindingFlags binding if (args.Length == 0 && type.IsValueType && GetConstructor(type, bindingAttr, null, Type.EmptyTypes, null) == null) throw new NotSupportedException("Activator.CreateInstance of value type '" + type + "' is not supported by csharpc yet."); ConstructorInfo match = null; + bool sameArity = false; foreach (ConstructorInfo ctor in GetConstructors(type, bindingAttr)) { ParameterInfo[] parameters = ctor.GetParameters(); if (parameters.Length != args.Length) continue; + sameArity = true; bool fits = true; for (int i = 0; i < parameters.Length && fits; i++) { @@ -1797,7 +1799,12 @@ public static object ActivatorCreateInstanceWith(Type type, BindingFlags binding throw new NotSupportedException("Activator.CreateInstance on '" + type + "' with arguments several constructors accept is not supported by csharpc yet."); match = ctor; } - if (match == null) throw new MissingMethodException("Constructor on type '" + type.FullName + "' not found."); + // .NET filters the constructors by arity, then asks the default binder: when some have the arity but none bind, the + // binder's "Member not found." is the inner exception; when none has it, there is no inner one. + if (match == null) + throw sameArity + ? new MissingMethodException("Constructor on type '" + type.FullName + "' not found.", new MissingMethodException("Member not found.")) + : new MissingMethodException("Constructor on type '" + type.FullName + "' not found."); return match.Invoke(args); } diff --git a/src/Csharpc/corelib/Resources.cs b/src/Csharpc/corelib/Resources.cs index f36fe91c..860a33d4 100644 --- a/src/Csharpc/corelib/Resources.cs +++ b/src/Csharpc/corelib/Resources.cs @@ -217,13 +217,29 @@ internal static object ObjectOf(string baseName, string name, string value) object[] converted = CoreIntrinsics.ResourceObjectHook(type, text); if (converted != null) return converted[0] ?? throw new NullReferenceException(); } + // Format 2: the converter's byte array (a WinForms .resx's images and icons), DeserializingResourceReader's + // TypeDescriptor.GetConverter(type).ConvertFrom(bytes); a byte[] itself gets TypeDescriptor's ArrayConverter (#300). + else if (stored == ConverterBytes && CoreIntrinsics.HasConverterResources()) + { + byte[] data = Convert.FromBase64String(text); + if (type == "System.Byte[]") return TypeDescriptor.GetConverter(typeof(byte[])).ConvertFrom(data) ?? throw new NullReferenceException(); + object[] converted = CoreIntrinsics.ResourceObjectFromBytesHook(type, data); + if (converted != null) return converted[0] ?? throw new NullReferenceException(); + } + // Format 4: a read-only stream of the bytes for the type's (Stream) constructor (a ResXFileRef), as Activator.CreateInstance(type, stream). + else if (stored == ActivatorStream && CoreIntrinsics.HasConverterResources()) + { + object[] created = CoreIntrinsics.ResourceObjectFromStreamHook(type, new System.IO.MemoryStream(Convert.FromBase64String(text), false)); + if (created != null) return created[0]; + } throw new NotSupportedException("csharpc: the resource '" + name + "' of '" + baseName + "' is a " + type + (stored != null && stored != ConverterString ? " stored " + StoredHow(stored) : "") - + ", which ResourceManager.GetObject does not create yet (only strings, numbers, bools, chars, byte arrays, streams and types whose TypeConverter csharpc can create from the string in the .resx, from the types the project's .resx files name)."); + + ", which ResourceManager.GetObject does not create yet (only strings, numbers, bools, chars, byte arrays, streams, and the types the project's .resx files name whose TypeConverter or (Stream) constructor csharpc can call)."); } // A preserialized value that is the type converter's string ("\u0002" + this after the type name). private const string ConverterString = "3"; + private const string ConverterBytes = "2", ActivatorStream = "4"; private static string StoredHow(string format) { 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 9103e6ca..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 @@ -340,5 +343,7 @@ wasi 1346_nfloat_from_framework NFloat is a float on 32-bit targets (wasm32), windows 1563_timezoneinfo_from_il live: Windows takes the local zone from the system settings, not TZ; recorded there macos 1562_special_folders live: macOS takes the user folders from NSFileManager (the real home, not $HOME), Linux from $HOME and XDG; recorded on each windows 1562_special_folders known gap: Environment.GetFolderPath on Windows (the known folders) is not supported by csharpc yet; an explicit NotSupportedException +wasi 1567_named_pipes WASI has no Unix domain sockets or pipes: System.IO.Pipes does not work there +windows 1567_named_pipes known gap: System.IO.Pipes on Windows is not supported by csharpc yet (it is compiled from IL on Linux and macOS); an explicit NotSupportedException wasi 1570_process_lookups WASI has no processes to look up or start: Process.GetProcesses and Process.Start are explicit NotSupportedExceptions windows 1570_process_lookups known gap: looking up and naming processes on Windows (GetProcessById, GetProcesses, Modules) is not supported by csharpc yet; an explicit NotSupportedException diff --git a/tests/projects/cli/PreserializedBinary/Assets.resx b/tests/projects/cli/PreserializedBinary/Assets.resx new file mode 100644 index 00000000..5170d2c9 --- /dev/null +++ b/tests/projects/cli/PreserializedBinary/Assets.resx @@ -0,0 +1,15 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + AAABAAEAEBAAAA== + + picture.bin;Repro.Blob, PreserializedBinary + cmF3IGJ5dGVz + picture.bin;System.IO.MemoryStream, mscorlib + picture.bin;Repro.Broken, PreserializedBinary + picture.bin;Repro.NoStream, PreserializedBinary + diff --git a/tests/projects/cli/PreserializedBinary/PreserializedBinary.csproj b/tests/projects/cli/PreserializedBinary/PreserializedBinary.csproj new file mode 100644 index 00000000..6be7cc1c --- /dev/null +++ b/tests/projects/cli/PreserializedBinary/PreserializedBinary.csproj @@ -0,0 +1,16 @@ + + + + Exe + net11.0 + enable + enable + Repro + true + + + + + diff --git a/tests/projects/cli/PreserializedBinary/Program.cs b/tests/projects/cli/PreserializedBinary/Program.cs new file mode 100644 index 00000000..cf515143 --- /dev/null +++ b/tests/projects/cli/PreserializedBinary/Program.cs @@ -0,0 +1,69 @@ +using System.ComponentModel; +using System.Globalization; +using System.Resources; + +namespace Repro; + +// A type of the program standing in for System.Drawing's Bitmap and Icon: its converter takes a byte array (format 2), and it has a +// (Stream) constructor (format 4). +[TypeConverter(typeof(BlobConverter))] +sealed class Blob +{ + public byte[] Data { get; } + public string Via { get; } + public Blob(byte[] data, string via) { Data = data; Via = via; } + public Blob(Stream stream) + { + using var copy = new MemoryStream(); + stream.CopyTo(copy); + Data = copy.ToArray(); + Via = "stream" + (stream.CanWrite ? " (writable)" : ""); + } + public override string ToString() => $"{Via}: {Data.Length} bytes [{string.Join(",", Data.Take(6))}]"; +} + +// A (Stream) constructor that throws: Activator.CreateInstance wraps it in TargetInvocationException. +sealed class Broken +{ + public Broken(Stream stream) => throw new InvalidDataException("bad header: " + stream.Length); +} + +// No constructor takes one argument: .NET's MissingMethodException then has no inner exception. +sealed class NoStream +{ + public NoStream() { } + public NoStream(Stream stream, int length) { } +} + +sealed class BlobConverter : TypeConverter +{ + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) => sourceType == typeof(byte[]) || base.CanConvertFrom(context, sourceType); + + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) => + value is byte[] bytes ? (bytes.Length == 0 ? throw new FormatException("empty blob") : new Blob(bytes, "converter")) : base.ConvertFrom(context, culture, value); +} + +static class Program +{ + static void Main() + { + var resources = new ResourceManager("Repro.Assets", typeof(Program).Assembly); + foreach (var name in new[] { "Icon", "Picture", "Empty", "Raw", "RawStream", "BrokenFile", "NoStreamFile" }) + { + try + { + var o = resources.GetObject(name); + string shown = o switch + { + byte[] b => $"{b.Length} bytes", + Stream s => $"stream of {s.Length}", + _ => o?.ToString() ?? "(null)", + }; + Console.WriteLine($"{name}: {shown} [{o?.GetType().Name}]"); + } + catch (Exception e) { Console.WriteLine($"{name}: {e.GetType().Name}: {e.Message}" + (e.InnerException is { } inner ? $" ({inner.GetType().Name}: {inner.Message})" : "")); } + } + // Each GetObject creates the object again. + Console.WriteLine(ReferenceEquals(resources.GetObject("Icon"), resources.GetObject("Icon"))); + } +} diff --git a/tests/projects/cli/PreserializedBinary/picture.bin b/tests/projects/cli/PreserializedBinary/picture.bin new file mode 100644 index 00000000..8e8c1ce6 --- /dev/null +++ b/tests/projects/cli/PreserializedBinary/picture.bin @@ -0,0 +1,3 @@ +‰PNG + +fake picture bytes \ No newline at end of file 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/1345_memorymapped_read_write.cs b/tests/samples/1345_memorymapped_read_write.cs new file mode 100644 index 00000000..d372a04d --- /dev/null +++ b/tests/samples/1345_memorymapped_read_write.cs @@ -0,0 +1,71 @@ +// Read-write memory-mapped files: CreateFromFile with MemoryMappedFileAccess.ReadWrite grows the file to the capacity, a +// ReadWrite view accessor reads and writes structs, scalars and arrays (UnmanagedMemoryAccessor), the writes reach the file, +// and the accessor's bounds, access and disposal checks throw .NET's exceptions. +using System; +using System.IO; +using System.IO.MemoryMappedFiles; + +struct Checkpoint { public ulong ItemId; public short Kind; public int Count; } + +static class Program +{ + static void Try(string label, Action action) + { + try { action(); Console.WriteLine(label + ": ok"); } + catch (Exception e) { Console.WriteLine($"{label}: {e.GetType().Name}: {e.Message}"); } + } + + static void Main() + { + var path = Path.Combine(Path.GetTempPath(), "csharpc-mmap-sample-" + Environment.ProcessId + ".bin"); + File.Delete(path); + try + { + using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) + using (var file = MemoryMappedFile.CreateFromFile(stream, null, 64, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false)) + using (var view = file.CreateViewAccessor(0, 64, MemoryMappedFileAccess.ReadWrite)) + { + Console.WriteLine($"file {new FileInfo(path).Length} capacity {view.Capacity} read {view.CanRead} write {view.CanWrite}"); + var checkpoint = new Checkpoint { ItemId = 0x1122334455667788, Kind = 3, Count = -5 }; + view.Write(0, ref checkpoint); + view.Write(24, 0x7FFFFFFF); + view.Write(28, (byte)9); + view.Write(30, (short)-2); + view.Write(32, 1.5); + view.WriteArray(40, new int[] { 10, 20, 30 }, 0, 3); + view.Read(0, out Checkpoint back); + Console.WriteLine($"{back.ItemId:X} {back.Kind} {back.Count} {view.ReadInt32(24)} {view.ReadByte(28)} {view.ReadInt16(30)} {view.ReadDouble(32) == 1.5}"); + var ints = new int[5]; + Console.WriteLine($"{view.ReadArray(40, ints, 1, 3)} [{string.Join(",", ints)}]"); + Console.WriteLine($"{view.ReadArray(56, ints, 0, 5)} [{string.Join(",", ints)}]"); + Try("write past the end", () => view.Write(60, 1L)); + Try("read at the capacity", () => view.ReadInt32(64)); + Try("negative position", () => view.ReadByte(-1)); + Try("struct past the end", () => view.Read(56, out Checkpoint _)); + Try("struct write past the end", () => view.Write(56, ref checkpoint)); + Try("array past the end", () => view.WriteArray(60, new int[2], 0, 2)); + Try("array at the capacity", () => view.ReadArray(64, ints, 0, 1)); + Try("array null", () => view.ReadArray(0, (int[])null!, 0, 1)); + Try("array count", () => view.ReadArray(0, ints, 4, 2)); + } + + var bytes = File.ReadAllBytes(path); + Console.WriteLine($"on disk {bytes.Length}: {bytes[0]:X2} {bytes[7]:X2} {bytes[8]} {bytes[24]:X2} {bytes[28]} {bytes[40]} {bytes[44]}"); + + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + using (var file = MemoryMappedFile.CreateFromFile(stream, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, false)) + { + var view = file.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); + Console.WriteLine($"read-only: {view.ReadInt32(24)} write {view.CanWrite}"); + Try("write to a read view", () => view.Write(0, 1)); + view.Dispose(); + Console.WriteLine($"disposed: read {view.CanRead}"); + Try("read after dispose", () => view.ReadInt32(0)); + } + } + finally + { + File.Delete(path); + } + } +} diff --git a/tests/samples/1345_memorymapped_read_write.expected b/tests/samples/1345_memorymapped_read_write.expected new file mode 100644 index 00000000..6de06e5d --- /dev/null +++ b/tests/samples/1345_memorymapped_read_write.expected @@ -0,0 +1,20 @@ +file 64 capacity 64 read True write True +1122334455667788 3 -5 2147483647 9 -2 True +3 [0,10,20,30,0] +2 [0,0,20,30,0] +write past the end: ArgumentException: There are not enough bytes remaining in the accessor to write at this position. (Parameter 'position') +read at the capacity: ArgumentOutOfRangeException: The position may not be greater or equal to the capacity of the accessor. (Parameter 'position') +negative position: ArgumentOutOfRangeException: position ('-1') must be a non-negative value. (Parameter 'position') +Actual value was -1. +struct past the end: ArgumentException: There are not enough bytes remaining in the accessor to read at this position. (Parameter 'position') +struct write past the end: ArgumentException: There are not enough bytes remaining in the accessor to write at this position. (Parameter 'position') +array past the end: ArgumentException: Not enough space available in the buffer. +array at the capacity: ArgumentOutOfRangeException: The position may not be greater or equal to the capacity of the accessor. (Parameter 'position') +array null: ArgumentNullException: Value cannot be null. (Parameter 'array') +array count: ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. +on disk 64: 88 11 3 FF 9 10 20 +read-only: 2147483647 write False +write to a read view: NotSupportedException: Accessor does not support writing. +disposed: read False +read after dispose: ObjectDisposedException: Cannot access a closed accessor. +Object name: 'UnmanagedMemoryAccessor'. 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 diff --git a/tests/samples/1564_activator_missing_constructor_inner.cs b/tests/samples/1564_activator_missing_constructor_inner.cs new file mode 100644 index 00000000..23a0340b --- /dev/null +++ b/tests/samples/1564_activator_missing_constructor_inner.cs @@ -0,0 +1,32 @@ +// Activator.CreateInstance(type, args) with no constructor that binds: .NET's MissingMethodException carries the default +// binder's "Member not found." when some public constructor has the arguments' count, and no inner exception when none has. +using System; +using System.IO; + +Try("MemoryStream(Stream)", () => Activator.CreateInstance(typeof(MemoryStream), new object[] { new MemoryStream() })); +Try("OnlyInt(string)", () => Activator.CreateInstance(typeof(OnlyInt), new object[] { "x" })); +Try("OnlyInt(int, int)", () => Activator.CreateInstance(typeof(OnlyInt), new object[] { 1, 2 })); +Try("NoPublic(int)", () => Activator.CreateInstance(typeof(NoPublic), new object[] { 1 })); +Try("OnlyInt(int)", () => Activator.CreateInstance(typeof(OnlyInt), new object[] { 7 })); + +static void Try(string label, Func create) +{ + try { Console.WriteLine($"{label}: {create()}"); } + catch (Exception e) + { + Console.WriteLine($"{label}: {e.GetType().Name}: {e.Message}"); + Console.WriteLine($" inner: {(e.InnerException is { } inner ? inner.GetType().Name + ": " + inner.Message : "none")}"); + } +} + +class OnlyInt +{ + private readonly int _value; + public OnlyInt(int value) => _value = value; + public override string ToString() => $"OnlyInt {_value}"; +} + +class NoPublic +{ + private NoPublic(int value) => Console.WriteLine(value); +} diff --git a/tests/samples/1564_activator_missing_constructor_inner.expected b/tests/samples/1564_activator_missing_constructor_inner.expected new file mode 100644 index 00000000..0f47e41b --- /dev/null +++ b/tests/samples/1564_activator_missing_constructor_inner.expected @@ -0,0 +1,9 @@ +MemoryStream(Stream): MissingMethodException: Constructor on type 'System.IO.MemoryStream' not found. + inner: MissingMethodException: Member not found. +OnlyInt(string): MissingMethodException: Constructor on type 'OnlyInt' not found. + inner: MissingMethodException: Member not found. +OnlyInt(int, int): MissingMethodException: Constructor on type 'OnlyInt' not found. + inner: none +NoPublic(int): MissingMethodException: Constructor on type 'NoPublic' not found. + inner: none +OnlyInt(int): OnlyInt 7 diff --git a/tests/samples/1565_exception_inner_parameter_names.cs b/tests/samples/1565_exception_inner_parameter_names.cs new file mode 100644 index 00000000..7818dad9 --- /dev/null +++ b/tests/samples/1565_exception_inner_parameter_names.cs @@ -0,0 +1,21 @@ +// Framework exception constructors name their inner-exception parameter differently ("innerException", "inner", "e"); +// every one must keep it, as .NET does. +using System; +using System.Reflection; + +var cause = new InvalidOperationException("the cause"); +Show(new MissingMethodException("missing method", cause)); +Show(new MissingMemberException("missing member", cause)); +Show(new MissingFieldException("missing field", cause)); +Show(new MemberAccessException("member access", cause)); +Show(new TargetInvocationException(cause)); +Show(new TargetInvocationException("target invocation", cause)); +Show(new UriFormatException("uri format", cause)); +Show(new InvalidCastException("invalid cast", cause)); +Show(new TypeInitializationException("Some.Type", cause)); + +try { throw new MissingMethodException("thrown", new MissingMethodException("Member not found.")); } +catch (MissingMethodException e) { Show(e); } + +static void Show(Exception e) => + Console.WriteLine($"{e.GetType().Name}: {e.Message} | inner: {(e.InnerException is { } i ? i.GetType().Name + ": " + i.Message : "none")}"); diff --git a/tests/samples/1565_exception_inner_parameter_names.expected b/tests/samples/1565_exception_inner_parameter_names.expected new file mode 100644 index 00000000..27d594b5 --- /dev/null +++ b/tests/samples/1565_exception_inner_parameter_names.expected @@ -0,0 +1,10 @@ +MissingMethodException: missing method | inner: InvalidOperationException: the cause +MissingMemberException: missing member | inner: InvalidOperationException: the cause +MissingFieldException: missing field | inner: InvalidOperationException: the cause +MemberAccessException: member access | inner: InvalidOperationException: the cause +TargetInvocationException: Exception has been thrown by the target of an invocation. | inner: InvalidOperationException: the cause +TargetInvocationException: target invocation | inner: InvalidOperationException: the cause +UriFormatException: uri format | inner: InvalidOperationException: the cause +InvalidCastException: invalid cast | inner: InvalidOperationException: the cause +TypeInitializationException: The type initializer for 'Some.Type' threw an exception. | inner: InvalidOperationException: the cause +MissingMethodException: thrown | inner: MissingMethodException: Member not found. diff --git a/tests/samples/1567_named_pipes.cs b/tests/samples/1567_named_pipes.cs new file mode 100644 index 00000000..2b43dea3 --- /dev/null +++ b/tests/samples/1567_named_pipes.cs @@ -0,0 +1,47 @@ +// Named and anonymous pipes from System.IO.Pipes: a server and a client in one process, over a Unix domain socket on Unix. +using System; +using System.IO; +using System.IO.Pipes; +using System.Text; +using System.Threading.Tasks; + +var name = "csharpc-pipe-" + Environment.ProcessId; +using (var server = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) +using (var client = new NamedPipeClientStream(".", name, PipeDirection.InOut, PipeOptions.Asynchronous)) +{ + var accept = server.WaitForConnectionAsync(); + await client.ConnectAsync(5000); + await accept; + Console.WriteLine($"connected: server {server.IsConnected}, client {client.IsConnected}"); + Console.WriteLine($"can read/write: {client.CanRead}/{client.CanWrite}, transmission {client.TransmissionMode}"); + + var request = Encoding.UTF8.GetBytes("ping from client"); + await client.WriteAsync(request); + var buffer = new byte[64]; + var read = await server.ReadAsync(buffer); + Console.WriteLine($"server got: {Encoding.UTF8.GetString(buffer, 0, read)}"); + + using (var writer = new StreamWriter(server, leaveOpen: true) { AutoFlush = true }) + using (var reader = new StreamReader(client, leaveOpen: true)) + { + await writer.WriteLineAsync("pong from server"); + Console.WriteLine($"client got: {await reader.ReadLineAsync()}"); + } + + server.Disconnect(); + Console.WriteLine($"after disconnect: server {server.IsConnected}"); + Console.WriteLine($"client read after disconnect: {client.Read(buffer, 0, buffer.Length)}"); +} + +using (var parent = new AnonymousPipeServerStream(PipeDirection.Out)) +using (var child = new AnonymousPipeClientStream(PipeDirection.In, parent.ClientSafePipeHandle)) +{ + parent.Write(Encoding.ASCII.GetBytes("anonymous")); + var bytes = new byte[9]; + var total = 0; + while (total < bytes.Length) total += child.Read(bytes, total, bytes.Length - total); + Console.WriteLine($"anonymous: {Encoding.ASCII.GetString(bytes)} ({parent.TransmissionMode}, {child.ReadMode})"); +} + +try { new NamedPipeClientStream(".", "csharpc-missing-" + Environment.ProcessId).Connect(50); } +catch (TimeoutException e) { Console.WriteLine($"no server: {e.GetType().Name}"); } diff --git a/tests/samples/1567_named_pipes.expected b/tests/samples/1567_named_pipes.expected new file mode 100644 index 00000000..3ef27670 --- /dev/null +++ b/tests/samples/1567_named_pipes.expected @@ -0,0 +1,8 @@ +connected: server True, client True +can read/write: True/True, transmission Byte +server got: ping from client +client got: pong from server +after disconnect: server False +client read after disconnect: 0 +anonymous: anonymous (Byte, Byte) +no server: TimeoutException diff --git a/tests/samples/1568_library_struct_default_tostring.cs b/tests/samples/1568_library_struct_default_tostring.cs new file mode 100644 index 00000000..92004abb --- /dev/null +++ b/tests/samples/1568_library_struct_default_tostring.cs @@ -0,0 +1,13 @@ +// A framework struct that does not override ToString formats as its full type name (ValueType.ToString), in interpolation, +// string.Concat and ToString alike. +using System; +using System.Threading; + +var token = CancellationToken.None; +Console.WriteLine($"token: {token}"); +Console.WriteLine("concat: " + token); +Console.WriteLine($"ToString: {token.ToString()}"); +var registration = default(CancellationTokenRegistration); +Console.WriteLine($"registration: {registration}"); +var handle = default(RuntimeTypeHandle); +Console.WriteLine($"handle: {handle}"); diff --git a/tests/samples/1568_library_struct_default_tostring.expected b/tests/samples/1568_library_struct_default_tostring.expected new file mode 100644 index 00000000..e615f05c --- /dev/null +++ b/tests/samples/1568_library_struct_default_tostring.expected @@ -0,0 +1,5 @@ +token: System.Threading.CancellationToken +concat: System.Threading.CancellationToken +ToString: System.Threading.CancellationToken +registration: System.Threading.CancellationTokenRegistration +handle: System.RuntimeTypeHandle diff --git a/tests/samples/1569_property_setter_only_override.cs b/tests/samples/1569_property_setter_only_override.cs new file mode 100644 index 00000000..08c26a05 --- /dev/null +++ b/tests/samples/1569_property_setter_only_override.cs @@ -0,0 +1,35 @@ +// Reading a property through a type whose override has only a setter calls the nearest getter, virtually. +using System; + +var d = new Derived { Value = 5 }; +Console.WriteLine(d.Value); +Base b = d; +Console.WriteLine(b.Value); +var e = new MoreDerived { Value = 2 }; +Console.WriteLine(e.Value); +Console.WriteLine(((Derived)e).Value); + +// Compound assignments read and write through the nearest accessors, both called virtually. +d.Value += 1; +Console.WriteLine(d.Value); +e.Value += 3; +Console.WriteLine(e.Value); +Derived viaBase = new MoreDerived { Value = 1 }; +viaBase.Value++; +Console.WriteLine(viaBase.Value); + +class Base +{ + protected int stored; + public virtual int Value { get => stored; set => stored = value; } +} + +class Derived : Base +{ + public override int Value { set => stored = value * 10; } +} + +class MoreDerived : Derived +{ + public override int Value { get => stored + 1; } +} diff --git a/tests/samples/1569_property_setter_only_override.expected b/tests/samples/1569_property_setter_only_override.expected new file mode 100644 index 00000000..9ba0b761 --- /dev/null +++ b/tests/samples/1569_property_setter_only_override.expected @@ -0,0 +1,7 @@ +50 +50 +21 +21 +510 +241 +121