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

StructMarshallingThunk.cs « Stubs « IL « TypeSystem « src « Common « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e5360b37c48445006a8e8b11631f91bc1295ddd4 (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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.TypeSystem;
using Internal.TypeSystem.Interop;
using Debug = System.Diagnostics.Debug;

namespace Internal.IL.Stubs
{
    public enum StructMarshallingThunkType : byte
    {
        ManagedToNative = 1,
        NativeToManaged = 2,
        Cleanup = 4
    }

    public struct InlineArrayCandidate
    {
        public readonly MetadataType ElementType;
        public readonly uint Length;

        public InlineArrayCandidate(MetadataType type, uint length)
        {
            ElementType = type;
            Length = length;
        }
    }

    public partial class StructMarshallingThunk : ILStubMethod
    {
        internal readonly MetadataType ManagedType;
        internal readonly NativeStructType NativeType;
        internal readonly StructMarshallingThunkType ThunkType;
        private  InteropStateManager _interopStateManager;
        private TypeDesc _owningType;
        private Marshaller[] _marshallers;

        public StructMarshallingThunk(TypeDesc owningType, MetadataType managedType, StructMarshallingThunkType thunkType, InteropStateManager interopStateManager)
        {
            _owningType = owningType;
            ManagedType = managedType;
            _interopStateManager = interopStateManager;
            NativeType = _interopStateManager.GetStructMarshallingNativeType(managedType);
            ThunkType = thunkType;
            _marshallers = InitializeMarshallers();
        }

        public override TypeSystemContext Context
        {
            get
            {
                return ManagedType.Context;
            }
        }

        public override TypeDesc OwningType
        {
            get
            {
                return _owningType;
            }
        }

        private MethodSignature _signature;
        public override MethodSignature Signature
        {
            get
            {
                if (_signature == null)
                {
                    TypeDesc[] parameters = null;
                    switch (ThunkType)
                    {
                        case StructMarshallingThunkType.ManagedToNative:
                            parameters = new TypeDesc[] {
                                ManagedType.IsValueType ? (TypeDesc)ManagedType.MakeByRefType() : ManagedType,
                                NativeType.MakeByRefType()
                            };
                            break;
                        case StructMarshallingThunkType.NativeToManaged:
                            parameters = new TypeDesc[] {
                                NativeType.MakeByRefType(),
                                ManagedType.IsValueType ? (TypeDesc)ManagedType.MakeByRefType() : ManagedType
                            };
                            break;
                        case StructMarshallingThunkType.Cleanup:
                            parameters = new TypeDesc[] {
                                NativeType.MakeByRefType()
                            };
                            break;
                        default:
                            System.Diagnostics.Debug.Fail("Unexpected Struct marshalling thunk type");
                            break;
                    }
                    _signature = new MethodSignature(MethodSignatureFlags.Static, 0, Context.GetWellKnownType(WellKnownType.Void), parameters);
                }
                return _signature;
            }
        }

        private string NamePrefix
        {
            get
            {
                switch (ThunkType)
                {
                    case StructMarshallingThunkType.ManagedToNative:
                        return "ManagedToNative";
                    case StructMarshallingThunkType.NativeToManaged:
                        return "NativeToManaged";
                    case StructMarshallingThunkType.Cleanup:
                        return "Cleanup";
                    default:
                        System.Diagnostics.Debug.Fail("Unexpected Struct marshalling thunk type");
                        return string.Empty;
                }
            }
        }

        public override string Name
        {
            get
            {
                return NamePrefix + "__" + ((MetadataType)ManagedType).Name;
            }
        }

        private Marshaller[] InitializeMarshallers()
        {
            Debug.Assert(_interopStateManager != null);
            MarshalAsDescriptor[] marshalAsDescriptors = ((MetadataType)ManagedType).GetFieldMarshalAsDescriptors();
            Marshaller[] marshallers = new Marshaller[marshalAsDescriptors.Length];

            PInvokeFlags flags = new PInvokeFlags();
            if (ManagedType.PInvokeStringFormat == PInvokeStringFormat.UnicodeClass || ManagedType.PInvokeStringFormat == PInvokeStringFormat.AutoClass)
            {
                flags.CharSet = CharSet.Unicode;
            }
            else
            {
                flags.CharSet = CharSet.Ansi;
            }

            int index = 0;

            foreach (FieldDesc field in ManagedType.GetFields())
            {
                if (field.IsStatic)
                {
                    continue;
                }

                marshallers[index] = Marshaller.CreateMarshaller(field.FieldType,
                                                                    MarshallerType.Field,
                                                                    marshalAsDescriptors[index],
                                                                    (ThunkType == StructMarshallingThunkType.NativeToManaged) ? MarshalDirection.Reverse : MarshalDirection.Forward,
                                                                    marshallers,
                                                                    _interopStateManager,
                                                                    index,
                                                                    flags,
                                                                    isIn: true,     /* Struct fields are considered as IN within the helper*/
                                                                    isOut: false,
                                                                    isReturn: false);
                index++;
            }

            return marshallers;
        }

        private MethodIL EmitMarshallingIL(PInvokeILCodeStreams pInvokeILCodeStreams)
        {
            ILEmitter emitter = pInvokeILCodeStreams.Emitter;

            IEnumerator<FieldDesc> nativeEnumerator = NativeType.GetFields().GetEnumerator();

            int index = 0;
            foreach (var managedField in ManagedType.GetFields())
            {
                if (managedField.IsStatic)
                {
                    continue;
                }

                bool notEmpty = nativeEnumerator.MoveNext();
                Debug.Assert(notEmpty == true);

                var nativeField = nativeEnumerator.Current;
                Debug.Assert(nativeField != null);
                bool isInlineArray = nativeField.FieldType is InlineArrayType;
                //
                // Field marshallers expects the value of the fields to be 
                // loaded on the stack. We load the value on the stack
                // before calling the marshallers.
                // Only exception is ByValArray marshallers. Since they can
                // only be used for field marshalling, they load/store values 
                // directly from arguments.
                //

                if (isInlineArray)
                {
                    var byValMarshaller = _marshallers[index++] as ByValArrayMarshaller;

                    Debug.Assert(byValMarshaller != null);

                    byValMarshaller.EmitMarshallingIL(pInvokeILCodeStreams, managedField, nativeField);
                }
                else
                {
                    if (ThunkType == StructMarshallingThunkType.ManagedToNative)
                    {
                        LoadFieldValueFromArg(0, managedField, pInvokeILCodeStreams);
                    }
                    else if (ThunkType == StructMarshallingThunkType.NativeToManaged)
                    {
                        LoadFieldValueFromArg(0, nativeField, pInvokeILCodeStreams);
                    }

                    _marshallers[index++].EmitMarshallingIL(pInvokeILCodeStreams);

                    if (ThunkType == StructMarshallingThunkType.ManagedToNative)
                    {
                        StoreFieldValueFromArg(1, nativeField, pInvokeILCodeStreams);
                    }
                    else if (ThunkType == StructMarshallingThunkType.NativeToManaged)
                    {
                        StoreFieldValueFromArg(1, managedField, pInvokeILCodeStreams);
                    }
                }
            }

            Debug.Assert(!nativeEnumerator.MoveNext());

            pInvokeILCodeStreams.UnmarshallingCodestream.Emit(ILOpcode.ret);
            return emitter.Link(this);
        }

        private MethodIL EmitCleanupIL(PInvokeILCodeStreams pInvokeILCodeStreams)
        {
            ILEmitter emitter = pInvokeILCodeStreams.Emitter;
            ILCodeStream codeStream = pInvokeILCodeStreams.MarshallingCodeStream;
            IEnumerator<FieldDesc> nativeEnumerator = NativeType.GetFields().GetEnumerator();
            int index = 0;
            foreach (var managedField in ManagedType.GetFields())
            {
                if (managedField.IsStatic)
                {
                    continue;
                }

                bool notEmpty = nativeEnumerator.MoveNext();
                Debug.Assert(notEmpty == true);

                var nativeField = nativeEnumerator.Current;
                Debug.Assert(nativeField != null);

                if (_marshallers[index].CleanupRequired)
                {
                    LoadFieldValueFromArg(0, nativeField, pInvokeILCodeStreams);
                    _marshallers[index].EmitElementCleanup(codeStream, emitter);
                }
                index++;
            }

            pInvokeILCodeStreams.UnmarshallingCodestream.Emit(ILOpcode.ret);
            return emitter.Link(this);
        }

        public override MethodIL EmitIL()
        {
            try
            {
                PInvokeILCodeStreams pInvokeILCodeStreams = new PInvokeILCodeStreams();

                if (ThunkType == StructMarshallingThunkType.Cleanup)
                {
                    return EmitCleanupIL(pInvokeILCodeStreams);
                }
                else
                {
                    return EmitMarshallingIL(pInvokeILCodeStreams);
                }
            }
            catch (NotSupportedException)
            {
                string message = "Struct '" + ((MetadataType)ManagedType).Name +
                    "' requires non-trivial marshalling that is not yet supported by this compiler.";
                return MarshalHelpers.EmitExceptionBody(message, this);
            }
            catch (InvalidProgramException ex)
            {
                Debug.Assert(!String.IsNullOrEmpty(ex.Message));
                return MarshalHelpers.EmitExceptionBody(ex.Message, this);
            }
        }

        /// <summary>
        /// Loads the value of field of a struct at argument index argIndex to stack
        /// </summary>
        private void LoadFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams)
        {
            ILCodeStream stream = pInvokeILCodeStreams.MarshallingCodeStream;
            ILEmitter emitter = pInvokeILCodeStreams.Emitter;
            stream.EmitLdArg(argIndex);
            stream.Emit(ILOpcode.ldfld, emitter.NewToken(field));
        }

        private void StoreFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams)
        {
            ILCodeStream stream = pInvokeILCodeStreams.MarshallingCodeStream;
            ILEmitter emitter = pInvokeILCodeStreams.Emitter;
            Internal.IL.Stubs.ILLocalVariable var = emitter.NewLocal(field.FieldType);

            stream.EmitStLoc(var);

            stream.EmitLdArg(argIndex);
            stream.EmitLdLoc(var);
            stream.Emit(ILOpcode.stfld, emitter.NewToken(field));
        }
    }
}