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

EcmaSignatureParser.cs « Ecma « TypeSystem « Common « tools « coreclr « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f2530ec8b19d7cb8e8208c0cbdbe6ca32419b54b (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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
// 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.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text;

using Internal.TypeSystem;
using System.Collections.Generic;

namespace Internal.TypeSystem.Ecma
{
    public struct EcmaSignatureParser
    {
        private TypeSystemContext _tsc;
        private Func<EntityHandle, NotFoundBehavior, TypeDesc> _typeResolver;
        private NotFoundBehavior _notFoundBehavior;
        private EcmaModule _ecmaModule;
        private BlobReader _reader;
        private ResolutionFailure _resolutionFailure;

        private Stack<int> _indexStack;
        private List<EmbeddedSignatureData> _embeddedSignatureDataList;


        public EcmaSignatureParser(TypeSystemContext tsc, Func<EntityHandle, NotFoundBehavior, TypeDesc> typeResolver, BlobReader reader, NotFoundBehavior notFoundBehavior)
        {
            _notFoundBehavior = notFoundBehavior;
            _ecmaModule = null;
            _tsc = tsc;
            _typeResolver = typeResolver;
            _reader = reader;
            _indexStack = null;
            _embeddedSignatureDataList = null;
            _resolutionFailure = null;
        }

        public EcmaSignatureParser(EcmaModule ecmaModule, BlobReader reader, NotFoundBehavior notFoundBehavior)
        {
            _notFoundBehavior = notFoundBehavior;
            _ecmaModule = ecmaModule;
            _tsc = ecmaModule.Context;
            _typeResolver = null;
            _reader = reader;
            _indexStack = null;
            _embeddedSignatureDataList = null;
            _resolutionFailure = null;
        }

        void SetResolutionFailure(ResolutionFailure failure)
        {
            if (_resolutionFailure == null)
                _resolutionFailure = failure;
        }

        public ResolutionFailure ResolutionFailure => _resolutionFailure;

        private TypeDesc ResolveHandle(EntityHandle handle)
        {
            object resolvedValue;
            if (_ecmaModule != null)
            {
                resolvedValue = _ecmaModule.GetObject(handle, _notFoundBehavior);
            }
            else
            {
                resolvedValue = _typeResolver(handle, _notFoundBehavior);
            }

            if (resolvedValue == null)
                return null;
            if (resolvedValue is ResolutionFailure failure)
            {
                SetResolutionFailure(failure);
                return null;
            }
            if (resolvedValue is TypeDesc type)
            {
                return type;
            }
            else
            {
                throw new BadImageFormatException("Type expected");
            }
        }

        private TypeDesc GetWellKnownType(WellKnownType wellKnownType)
        {
            return _tsc.GetWellKnownType(wellKnownType);
        }

        private TypeDesc ParseType(SignatureTypeCode typeCode)
        {
            if (_indexStack != null)
            {
                int was = _indexStack.Pop();
                _indexStack.Push(was + 1);
                _indexStack.Push(0);
            }
            TypeDesc result = ParseTypeImpl(typeCode);
            if (_indexStack != null)
            {
                _indexStack.Pop();
            }
            return result;
        }

        private TypeDesc ParseTypeImpl(SignatureTypeCode typeCode)
        {
            // Switch on the type.
            switch (typeCode)
            {
                case SignatureTypeCode.Void:
                    return GetWellKnownType(WellKnownType.Void);
                case SignatureTypeCode.Boolean:
                    return GetWellKnownType(WellKnownType.Boolean);
                case SignatureTypeCode.SByte:
                    return GetWellKnownType(WellKnownType.SByte);
                case SignatureTypeCode.Byte:
                    return GetWellKnownType(WellKnownType.Byte);
                case SignatureTypeCode.Int16:
                    return GetWellKnownType(WellKnownType.Int16);
                case SignatureTypeCode.UInt16:
                    return GetWellKnownType(WellKnownType.UInt16);
                case SignatureTypeCode.Int32:
                    return GetWellKnownType(WellKnownType.Int32);
                case SignatureTypeCode.UInt32:
                    return GetWellKnownType(WellKnownType.UInt32);
                case SignatureTypeCode.Int64:
                    return GetWellKnownType(WellKnownType.Int64);
                case SignatureTypeCode.UInt64:
                    return GetWellKnownType(WellKnownType.UInt64);
                case SignatureTypeCode.Single:
                    return GetWellKnownType(WellKnownType.Single);
                case SignatureTypeCode.Double:
                    return GetWellKnownType(WellKnownType.Double);
                case SignatureTypeCode.Char:
                    return GetWellKnownType(WellKnownType.Char);
                case SignatureTypeCode.String:
                    return GetWellKnownType(WellKnownType.String);
                case SignatureTypeCode.IntPtr:
                    return GetWellKnownType(WellKnownType.IntPtr);
                case SignatureTypeCode.UIntPtr:
                    return GetWellKnownType(WellKnownType.UIntPtr);
                case SignatureTypeCode.Object:
                    return GetWellKnownType(WellKnownType.Object);
                case SignatureTypeCode.TypeHandle:
                    return ResolveHandle(_reader.ReadTypeHandle());
                case SignatureTypeCode.SZArray:
                    {
                        var elementType = ParseType();
                        if (elementType == null)
                            return null;
                        return _tsc.GetArrayType(elementType);
                    }
                case SignatureTypeCode.Array:
                    {
                        var elementType = ParseType();
                        var rank = _reader.ReadCompressedInteger();

                        if (_embeddedSignatureDataList != null)
                        {
                            var boundsCount = _reader.ReadCompressedInteger();
                            int []bounds = boundsCount > 0 ? new int[boundsCount] : Array.Empty<int>();
                            for (int i = 0; i < boundsCount; i++)
                                bounds[i] = _reader.ReadCompressedInteger();

                            var lowerBoundsCount = _reader.ReadCompressedInteger();
                            int []lowerBounds = lowerBoundsCount > 0 ? new int[lowerBoundsCount] : Array.Empty<int>();
                            bool nonZeroLowerBounds = false;
                            for (int j = 0; j < lowerBoundsCount; j++)
                            {
                                int loBound = _reader.ReadCompressedSignedInteger();
                                if (loBound != 0)
                                    nonZeroLowerBounds = true;
                                lowerBounds[j] = loBound;
                            }

                            if (boundsCount != 0 || lowerBoundsCount != rank || nonZeroLowerBounds)
                            {
                                StringBuilder arrayShapeString = new StringBuilder();
                                arrayShapeString.Append(string.Join(",", bounds));
                                arrayShapeString.Append('|');
                                arrayShapeString.Append(string.Join(",", lowerBounds));
                                _embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack) + "|" + arrayShapeString.ToString(), kind = EmbeddedSignatureDataKind.ArrayShape, type = null });
                            }
                        }
                        else
                        {
                            var boundsCount = _reader.ReadCompressedInteger();
                            for (int i = 0; i < boundsCount; i++)
                                _reader.ReadCompressedInteger();
                            var lowerBoundsCount = _reader.ReadCompressedInteger();
                            for (int j = 0; j < lowerBoundsCount; j++)
                                _reader.ReadCompressedSignedInteger();
                        }

                        if (elementType != null)
                            return _tsc.GetArrayType(elementType, rank);
                        else
                            return null;
                    }
                case SignatureTypeCode.ByReference:
                    {
                        TypeDesc byRefedType = ParseType();
                        if (byRefedType != null)
                            return byRefedType.MakeByRefType();
                        else
                            return null;
                    }
                case SignatureTypeCode.Pointer:
                    {
                        TypeDesc pointedAtType = ParseType();
                        if (pointedAtType != null)
                            return _tsc.GetPointerType(pointedAtType);
                        else
                            return null;
                    }
                case SignatureTypeCode.GenericTypeParameter:
                    return _tsc.GetSignatureVariable(_reader.ReadCompressedInteger(), false);
                case SignatureTypeCode.GenericMethodParameter:
                    return _tsc.GetSignatureVariable(_reader.ReadCompressedInteger(), true);
                case SignatureTypeCode.GenericTypeInstance:
                    {
                        TypeDesc typeDef = ParseType();
                        MetadataType metadataTypeDef = null;

                        if (typeDef != null)
                        {
                            metadataTypeDef = typeDef as MetadataType;
                            if (metadataTypeDef == null)
                                throw new BadImageFormatException();
                        }

                        TypeDesc[] instance = new TypeDesc[_reader.ReadCompressedInteger()];
                        for (int i = 0; i < instance.Length; i++)
                        {
                            instance[i] = ParseType();
                            if (instance[i] == null)
                                metadataTypeDef = null;
                        }

                        if (metadataTypeDef != null)
                            return _tsc.GetInstantiatedType(metadataTypeDef, new Instantiation(instance));
                        else
                            return null;
                    }
                case SignatureTypeCode.TypedReference:
                    return GetWellKnownType(WellKnownType.TypedReference);
                case SignatureTypeCode.FunctionPointer:
                    MethodSignature sig = ParseMethodSignatureInternal(skipEmbeddedSignatureData: true);
                    if (sig != null)
                        return _tsc.GetFunctionPointerType(sig);
                    else
                        return null;
                default:
                    ThrowHelper.ThrowBadImageFormatException();
                    return null;
            }
        }

        private SignatureTypeCode ParseTypeCode(bool skipPinned = true)
        {
            if (_indexStack != null)
            {
                int was = _indexStack.Pop();
                _indexStack.Push(was + 1);
                _indexStack.Push(0);
            }
            SignatureTypeCode result = ParseTypeCodeImpl(skipPinned);
            if (_indexStack != null)
            {
                _indexStack.Pop();
            }
            return result;
        }

        private SignatureTypeCode ParseTypeCodeImpl(bool skipPinned = true)
        {
            for (; ; )
            {
                SignatureTypeCode typeCode = _reader.ReadSignatureTypeCode();

                if (typeCode == SignatureTypeCode.RequiredModifier)
                {
                    EntityHandle typeHandle = _reader.ReadTypeHandle();
                    if (_embeddedSignatureDataList != null)
                    {
                        _embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.RequiredCustomModifier, type = ResolveHandle(typeHandle) });
                    }
                    continue;
                }

                if (typeCode == SignatureTypeCode.OptionalModifier)
                {
                    EntityHandle typeHandle = _reader.ReadTypeHandle();
                    if (_embeddedSignatureDataList != null)
                    {
                        _embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.OptionalCustomModifier, type = ResolveHandle(typeHandle) });
                    }
                    continue;
                }

                // TODO: treat PINNED in the signature same as modopts (it matters
                // in signature matching - you can actually define overloads on this)
                if (skipPinned && typeCode == SignatureTypeCode.Pinned)
                {
                    continue;
                }

                return typeCode;
            }
        }

        public TypeDesc ParseType()
        {
            if (_indexStack != null)
            {
                int was = _indexStack.Pop();
                _indexStack.Push(was + 1);
                _indexStack.Push(0);
            }
            TypeDesc result = ParseTypeImpl();
            if (_indexStack != null)
            {
                _indexStack.Pop();
            }
            return result;
        }

        private TypeDesc ParseTypeImpl()
        {
            return ParseType(ParseTypeCode());
        }

        public bool IsFieldSignature
        {
            get
            {
                BlobReader peek = _reader;
                return peek.ReadSignatureHeader().Kind == SignatureKind.Field;
            }
        }

        public MethodSignature ParseMethodSignature()
        {
            try
            {
                _indexStack = new Stack<int>();
                _indexStack.Push(0);
                _embeddedSignatureDataList = new List<EmbeddedSignatureData>();
                return ParseMethodSignatureInternal(skipEmbeddedSignatureData: false);
            }
            finally
            {
                _indexStack = null;
                _embeddedSignatureDataList = null;
            }

        }

        private MethodSignature ParseMethodSignatureInternal(bool skipEmbeddedSignatureData)
        {
            if (_indexStack != null)
            {
                int was = _indexStack.Pop();
                _indexStack.Push(was + 1);
                _indexStack.Push(0);
            }
            MethodSignature result = ParseMethodSignatureImpl(skipEmbeddedSignatureData);
            if (_indexStack != null)
            {
                _indexStack.Pop();
            }
            return result;
        }

        private MethodSignature ParseMethodSignatureImpl(bool skipEmbeddedSignatureData)
        {
            SignatureHeader header = _reader.ReadSignatureHeader();

            MethodSignatureFlags flags = 0;

            SignatureCallingConvention signatureCallConv = header.CallingConvention;
            if (signatureCallConv != SignatureCallingConvention.Default)
            {
                // Verify that it is safe to convert CallingConvention to MethodSignatureFlags via a simple cast
                Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConventionCdecl == (int)SignatureCallingConvention.CDecl);
                Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConventionStdCall == (int)SignatureCallingConvention.StdCall);
                Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConventionThisCall == (int)SignatureCallingConvention.ThisCall);
                Debug.Assert((int)MethodSignatureFlags.CallingConventionVarargs == (int)SignatureCallingConvention.VarArgs);
                Debug.Assert((int)MethodSignatureFlags.UnmanagedCallingConvention == (int)SignatureCallingConvention.Unmanaged);

                flags = (MethodSignatureFlags)signatureCallConv;
            }

            if (!header.IsInstance)
                flags |= MethodSignatureFlags.Static;

            int arity = header.IsGeneric ? _reader.ReadCompressedInteger() : 0;

            int count = _reader.ReadCompressedInteger();

            TypeDesc returnType = ParseType();
            TypeDesc[] parameters;

            if (count > 0)
            {
                // Get all of the parameters.
                parameters = new TypeDesc[count];
                for (int i = 0; i < count; i++)
                {
                    parameters[i] = ParseType();
                }
            }
            else
            {
                parameters = TypeDesc.EmptyTypes;
            }

            EmbeddedSignatureData[] embeddedSignatureDataArray = (_embeddedSignatureDataList == null || _embeddedSignatureDataList.Count == 0 || skipEmbeddedSignatureData) ? null : _embeddedSignatureDataList.ToArray();

            if (_resolutionFailure == null)
                return new MethodSignature(flags, arity, returnType, parameters, embeddedSignatureDataArray);
            else
                return null;

        }

        public PropertySignature ParsePropertySignature()
        {
            // As PropertySignature is a struct, we cannot return null
            if (_notFoundBehavior != NotFoundBehavior.Throw)
                throw new ArgumentException();

            SignatureHeader header = _reader.ReadSignatureHeader();
            if (header.Kind != SignatureKind.Property)
                throw new BadImageFormatException();

            bool isStatic = !header.IsInstance;

            int count = _reader.ReadCompressedInteger();

            TypeDesc returnType = ParseType();
            TypeDesc[] parameters;

            if (count > 0)
            {
                // Get all of the parameters.
                parameters = new TypeDesc[count];
                for (int i = 0; i < count; i++)
                {
                    parameters[i] = ParseType();
                }
            }
            else
            {
                parameters = TypeDesc.EmptyTypes;
            }

            return new PropertySignature(isStatic, parameters, returnType);
        }

        public TypeDesc ParseFieldSignature()
        {
            if (_reader.ReadSignatureHeader().Kind != SignatureKind.Field)
                throw new BadImageFormatException();

            return ParseType();
        }

        public TypeDesc ParseFieldSignature(out EmbeddedSignatureData[] embeddedSigData)
        {
            try
            {
                _indexStack = new Stack<int>();
                _indexStack.Push(1);
                _indexStack.Push(0);
                _embeddedSignatureDataList = new List<EmbeddedSignatureData>();
                TypeDesc parsedType = ParseFieldSignature();
                embeddedSigData = _embeddedSignatureDataList.Count == 0 ? null : _embeddedSignatureDataList.ToArray();
                return parsedType;
            }
            finally
            {
                _indexStack = null;
                _embeddedSignatureDataList = null;
            }
        }

        public LocalVariableDefinition[] ParseLocalsSignature()
        {
            if (_reader.ReadSignatureHeader().Kind != SignatureKind.LocalVariables)
                throw new BadImageFormatException();

            int count = _reader.ReadCompressedInteger();

            LocalVariableDefinition[] locals;

            if (count > 0)
            {
                locals = new LocalVariableDefinition[count];
                for (int i = 0; i < count; i++)
                {
                    bool isPinned = false;

                    SignatureTypeCode typeCode = ParseTypeCode(skipPinned: false);
                    if (typeCode == SignatureTypeCode.Pinned)
                    {
                        isPinned = true;
                        typeCode = ParseTypeCode();
                    }

                    locals[i] = new LocalVariableDefinition(ParseType(typeCode), isPinned);
                }
            }
            else
            {
                locals = Array.Empty<LocalVariableDefinition>();
            }
            if (_resolutionFailure == null)
                return locals;
            else
                return null;
        }

        public TypeDesc[] ParseMethodSpecSignature()
        {
            if (_reader.ReadSignatureHeader().Kind != SignatureKind.MethodSpecification)
                throw new BadImageFormatException();

            int count = _reader.ReadCompressedInteger();

            if (count <= 0)
                throw new BadImageFormatException();

            TypeDesc[] arguments = new TypeDesc[count];
            for (int i = 0; i < count; i++)
            {
                arguments[i] = ParseType();
            }
            if (_resolutionFailure == null)
                return arguments;
            else
                return null;
        }

        public MarshalAsDescriptor ParseMarshalAsDescriptor()
        {
            Debug.Assert(_reader.RemainingBytes != 0);

            NativeTypeKind type = (NativeTypeKind)_reader.ReadByte();
            NativeTypeKind arraySubType = NativeTypeKind.Default;
            uint? paramNum = null, numElem = null;
            string cookie = null;
            TypeDesc marshallerType = null;

            switch (type)
            {
                case NativeTypeKind.Array:
                    {
                        if (_reader.RemainingBytes != 0)
                        {
                            arraySubType = (NativeTypeKind)_reader.ReadByte();
                        }

                        if (_reader.RemainingBytes != 0)
                        {
                            paramNum = (uint)_reader.ReadCompressedInteger();
                        }

                        if (_reader.RemainingBytes != 0)
                        {
                            numElem = (uint)_reader.ReadCompressedInteger();
                        }

                        if (_reader.RemainingBytes != 0)
                        {
                            int flag = _reader.ReadCompressedInteger();
                            if (flag == 0)
                            {
                                paramNum = null; //paramNum is just a place holder so that numElem can be present
                            }
                        }

                    }
                    break;
                case NativeTypeKind.ByValArray:
                    {
                        if (_reader.RemainingBytes != 0)
                        {
                            numElem = (uint)_reader.ReadCompressedInteger();
                        }

                        if (_reader.RemainingBytes != 0)
                        {
                            arraySubType = (NativeTypeKind)_reader.ReadByte();
                        }
                    }
                    break;
                case NativeTypeKind.ByValTStr:
                    {
                        if (_reader.RemainingBytes != 0)
                        {
                            numElem = (uint)_reader.ReadCompressedInteger();
                        }
                    }
                    break;
                case NativeTypeKind.SafeArray:
                    {
                        // There's nobody to consume SafeArrays, so let's just parse the data
                        // to avoid asserting later.

                        // Get optional VARTYPE for the element
                        if (_reader.RemainingBytes != 0)
                        {
                            _reader.ReadCompressedInteger();
                        }

                        // VARTYPE can be followed by optional type name
                        if (_reader.RemainingBytes != 0)
                        {
                            _reader.ReadSerializedString();
                        }
                    }
                    break;
                case NativeTypeKind.CustomMarshaler:
                    {
                        // Read typelib guid
                        _reader.ReadSerializedString();

                        // Read native type name
                        _reader.ReadSerializedString();

                        // Read managed marshaler name
                        var customMarshallerTypeName = _reader.ReadSerializedString();
                        marshallerType = _ecmaModule.GetTypeByCustomAttributeTypeName(customMarshallerTypeName, true);

                        // Read cookie
                        cookie = _reader.ReadSerializedString();
                    }
                    break;
                default:
                    break;
            }

            Debug.Assert(_reader.RemainingBytes == 0);

            return new MarshalAsDescriptor(type, arraySubType, paramNum, numElem, marshallerType, cookie);
        }
    }
}