Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PInvokeMethodFixupNode.cs « DependencyAnalysis « Compiler « ILCompiler.Compiler « aot « tools « coreclr « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 92240c4e8c6d45a82489187b5ac76d9cd2a49adc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

using Internal.IL.Stubs;
using Internal.Runtime;
using Internal.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.TypeSystem.Interop;

namespace ILCompiler.DependencyAnalysis
{
    /// <summary>
    /// Represents a single PInvoke MethodFixupCell as defined in the core library.
    /// </summary>
    public class PInvokeMethodFixupNode : ObjectNode, ISymbolDefinitionNode
    {
        private readonly PInvokeMethodData _pInvokeMethodData;

        public PInvokeMethodFixupNode(PInvokeMethodData pInvokeMethodData)
        {
            _pInvokeMethodData = pInvokeMethodData;
        }

        public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
        {
            sb.Append("__pinvoke_");
            _pInvokeMethodData.AppendMangledName(nameMangler, sb);
        }
        public int Offset => 0;
        public override bool IsShareable => true;

        protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);

        public override ObjectNodeSection GetSection(NodeFactory factory) => ObjectNodeSection.DataSection;

        public override bool StaticDependenciesAreComputed => true;

        public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
        {
            ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly);
            builder.RequireInitialPointerAlignment();

            builder.AddSymbol(this);

            //
            // Emit a MethodFixupCell struct
            //

            // Address (to be fixed up at runtime)
            builder.EmitZeroPointer();

            // Entry point name
            string entryPointName = _pInvokeMethodData.EntryPointName;
            if (factory.Target.IsWindows && entryPointName.StartsWith("#", StringComparison.OrdinalIgnoreCase))
            {
                // Windows-specific ordinal import
                // CLR-compatible behavior: Strings that can't be parsed as a signed integer are treated as zero.
                int entrypointOrdinal;
                if (!int.TryParse(entryPointName.AsSpan(1), out entrypointOrdinal))
                    entrypointOrdinal = 0;

                // CLR-compatible behavior: Ordinal imports are 16-bit on Windows. Discard rest of the bits.
                builder.EmitNaturalInt((ushort)entrypointOrdinal);
            }
            else
            {
                // Import by name
                builder.EmitPointerReloc(factory.ConstantUtf8String(entryPointName));
            }

            // Module fixup cell
            builder.EmitPointerReloc(factory.PInvokeModuleFixup(_pInvokeMethodData.ModuleData));

            int flags = 0;

            int charsetFlags = (int)_pInvokeMethodData.CharSetMangling;
            Debug.Assert((charsetFlags & MethodFixupCellFlagsConstants.CharSetMask) == charsetFlags);
            charsetFlags &= MethodFixupCellFlagsConstants.CharSetMask;
            flags |= charsetFlags;

            int? objcFunction = MarshalHelpers.GetObjectiveCMessageSendFunction(factory.Target, _pInvokeMethodData.ModuleData.ModuleName, _pInvokeMethodData.EntryPointName);
            if (objcFunction.HasValue)
            {
                flags |= MethodFixupCellFlagsConstants.IsObjectiveCMessageSendMask;

                int objcFunctionFlags = objcFunction.Value << MethodFixupCellFlagsConstants.ObjectiveCMessageSendFunctionShift;
                Debug.Assert((objcFunctionFlags & MethodFixupCellFlagsConstants.ObjectiveCMessageSendFunctionMask) == objcFunctionFlags);
                objcFunctionFlags &= MethodFixupCellFlagsConstants.ObjectiveCMessageSendFunctionMask;
                flags |= objcFunctionFlags;
            }

            builder.EmitInt(flags);

            return builder.ToObjectData();
        }

        public override int ClassCode => -1592006940;

        public override int CompareToImpl(ISortableNode other, CompilerComparer comparer)
        {
            return _pInvokeMethodData.CompareTo(((PInvokeMethodFixupNode)other)._pInvokeMethodData, comparer);
        }
    }

    public readonly struct PInvokeMethodData : IEquatable<PInvokeMethodData>
    {
        public readonly PInvokeModuleData ModuleData;
        public readonly string EntryPointName;
        public readonly CharSet CharSetMangling;

        public PInvokeMethodData(PInvokeLazyFixupField pInvokeLazyFixupField)
        {
            PInvokeMetadata metadata = pInvokeLazyFixupField.PInvokeMetadata;
            ModuleDesc declaringModule = ((MetadataType)pInvokeLazyFixupField.TargetMethod.OwningType).Module;

            DllImportSearchPath? dllImportSearchPath = default;
            if (declaringModule.Assembly is EcmaAssembly asm)
            {
                // We look for [assembly:DefaultDllImportSearchPaths(...)]
                var attrHandle = asm.MetadataReader.GetCustomAttributeHandle(asm.AssemblyDefinition.GetCustomAttributes(),
                    "System.Runtime.InteropServices", "DefaultDllImportSearchPathsAttribute");
                if (!attrHandle.IsNil)
                {
                    var attr = asm.MetadataReader.GetCustomAttribute(attrHandle);
                    var decoded = attr.DecodeValue(new CustomAttributeTypeProvider(asm));
                    if (decoded.FixedArguments.Length == 1 &&
                        decoded.FixedArguments[0].Value is int searchPath)
                    {
                        dllImportSearchPath = (DllImportSearchPath)searchPath;
                    }
                }
            }
            ModuleData = new PInvokeModuleData(metadata.Module, dllImportSearchPath, declaringModule);

            EntryPointName = metadata.Name;

            CharSet charSetMangling = default;
            if (declaringModule.Context.Target.IsWindows && !metadata.Flags.ExactSpelling)
            {
                // Mirror CharSet normalization from Marshaller.CreateMarshaller
                bool isAnsi = metadata.Flags.CharSet switch
                {
                    CharSet.Ansi => true,
                    CharSet.Unicode => false,
                    CharSet.Auto => false,
                    _ => true
                };

                charSetMangling = isAnsi ? CharSet.Ansi : CharSet.Unicode;
            }
            CharSetMangling = charSetMangling;
        }

        public bool Equals(PInvokeMethodData other)
        {
            return ModuleData.Equals(other.ModuleData) &&
                EntryPointName == other.EntryPointName &&
                CharSetMangling == other.CharSetMangling;
        }

        public override bool Equals(object obj)
        {
            return obj is PInvokeMethodData other && Equals(other);
        }

        public override int GetHashCode()
        {
            return ModuleData.GetHashCode() ^ EntryPointName.GetHashCode();
        }

        public int CompareTo(PInvokeMethodData other, CompilerComparer comparer)
        {
            var entryPointCompare = StringComparer.Ordinal.Compare(EntryPointName, other.EntryPointName);
            if (entryPointCompare != 0)
                return entryPointCompare;

            var moduleCompare = ModuleData.CompareTo(other.ModuleData, comparer);
            if (moduleCompare != 0)
                return moduleCompare;

            return CharSetMangling.CompareTo(other.CharSetMangling);
        }

        public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
        {
            ModuleData.AppendMangledName(nameMangler, sb);
            sb.Append("__");
            sb.Append(EntryPointName);
            if (CharSetMangling != default)
            {
                sb.Append("__");
                sb.Append(CharSetMangling.ToString());
            }
        }
    }
}