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

AssemblyBinderImplementation.cs « Execution « Reflection « Internal « src « System.Private.TypeLoader « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e2fcc6a579ae9702900779cb01733d7b4390d172 (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
// 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.IO;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;

using System.Reflection.Runtime.General;

using Internal.Reflection.Core;
using Internal.Runtime.TypeLoader;

using Internal.Metadata.NativeFormat;

namespace Internal.Reflection.Execution
{
    //=============================================================================================================================
    // The assembly resolution policy for Project N's emulation of "classic reflection."
    //
    // The policy is very simple: the only assemblies that can be "loaded" are those that are statically linked into the running
    // native process. There is no support for probing for assemblies in directories, user-supplied files, GACs, NICs or any
    // other repository.
    //=============================================================================================================================
    public sealed partial class AssemblyBinderImplementation : AssemblyBinder
    {
        private AssemblyBinderImplementation()
        {
            _scopeGroups = new KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[0];
            ModuleList.AddModuleRegistrationCallback(RegisterModule);
        }

        public static AssemblyBinderImplementation Instance { get; } = new AssemblyBinderImplementation();

        partial void BindEcmaByteArray(byte[] rawAssembly, byte[] rawSymbolStore, ref AssemblyBindResult bindResult, ref Exception exception, ref bool? result);
        partial void BindEcmaAssemblyName(RuntimeAssemblyName refName, bool cacheMissedLookups, ref AssemblyBindResult result, ref Exception exception, ref Exception preferredException, ref bool resultBoolean);
        partial void InsertEcmaLoadedAssemblies(List<AssemblyBindResult> loadedAssemblies);

        public sealed override bool Bind(byte[] rawAssembly, byte[] rawSymbolStore, out AssemblyBindResult bindResult, out Exception exception)
        {
            bool? result = null;
            exception = null;
            bindResult = default(AssemblyBindResult);

            BindEcmaByteArray(rawAssembly, rawSymbolStore, ref bindResult, ref exception, ref result);

            // If the Ecma assembly binder isn't linked in, simply throw PlatformNotSupportedException
            if (!result.HasValue)
                throw new PlatformNotSupportedException();
            else
                return result.Value;
        }

        public sealed override bool Bind(RuntimeAssemblyName refName, bool cacheMissedLookups, out AssemblyBindResult result, out Exception exception)
        {
            bool foundMatch = false;
            result = default(AssemblyBindResult);
            exception = null;

            Exception preferredException = null;

            refName = refName.CanonicalizePublicKeyToken();

            // At least one real-world app calls Type.GetType() for "char" using the assembly name "mscorlib". To accomodate this,
            // we will adopt the desktop CLR rule that anything named "mscorlib" automatically binds to the core assembly.
            bool useMscorlibNameCompareFunc = false;
            RuntimeAssemblyName compareRefName = refName;
            if (refName.Name == "mscorlib")
            {
                useMscorlibNameCompareFunc = true;
                compareRefName = AssemblyNameParser.Parse(AssemblyBinder.DefaultAssemblyNameForGetType);
            }

            foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> group in ScopeGroups)
            {
                bool nameMatches;
                if (useMscorlibNameCompareFunc)
                {
                    nameMatches = MscorlibAssemblyNameMatches(compareRefName, group.Key);
                }
                else
                {
                    nameMatches = AssemblyNameMatches(refName, group.Key, ref preferredException);
                }

                if (nameMatches)
                {
                    if (foundMatch)
                    {
                        exception = new AmbiguousMatchException();
                        return false;
                    }

                    foundMatch = true;
                    ScopeDefinitionGroup scopeDefinitionGroup = group.Value;

                    result.Reader = scopeDefinitionGroup.CanonicalScope.Reader;
                    result.ScopeDefinitionHandle = scopeDefinitionGroup.CanonicalScope.Handle;
                    result.OverflowScopes = scopeDefinitionGroup.OverflowScopes;
                }
            }

            BindEcmaAssemblyName(refName, cacheMissedLookups, ref result, ref exception, ref preferredException, ref foundMatch);
            if (exception != null)
                return false;

            if (!foundMatch)
            {
                exception = preferredException ?? new FileNotFoundException(SR.Format(SR.FileNotFound_AssemblyNotFound, refName.FullName));
                return false;
            }

            return true;
        }

        public sealed override IList<AssemblyBindResult> GetLoadedAssemblies()
        {
            List<AssemblyBindResult> loadedAssemblies = new List<AssemblyBindResult>(ScopeGroups.Length);
            foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> group in ScopeGroups)
            {
                ScopeDefinitionGroup scopeDefinitionGroup = group.Value;

                AssemblyBindResult result = default(AssemblyBindResult);
                result.Reader = scopeDefinitionGroup.CanonicalScope.Reader;
                result.ScopeDefinitionHandle = scopeDefinitionGroup.CanonicalScope.Handle;
                result.OverflowScopes = scopeDefinitionGroup.OverflowScopes;
                loadedAssemblies.Add(result);
            }

            InsertEcmaLoadedAssemblies(loadedAssemblies);

            return loadedAssemblies;
        }

        //
        // Name match routine for mscorlib references
        //
        private bool MscorlibAssemblyNameMatches(RuntimeAssemblyName coreAssemblyName, RuntimeAssemblyName defName)
        {
            //
            // The defName came from trusted metadata so it should be fully specified.
            //
            Debug.Assert(defName.Version != null);
            Debug.Assert(defName.CultureName != null);

            Debug.Assert((coreAssemblyName.Flags & AssemblyNameFlags.PublicKey) == 0);
            Debug.Assert((defName.Flags & AssemblyNameFlags.PublicKey) == 0);

            if (defName.Name != coreAssemblyName.Name)
                return false;
            byte[] defPkt = defName.PublicKeyOrToken;
            if (defPkt == null)
                return false;
            if (!ArePktsEqual(defPkt, coreAssemblyName.PublicKeyOrToken))
                return false;
            return true;
        }

        //
        // Encapsulates the assembly ref->def matching policy.
        //
        private bool AssemblyNameMatches(RuntimeAssemblyName refName, RuntimeAssemblyName defName, ref Exception preferredException)
        {
            //
            // The defName came from trusted metadata so it should be fully specified.
            //
            Debug.Assert(defName.Version != null);
            Debug.Assert(defName.CultureName != null);

            Debug.Assert((defName.Flags & AssemblyNameFlags.PublicKey) == 0);
            Debug.Assert((refName.Flags & AssemblyNameFlags.PublicKey) == 0);

            if (!(refName.Name.Equals(defName.Name, StringComparison.OrdinalIgnoreCase)))
                return false;

            if (refName.Version != null)
            {
                if (!AssemblyVersionMatches(refVersion: refName.Version, defVersion: defName.Version))
                {
                    preferredException = new FileLoadException(SR.Format(SR.FileLoadException_RefDefMismatch, refName.FullName, defName.Version, refName.Version));
                    return false;
                }
            }

            if (refName.CultureName != null)
            {
                if (!(refName.CultureName.Equals(defName.CultureName)))
                    return false;
            }

            AssemblyNameFlags materialRefNameFlags = refName.Flags.ExtractAssemblyNameFlags();
            AssemblyNameFlags materialDefNameFlags = defName.Flags.ExtractAssemblyNameFlags();
            if (materialRefNameFlags != materialDefNameFlags)
            {
                return false;
            }

            byte[] refPublicKeyToken = refName.PublicKeyOrToken;
            if (refPublicKeyToken != null)
            {
                byte[] defPublicKeyToken = defName.PublicKeyOrToken;
                if (defPublicKeyToken == null)
                    return false;
                if (!ArePktsEqual(refPublicKeyToken, defPublicKeyToken))
                    return false;
            }

            return true;
        }

        private static bool AssemblyVersionMatches(Version refVersion, Version defVersion)
        {
            if (defVersion.Major < refVersion.Major)
                return false;
            if (defVersion.Major > refVersion.Major)
                return true;

            if (defVersion.Minor < refVersion.Minor)
                return false;
            if (defVersion.Minor > refVersion.Minor)
                return true;

            if (refVersion.Build == -1)
                return true;
            if (defVersion.Build < refVersion.Build)
                return false;
            if (defVersion.Build > refVersion.Build)
                return true;

            if (refVersion.Revision == -1)
                return true;
            if (defVersion.Revision < refVersion.Revision)
                return false;

            return true;
        }

        /// <summary>
        /// This callback gets called whenever a module gets registered. It adds the metadata reader
        /// for the new module to the available scopes. The lock in ExecutionEnvironmentImplementation ensures
        /// that this function may never be called concurrently so that we can assume that two threads
        /// never update the reader and scope list at the same time.
        /// </summary>
        /// <param name="moduleInfo">Module to register</param>
        private void RegisterModule(ModuleInfo moduleInfo)
        {
            NativeFormatModuleInfo nativeFormatModuleInfo = moduleInfo as NativeFormatModuleInfo;

            if (nativeFormatModuleInfo == null)
            {
                return;
            }

            LowLevelDictionaryWithIEnumerable<RuntimeAssemblyName, ScopeDefinitionGroup> scopeGroups = new LowLevelDictionaryWithIEnumerable<RuntimeAssemblyName, ScopeDefinitionGroup>();
            foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> oldGroup in _scopeGroups)
            {
                scopeGroups.Add(oldGroup.Key, oldGroup.Value);
            }
            AddScopesFromReaderToGroups(scopeGroups, nativeFormatModuleInfo.MetadataReader);

            // Update reader and scope list
            KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[] scopeGroupsArray = new KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[scopeGroups.Count];
            int i = 0;
            foreach (KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup> data in scopeGroups)
            {
                scopeGroupsArray[i] = data;
                i++;
            }

            _scopeGroups = scopeGroupsArray;
        }

        private KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[] ScopeGroups
        {
            get
            {
                return _scopeGroups;
            }
        }

        private void AddScopesFromReaderToGroups(LowLevelDictionaryWithIEnumerable<RuntimeAssemblyName, ScopeDefinitionGroup> groups, MetadataReader reader)
        {
            foreach (ScopeDefinitionHandle scopeDefinitionHandle in reader.ScopeDefinitions)
            {
                RuntimeAssemblyName defName = scopeDefinitionHandle.ToRuntimeAssemblyName(reader).CanonicalizePublicKeyToken();
                ScopeDefinitionGroup scopeDefinitionGroup;
                if (groups.TryGetValue(defName, out scopeDefinitionGroup))
                {
                    scopeDefinitionGroup.AddOverflowScope(new QScopeDefinition(reader, scopeDefinitionHandle));
                }
                else
                {
                    scopeDefinitionGroup = new ScopeDefinitionGroup(new QScopeDefinition(reader, scopeDefinitionHandle));
                    groups.Add(defName, scopeDefinitionGroup);
                }
            }
        }

        private static bool ArePktsEqual(byte[] pkt1, byte[] pkt2)
        {
            if (pkt1.Length != pkt2.Length)
                return false;
            for (int i = 0; i < pkt1.Length; i++)
            {
                if (pkt1[i] != pkt2[i])
                    return false;
            }
            return true;
        }

        private volatile KeyValuePair<RuntimeAssemblyName, ScopeDefinitionGroup>[] _scopeGroups;

        private class ScopeDefinitionGroup
        {
            public ScopeDefinitionGroup(QScopeDefinition canonicalScope)
            {
                _canonicalScope = canonicalScope;
            }

            public QScopeDefinition CanonicalScope { get { return _canonicalScope; } }

            public IEnumerable<QScopeDefinition> OverflowScopes
            {
                get
                {
                    return _overflowScopes.ToArray();
                }
            }

            public void AddOverflowScope(QScopeDefinition overflowScope)
            {
                _overflowScopes.Add(overflowScope);
            }

            private readonly QScopeDefinition _canonicalScope;
            private ArrayBuilder<QScopeDefinition> _overflowScopes;
        }
    }
}