InternalsVisibleToAndStrongNameTests.cs 81.1 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;

20
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
P
Pilchie 已提交
21
{
22
    public class InternalsVisibleToAndStrongNameTests : CSharpTestBase
P
Pilchie 已提交
23
    {
24
        #region Helpers
P
Pilchie 已提交
25

26 27 28 29
        public InternalsVisibleToAndStrongNameTests()
        {
            SigningTestHelpers.InstallKey();
        }
P
Pilchie 已提交
30

31 32 33 34 35 36 37 38 39
        private static readonly string s_keyPairFile = SigningTestHelpers.KeyPairFile;
        private static readonly string s_publicKeyFile = SigningTestHelpers.PublicKeyFile;
        private static readonly ImmutableArray<byte> s_publicKey = SigningTestHelpers.PublicKey;
        private static readonly DesktopStrongNameProvider s_defaultProvider = new SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create<string>());

        private static DesktopStrongNameProvider GetProviderWithPath(string keyFilePath)
        {
            return new SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create(keyFilePath));
        }
P
Pilchie 已提交
40

41
        #endregion
P
Pilchie 已提交
42

43
        #region Naming Tests
P
Pilchie 已提交
44

45 46 47 48
        [Fact, WorkItem(529419, "DevDiv")]
        public void AssemblyKeyFileAttributeNotExistFile()
        {
            string source = @"
P
Pilchie 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62
using System;
using System.Reflection;

[assembly: AssemblyKeyFile(""MyKey.snk"")]
[assembly: AssemblyKeyName(""Key Name"")]

public class Test
{
    public static void Main()
    {
        Console.Write(""Hello World!"");
    }
}
";
63 64 65 66 67 68 69 70 71 72
            // Dev11 RC gives error now (CS1548) + two warnings
            // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keyfile", "AssemblyKeyFile"),
            // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keycontainer", "AssemblyKeyName")
            var c = CreateCompilationWithMscorlib(source,
                references: new[] { SystemRef },
                options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()));

            c.VerifyDiagnostics(
                Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("MyKey.snk", CodeAnalysisResources.FileNotFound));
        }
P
Pilchie 已提交
73

74 75 76 77 78
        [Fact]
        public void PubKeyFromKeyFileAttribute()
        {
            var x = s_keyPairFile;
            string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}");
P
Pilchie 已提交
79

80 81 82
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
            other.VerifyDiagnostics();
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey));
P
Pilchie 已提交
83

84
            CompileAndVerify(other, symbolValidator: (ModuleSymbol m) =>
P
Pilchie 已提交
85
                {
86 87 88
                    bool haveAttribute = false;

                    foreach (var attrData in m.ContainingAssembly.GetAttributes())
P
Pilchie 已提交
89
                    {
90 91 92 93 94
                        if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyFileAttribute))
                        {
                            haveAttribute = true;
                            break;
                        }
P
Pilchie 已提交
95 96
                    }

97 98 99
                    Assert.True(haveAttribute);
                }, emitOptions: TestEmitters.CCI);
        }
P
Pilchie 已提交
100

101 102 103 104 105
        [Fact]
        public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver()
        {
            string keyFileDir = Path.GetDirectoryName(s_keyPairFile);
            string keyFileName = Path.GetFileName(s_keyPairFile);
106

107 108
            string s = string.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", keyFileName, @""")] public class C {}");
            var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs");
P
Pilchie 已提交
109

110 111 112 113
            // verify failure with default assembly key file resolver
            var comp = CreateCompilationWithMscorlib(syntaxTree, options: TestOptions.ReleaseDll);
            comp.VerifyDiagnostics(
                Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, "Assembly signing not supported."));
P
Pilchie 已提交
114

115
            Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty);
P
Pilchie 已提交
116

117 118 119 120 121 122
            // verify success with custom assembly key file resolver with keyFileDir added to search paths
            comp = CSharpCompilation.Create(
                GetUniqueName(),
                new[] { syntaxTree },
                new[] { MscorlibRef },
                TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(keyFileDir)));
P
Pilchie 已提交
123

124
            comp.VerifyDiagnostics();
P
Pilchie 已提交
125

126 127
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey));
        }
P
Pilchie 已提交
128

129 130 131 132 133
        [Fact]
        public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver_RelativeToCurrentParent()
        {
            string keyFileDir = Path.GetDirectoryName(s_keyPairFile);
            string keyFileName = Path.GetFileName(s_keyPairFile);
P
Pilchie 已提交
134

135 136
            string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}");
            var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs");
P
Pilchie 已提交
137

138 139 140 141 142
            // verify failure with default assembly key file resolver
            var comp = CreateCompilationWithMscorlib(syntaxTree, options: TestOptions.ReleaseDll);
            comp.VerifyDiagnostics(
                // error CS7027: Error extracting public key from file '..\KeyPairFile.snk' -- File not found.
                Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(@"..\" + keyFileName, "Assembly signing not supported."));
P
Pilchie 已提交
143

144
            Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty);
145

146 147 148 149 150 151
            // verify success with custom assembly key file resolver with keyFileDir\TempSubDir added to search paths
            comp = CSharpCompilation.Create(
                GetUniqueName(),
                new[] { syntaxTree },
                new[] { MscorlibRef },
                TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\"))));
152

153 154 155
            Assert.Empty(comp.GetDiagnostics());
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey));
        }
156

157 158 159 160 161
        [Fact]
        public void SigningNotAvailable001()
        {
            string keyFileDir = Path.GetDirectoryName(s_keyPairFile);
            string keyFileName = Path.GetFileName(s_keyPairFile);
162

163 164
            string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}");
            var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs");
165

166 167 168 169 170 171
            // verify failure 
            var comp = CSharpCompilation.Create(
                GetUniqueName(),
                new[] { syntaxTree },
                new[] { MscorlibRef },
                TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\"))));
172

173
            var provider = (DesktopStrongNameProvider)comp.Options.StrongNameProvider;
174

175 176 177 178
            provider.TestStrongNameInterfaceFactory = () =>
            {
                throw new DllNotFoundException("aaa.dll not found.");
            };
179

180 181 182 183
            comp.VerifyEmitDiagnostics(
                // error CS7027: Error signing output with public key from file '..\KeyPair_6187d0d6-f691-47fd-985b-03570bc0668d.snk' -- aaa.dll not found.
                Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("..\\" + keyFileName, "aaa.dll not found.").WithLocation(1, 1)
            );
P
Pilchie 已提交
184

185
        }
P
Pilchie 已提交
186

187 188
        [Fact]
        public void PubKeyFromKeyContainerAttribute()
P
Pilchie 已提交
189
        {
190 191 192 193 194 195
            var x = s_keyPairFile;
            string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}";

            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
            other.VerifyDiagnostics();
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey));
P
Pilchie 已提交
196

197
            CompileAndVerify(other, symbolValidator: (ModuleSymbol m) =>
P
Pilchie 已提交
198
            {
199 200 201
                bool haveAttribute = false;

                foreach (var attrData in m.ContainingAssembly.GetAttributes())
P
Pilchie 已提交
202
                {
203 204 205 206 207
                    if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyNameAttribute))
                    {
                        haveAttribute = true;
                        break;
                    }
P
Pilchie 已提交
208 209
                }

210 211 212
                Assert.True(haveAttribute);
            }, emitOptions: TestEmitters.CCI);
        }
P
Pilchie 已提交
213

214 215 216 217 218
        [Fact]
        public void PubKeyFromKeyFileOptions()
        {
            string s = "public class C {}";
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
219

220 221 222
            other.VerifyDiagnostics();
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey));
        }
P
Pilchie 已提交
223

224 225 226 227 228
        [Fact]
        public void PubKeyFromKeyFileOptions_ReferenceResolver()
        {
            string keyFileDir = Path.GetDirectoryName(s_keyPairFile);
            string keyFileName = Path.GetFileName(s_keyPairFile);
P
Pilchie 已提交
229

230 231
            string s = "public class C {}";
            var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs");
P
Pilchie 已提交
232

233 234
            // verify failure with default resolver
            var comp = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
235

236 237 238
            comp.VerifyDiagnostics(
                // error CS7027: Error extracting public key from file 'KeyPairFile.snk' -- File not found.
                Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, CodeAnalysisResources.FileNotFound));
239

240
            Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty);
P
Pilchie 已提交
241

242 243 244 245 246 247
            // verify success with custom assembly key file resolver with keyFileDir added to search paths
            comp = CSharpCompilation.Create(
                GetUniqueName(),
                new[] { syntaxTree },
                new[] { MscorlibRef },
                TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(GetProviderWithPath(keyFileDir)));
P
Pilchie 已提交
248

249 250 251
            Assert.Empty(comp.GetDiagnostics());
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey));
        }
P
Pilchie 已提交
252

253 254 255 256 257 258 259 260 261
        [Fact]
        public void PubKeyFromKeyFileOptionsJustPublicKey()
        {
            string s = "public class C {}";
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true).WithStrongNameProvider(s_defaultProvider));
            other.VerifyDiagnostics();
            Assert.True(ByteSequenceComparer.Equals(TestResources.SymbolsTests.General.snPublicKey.AsImmutableOrNull(), other.Assembly.Identity.PublicKey));
        }
P
Pilchie 已提交
262

263 264 265 266 267
        [Fact]
        public void PubKeyFromKeyFileOptionsJustPublicKey_ReferenceResolver()
        {
            string publicKeyFileDir = Path.GetDirectoryName(s_publicKeyFile);
            string publicKeyFileName = Path.GetFileName(s_publicKeyFile);
P
Pilchie 已提交
268

269 270
            string s = "public class C {}";
            var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs");
P
Pilchie 已提交
271

272 273 274
            // verify failure with default resolver
            var comp = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
275

276 277 278 279 280 281
            comp.VerifyDiagnostics(
                // error CS7027: Error extracting public key from file 'PublicKeyFile.snk' -- File not found.
                Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(publicKeyFileName, CodeAnalysisResources.FileNotFound),
                // warning CS7033: Delay signing was specified and requires a public key, but no public key was specified
                Diagnostic(ErrorCode.WRN_DelaySignButNoKey)
            );
P
Pilchie 已提交
282

283
            Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty);
P
Pilchie 已提交
284

285 286 287 288 289 290 291 292 293
            // verify success with custom assembly key file resolver with publicKeyFileDir added to search paths
            comp = CSharpCompilation.Create(
                GetUniqueName(),
                new[] { syntaxTree },
                new[] { MscorlibRef },
                TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true).WithStrongNameProvider(GetProviderWithPath(publicKeyFileDir)));
            Assert.Empty(comp.GetDiagnostics());
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey));
        }
P
Pilchie 已提交
294

295 296 297 298 299 300
        [Fact]
        public void PubKeyFileNotFoundOptions()
        {
            string s = "public class C {}";
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile("foo").WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
301

302 303 304 305 306
            other.VerifyDiagnostics(
                Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("foo", CodeAnalysisResources.FileNotFound));

            Assert.True(other.Assembly.Identity.PublicKey.IsEmpty);
        }
P
Pilchie 已提交
307

308 309 310 311 312
        [Fact]
        public void PubKeyFileBogusOptions()
        {
            var tempFile = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4 });
            string s = "public class C {}";
313

314
            CSharpCompilation other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(tempFile.Path));
315

316 317 318 319
            //TODO check for specific error
            Assert.NotEmpty(other.GetDiagnostics());
            Assert.True(other.Assembly.Identity.PublicKey.IsEmpty);
        }
P
Pilchie 已提交
320

321 322 323 324 325 326
        [Fact]
        public void PubKeyContainerBogusOptions()
        {
            string s = "public class C {}";
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyContainer("foo").WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
327

328 329
            // error CS7028: Error signing output with public key from container 'foo' -- Keyset does not exist (Exception from HRESULT: 0x80090016)
            var err = other.GetDiagnostics().Single();
P
Pilchie 已提交
330

331 332 333 334
            Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code);
            Assert.Equal(2, err.Arguments.Count);
            Assert.Equal("foo", err.Arguments[0]);
            Assert.True(((string)err.Arguments[1]).EndsWith(" HRESULT: 0x80090016)"));
P
Pilchie 已提交
335

336 337
            Assert.True(other.Assembly.Identity.PublicKey.IsEmpty);
        }
P
Pilchie 已提交
338

339 340 341 342
        [Fact]
        public void KeyFileAttributeOptionConflict()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}";
P
Pilchie 已提交
343

344 345
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
346

347 348 349
            other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyFile", "System.Reflection.AssemblyKeyFileAttribute"));
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey));
        }
P
Pilchie 已提交
350

351 352 353 354
        [Fact]
        public void KeyContainerAttributeOptionConflict()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}";
P
Pilchie 已提交
355

356 357
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyContainer("RoslynTestContainer").WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
358

359 360 361
            other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyContainer", "System.Reflection.AssemblyKeyNameAttribute"));
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey));
        }
P
Pilchie 已提交
362

363 364 365 366
        [Fact]
        public void KeyFileAttributeEmpty()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyFile("""")] public class C {}";
P
Pilchie 已提交
367

368 369 370 371
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
            Assert.True(other.Assembly.Identity.PublicKey.IsEmpty);
            other.VerifyDiagnostics();
        }
P
Pilchie 已提交
372

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        [Fact]
        public void KeyContainerEmpty()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyName("""")] public class C {}";

            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
            Assert.True(other.Assembly.Identity.PublicKey.IsEmpty);
            other.VerifyDiagnostics();
        }

        #endregion

        #region IVT Access Checking

        [Fact]
        public void IVTBasicCompilation()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")]
P
Pilchie 已提交
391 392
            public class C { internal void Foo() {} }";

393
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
394

395 396
            var c = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
397 398 399 400 401 402 403 404 405
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
406 407 408
                new[] { new CSharpCompilationReference(other) },
                assemblyName: "WantsIVTAccessButCantHave",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
409

410 411
            //compilation should not succeed, and internals should not be imported.
            c.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadAccess, "Foo").WithArguments("C.Foo()"));
P
Pilchie 已提交
412

413 414
            var c2 = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
415 416 417 418 419 420 421 422 423
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
424 425 426
                new[] { new CSharpCompilationReference(other) },
                assemblyName: "WantsIVTAccess",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
427

428 429
            Assert.Empty(c2.GetDiagnostics());
        }
P
Pilchie 已提交
430

431 432 433 434
        [Fact]
        public void IVTBasicMetadata()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")]
P
Pilchie 已提交
435 436
            public class C { internal void Foo() {} }";

437
            var otherStream = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)).EmitToStream();
P
Pilchie 已提交
438

439 440
            var c = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
441 442 443 444 445 446 447 448 449
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
450 451 452
            references: new[] { AssemblyMetadata.CreateFromStream(otherStream, leaveOpen: true).GetReference() },
            assemblyName: "WantsIVTAccessButCantHave",
            options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
453

454 455
            //compilation should not succeed, and internals should not be imported.
            c.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Foo").WithArguments("C", "Foo"));
P
Pilchie 已提交
456

457
            otherStream.Position = 0;
P
Pilchie 已提交
458

459 460
            var c2 = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
461 462 463 464 465 466 467 468 469
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
470 471 472
                new[] { MetadataReference.CreateFromStream(otherStream) },
                assemblyName: "WantsIVTAccess",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
473

474 475
            Assert.Empty(c2.GetDiagnostics());
        }
P
Pilchie 已提交
476

477 478 479 480
        [Fact]
        public void IVTSigned()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
481 482
            public class C { internal void Foo() {} }";

483 484 485
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider),
                assemblyName: "Paul");
P
Pilchie 已提交
486

487
            other.VerifyDiagnostics();
P
Pilchie 已提交
488

489 490
            var requestor = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
491 492 493 494 495 496 497 498 499
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
500 501 502
                new MetadataReference[] { new CSharpCompilationReference(other) },
                TestOptions.ReleaseDll.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider),
                assemblyName: "John");
P
Pilchie 已提交
503

504 505
            Assert.Empty(requestor.GetDiagnostics());
        }
P
Pilchie 已提交
506

507 508 509 510
        [Fact]
        public void IVTErrorNotBothSigned()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
511 512
            public class C { internal void Foo() {} }";

513 514
            var other = CreateCompilationWithMscorlib(s, assemblyName: "Paul", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
            other.VerifyDiagnostics();
P
Pilchie 已提交
515

516 517
            var requestor = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
518 519 520 521 522 523 524 525 526
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
527 528 529
                references: new[] { new CSharpCompilationReference(other) },
                assemblyName: "John",
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
530

531 532
            // We allow John to access Paul's internal Foo even though strong-named John should not be referencing weak-named Paul.
            // Paul has, after all, specifically granted access to John.
P
Pilchie 已提交
533

534 535 536 537
            // TODO: During emit time we should produce an error that says that a strong-named assembly cannot reference
            // TODO: a weak-named assembly.
            requestor.VerifyDiagnostics();
        }
P
Pilchie 已提交
538

539 540 541 542
        [Fact]
        public void IVTDeferredSuccess()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
543 544
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

545 546 547
            var other = CreateCompilationWithMscorlib(s,
                assemblyName: "Paul",
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
548

549
            other.VerifyDiagnostics();
P
Pilchie 已提交
550

551 552
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
553 554 555 556 557
[assembly: C()]  //causes optimistic granting
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class A
{
}",
558 559 560
                new[] { new CSharpCompilationReference(other) },
                assemblyName: "John",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
561

562 563 564
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey));
            Assert.Empty(requestor.GetDiagnostics());
        }
P
Pilchie 已提交
565

566 567 568 569
        [Fact]
        public void IVTDeferredFailSignMismatch()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
570 571
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

572 573 574
            var other = CreateCompilationWithMscorlib(s,
                assemblyName: "Paul",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)); //not signed. cryptoKeyFile: KeyPairFile,
P
Pilchie 已提交
575

576
            other.VerifyDiagnostics();
P
Pilchie 已提交
577

578 579
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
580 581 582 583 584
[assembly: C()] //causes optimistic granting
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class A
{
}",
585 586 587
                new[] { new CSharpCompilationReference(other) },
                assemblyName: "John",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
588

589 590 591
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey));
            requestor.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendRefSigningMismatch, null, new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" }));
        }
P
Pilchie 已提交
592

593 594 595 596 597
        [Fact]
        public void IVTDeferredFailKeyMismatch()
        {
            //key is wrong in the first digit. correct key starts with 0
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
598 599
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

600 601 602
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider),
                assemblyName: "Paul");
P
Pilchie 已提交
603

604
            other.VerifyDiagnostics();
P
Pilchie 已提交
605

606 607
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
608 609 610 611 612
[assembly: C()]  //causes optimistic granting
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class A
{
}",
613 614 615
              new MetadataReference[] { new CSharpCompilationReference(other) },
              assemblyName: "John",
              options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
616

617 618 619
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey));
            requestor.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, null, new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2" }));
        }
P
Pilchie 已提交
620

621 622 623 624
        [Fact]
        public void IVTSuccessThroughIAssembly()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
625 626
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

627 628 629
            var other = CreateCompilationWithMscorlib(s,
                assemblyName: "Paul",
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
630

631
            other.VerifyDiagnostics();
P
Pilchie 已提交
632

633 634
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
635 636 637 638 639
[assembly: C()]  //causes optimistic granting
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class A
{
}",
640 641 642
                new MetadataReference[] { new CSharpCompilationReference(other) },
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider),
                assemblyName: "John");
P
Pilchie 已提交
643

644 645 646
            Assert.True(((IAssemblySymbol)other.Assembly).GivesAccessTo(requestor.Assembly));
            Assert.Empty(requestor.GetDiagnostics());
        }
P
Pilchie 已提交
647

648 649 650 651 652
        [Fact]
        public void IVTDeferredFailKeyMismatchIAssembly()
        {
            //key is wrong in the first digit. correct key starts with 0
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
653 654
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

655 656 657
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider),
                assemblyName: "Paul");
P
Pilchie 已提交
658

659
            other.VerifyDiagnostics();
P
Pilchie 已提交
660

661 662
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
663 664 665 666 667 668

[assembly: C()]  //causes optimistic granting
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class A
{
}",
669 670 671
                new MetadataReference[] { new CSharpCompilationReference(other) },
                TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider),
                assemblyName: "John");
P
Pilchie 已提交
672

673 674 675
            Assert.False(((IAssemblySymbol)other.Assembly).GivesAccessTo(requestor.Assembly));
            requestor.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, null, new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2" }));
        }
P
Pilchie 已提交
676

677 678 679 680 681
        [WorkItem(820450, "DevDiv")]
        [Fact]
        public void IVTGivesAccessToUsingDifferentKeys()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
682 683
            namespace ClassLibrary1 { internal class Class1 { } } ";

684 685 686
            var giver = CreateCompilationWithMscorlib(s,
                assemblyName: "Paul",
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile2).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
687

688
            giver.VerifyDiagnostics();
P
Pilchie 已提交
689

690 691
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
692 693 694 695 696 697 698 699 700
namespace ClassLibrary2
{
    internal class A
    {
        public void Foo(ClassLibrary1.Class1 a)
        {   
        }
    }
}",
701 702 703
                new MetadataReference[] { new CSharpCompilationReference(giver) },
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider),
                assemblyName: "John");
P
Pilchie 已提交
704

705 706 707 708
            Assert.True(((IAssemblySymbol)giver.Assembly).GivesAccessTo(requestor.Assembly));
            Assert.Empty(requestor.GetDiagnostics());
        }
        #endregion
P
Pilchie 已提交
709

710
        #region IVT instantiations
P
Pilchie 已提交
711

712 713 714 715 716
        [Fact]
        public void IVTHasCulture()
        {
            var other = CreateCompilationWithMscorlib(
            @"
P
Pilchie 已提交
717 718 719 720 721 722
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")]
public class C
{
  static void Foo() {}
}
723
", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
724

725 726
            other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")").WithArguments("WantsIVTAccess, Culture=neutral"));
        }
P
Pilchie 已提交
727

728 729 730 731 732
        [Fact]
        public void IVTNoKey()
        {
            var other = CreateCompilationWithMscorlib(
            @"
P
Pilchie 已提交
733 734 735 736 737 738
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""WantsIVTAccess"")]
public class C
{
  static void Main() {}
}
739
", options: TestOptions.ReleaseExe.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
740

741 742
            other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblySNReq, @"InternalsVisibleTo(""WantsIVTAccess"")").WithArguments("WantsIVTAccess"));
        }
P
Pilchie 已提交
743

744
        #endregion
P
Pilchie 已提交
745

746
        #region Signing
P
Pilchie 已提交
747

748 749 750 751 752
        [Fact]
        public void SignIt()
        {
            var other = CreateCompilationWithMscorlib(
            @"
P
Pilchie 已提交
753 754 755 756
public class C
{
  static void Foo() {}
}",
757
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
758

759
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
760

761 762 763 764 765
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.True(success.Success);
            }
P
Pilchie 已提交
766

767 768
            AssertFileIsSigned(tempFile);
        }
P
Pilchie 已提交
769

770
        private static void AssertFileIsSigned(TempFile file)
P
Pilchie 已提交
771
        {
772 773 774 775 776 777
            //TODO should check to see that the output was actually signed
            using (var metadata = new FileStream(file.Path, FileMode.Open))
            {
                var flags = new PEHeaders(metadata).CorHeader.Flags;
                Assert.Equal(CorFlags.StrongNameSigned, flags & CorFlags.StrongNameSigned);
            }
P
Pilchie 已提交
778 779
        }

780
        private void ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(MemoryStream moduleContents, AttributeDescription expectedModuleAttr)
P
Pilchie 已提交
781
        {
782 783 784
            //a module doesn't get signed for real. It should have either a keyfile or keycontainer attribute
            //parked on a typeRef named 'AssemblyAttributesGoHere.' When the module is added to an assembly, the
            //resulting assembly is signed with the key referred to by the aforementioned attribute.
P
Pilchie 已提交
785

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
            EmitResult success;
            var tempFile = Temp.CreateFile();
            moduleContents.Position = 0;

            using (var metadata = ModuleMetadata.CreateFromStream(moduleContents))
            {
                var flags = metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags;
                //confirm file does not claim to be signed
                Assert.Equal(0, (int)(flags & CorFlags.StrongNameSigned));
                Handle token = metadata.Module.GetTypeRef(metadata.Module.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere");
                Assert.False(token.IsNil);   //could the type ref be located? If not then the attribute's not there.
                var attrInfos = metadata.Module.FindTargetAttributes(token, expectedModuleAttr);
                Assert.Equal(1, attrInfos.Count());

                var source = @"
P
Pilchie 已提交
801 802 803 804
public class Z
{
}";

805 806 807 808 809
                //now that the module checks out, ensure that adding it to a compilation outputing a dll
                //results in a signed assembly.
                var assemblyComp = CreateCompilationWithMscorlib(source,
                    new[] { metadata.GetReference() },
                    TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
810

811 812 813 814
                using (var finalStrm = tempFile.Open())
                {
                    success = assemblyComp.Emit(finalStrm);
                }
P
Pilchie 已提交
815 816
            }

817
            success.Diagnostics.Verify();
P
Pilchie 已提交
818

819 820 821
            Assert.True(success.Success);
            AssertFileIsSigned(tempFile);
        }
P
Pilchie 已提交
822

823 824 825 826 827
        [Fact]
        public void SignModuleKeyFileAttr()
        {
            var x = s_keyPairFile;
            string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}");
P
Pilchie 已提交
828

829
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
830

831 832 833
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
834

835 836
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute);
        }
P
Pilchie 已提交
837

838 839 840 841
        [Fact]
        public void SignModuleKeyContainerAttr()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}";
P
Pilchie 已提交
842

843
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
844

845 846 847
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
848

849 850
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute);
        }
P
Pilchie 已提交
851

852 853 854 855
        [Fact]
        public void SignModuleKeyContainerBogus()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}";
P
Pilchie 已提交
856

857 858 859
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider));
            //shouldn't have an error. The attribute's contents are checked when the module is added.
            var reference = other.EmitToImageReference();
P
Pilchie 已提交
860

861
            s = @"class D {}";
P
Pilchie 已提交
862

863
            other = CreateCompilationWithMscorlib(s, new[] { reference }, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
864

865 866
            // error CS7028: Error signing output with public key from container 'bogus' -- Keyset does not exist (Exception from HRESULT: 0x80090016)
            var err = other.GetDiagnostics().Single();
867

868 869 870 871 872
            Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code);
            Assert.Equal(2, err.Arguments.Count);
            Assert.Equal("bogus", err.Arguments[0]);
            Assert.True(((string)err.Arguments[1]).EndsWith(" HRESULT: 0x80090016)"));
        }
P
Pilchie 已提交
873

874 875 876 877
        [Fact]
        public void SignModuleKeyFileBogus()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}";
P
Pilchie 已提交
878

879
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
880

881 882
            //shouldn't have an error. The attribute's contents are checked when the module is added.
            var reference = other.EmitToImageReference();
P
Pilchie 已提交
883

884
            s = @"class D {}";
P
Pilchie 已提交
885

886 887 888
            other = CreateCompilationWithMscorlib(s, new[] { reference }, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
            other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("bogus", CodeAnalysisResources.FileNotFound));
        }
P
Pilchie 已提交
889

890 891 892 893 894
        [WorkItem(531195, "DevDiv")]
        [Fact()]
        public void SignModuleKeyContainerCmdLine()
        {
            string s = "public class C {}";
P
Pilchie 已提交
895

896
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
897

898 899 900
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
901

902 903
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute);
        }
P
Pilchie 已提交
904

905 906 907 908 909
        [WorkItem(531195, "DevDiv")]
        [Fact()]
        public void SignModuleKeyContainerCmdLine_1()
        {
            string s = @"
P
Pilchie 已提交
910 911 912
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class C {}";

913 914
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
915

916 917 918
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
919

920 921
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute);
        }
P
Pilchie 已提交
922

923 924 925 926 927
        [WorkItem(531195, "DevDiv")]
        [Fact()]
        public void SignModuleKeyContainerCmdLine_2()
        {
            string s = @"
P
Pilchie 已提交
928 929 930
[assembly: System.Reflection.AssemblyKeyName(""bogus"")]
public class C {}";

931
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
932

933 934 935 936 937 938 939 940
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.False(success.Success);
            success.Diagnostics.Verify(
        // error CS7091: Attribute 'System.Reflection.AssemblyKeyNameAttribute' given in a source file conflicts with option 'CryptoKeyContainer'.
        Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyNameAttribute", "CryptoKeyContainer")
                );
        }
P
Pilchie 已提交
941

942 943 944 945 946
        [WorkItem(531195, "DevDiv")]
        [Fact()]
        public void SignModuleKeyFileCmdLine()
        {
            string s = "public class C {}";
P
Pilchie 已提交
947

948
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
949

950 951 952
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
953

954 955
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute);
        }
P
Pilchie 已提交
956

957 958 959 960 961 962
        [WorkItem(531195, "DevDiv")]
        [Fact()]
        public void SignModuleKeyFileCmdLine_1()
        {
            var x = s_keyPairFile;
            string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}");
P
Pilchie 已提交
963

964
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
965

966 967 968
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
969

970 971
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute);
        }
P
Pilchie 已提交
972

973 974 975 976 977 978
        [WorkItem(531195, "DevDiv")]
        [Fact()]
        public void SignModuleKeyFileCmdLine_2()
        {
            var x = s_keyPairFile;
            string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}";
P
Pilchie 已提交
979

980
            var other = CreateCompilationWithMscorlib(s, options: TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
981

982 983 984 985 986 987 988
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.False(success.Success);
            success.Diagnostics.Verify(
                // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'.
                Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile"));
        }
P
Pilchie 已提交
989

990 991 992 993 994
        [Fact]
        public void SignItWithOnlyPublicKey()
        {
            var other = CreateCompilationWithMscorlib(
            @"
P
Pilchie 已提交
995 996 997 998
public class C
{
  static void Foo() {}
}",
999
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1000

1001 1002 1003
            var outStrm = new MemoryStream();
            var emitResult = other.Emit(outStrm);
            other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile));
P
Pilchie 已提交
1004

1005
            other = other.WithOptions(TestOptions.ReleaseModule.WithCryptoKeyFile(s_publicKeyFile));
P
Pilchie 已提交
1006

1007 1008 1009
            var assembly = CreateCompilationWithMscorlib("",
                references: new[] { other.EmitToImageReference() },
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1010

1011 1012
            assembly.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile));
        }
P
Pilchie 已提交
1013

1014 1015 1016 1017 1018
        [Fact]
        public void DelaySignItWithOnlyPublicKey()
        {
            var other = CreateCompilationWithMscorlib(
                @"
P
Pilchie 已提交
1019 1020 1021 1022
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C
{
  static void Foo() {}
1023
}", options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1024

1025 1026 1027 1028 1029
            using (var outStrm = new MemoryStream())
            {
                var emitResult = other.Emit(outStrm);
                Assert.True(emitResult.Success);
            }
P
Pilchie 已提交
1030 1031
        }

1032 1033 1034 1035 1036
        [Fact]
        public void DelaySignButNoKey()
        {
            var other = CreateCompilationWithMscorlib(
                @"
P
Pilchie 已提交
1037 1038 1039 1040 1041
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C
{
  static void Foo() {}
}",
1042
      options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1043

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
            var outStrm = new MemoryStream();
            var emitResult = other.Emit(outStrm);
            // Dev11: warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'AssemblyDelaySignAttribute'
            //        warning CS1607: Assembly generation -- Delay signing was requested, but no key was given
            // Roslyn: warning CS7033: Delay signing was specified and requires a public key, but no public key was specified
            other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_DelaySignButNoKey));
            Assert.True(emitResult.Success);
        }

        [Fact]
        public void SignInMemory()
        {
            var other = CreateCompilationWithMscorlib(
                @"
P
Pilchie 已提交
1058 1059 1060 1061
public class C
{
  static void Foo() {}
}",
1062 1063 1064 1065 1066
    options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
            var outStrm = new MemoryStream();
            var emitResult = other.Emit(outStrm);
            Assert.True(emitResult.Success);
        }
P
Pilchie 已提交
1067

1068 1069 1070 1071 1072
        [Fact]
        public void DelaySignConflict()
        {
            var other = CreateCompilationWithMscorlib(
                @"
P
Pilchie 已提交
1073 1074 1075 1076
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C
{
  static void Foo() {}
1077
}", options: TestOptions.ReleaseDll.WithDelaySign(false).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1078

1079 1080 1081 1082 1083 1084
            var outStrm = new MemoryStream();
            //shouldn't get any key warning.
            other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("DelaySign", "System.Reflection.AssemblyDelaySignAttribute"));
            var emitResult = other.Emit(outStrm);
            Assert.True(emitResult.Success);
        }
P
Pilchie 已提交
1085

1086 1087 1088 1089 1090
        [Fact]
        public void DelaySignNoConflict()
        {
            var other = CreateCompilationWithMscorlib(
                @"
P
Pilchie 已提交
1091 1092 1093 1094
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C
{
  static void Foo() {}
1095
}", options: TestOptions.ReleaseDll.WithDelaySign(true).WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1096

1097 1098 1099 1100 1101 1102
            var outStrm = new MemoryStream();
            //shouldn't get any key warning.
            other.VerifyDiagnostics();
            var emitResult = other.Emit(outStrm);
            Assert.True(emitResult.Success);
        }
P
Pilchie 已提交
1103

1104 1105 1106 1107 1108
        [Fact]
        public void DelaySignWithAssemblySignatureKey()
        {
            //Note that this SignatureKey is some random one that I found in the devdiv build.
            //It is not related to the other keys we use in these tests.
P
Pilchie 已提交
1109

1110 1111 1112 1113
            //In the native compiler, when the AssemblySignatureKey attribute is present, and
            //the binary is configured for delay signing, the contents of the assemblySignatureKey attribute
            //(rather than the contents of the keyfile or container) are used to compute the size needed to 
            //reserve in the binary for its signature. Signing using this key is only supported via sn.exe
P
Pilchie 已提交
1114

1115 1116
            var other = CreateCompilation(
                @"
P
Pilchie 已提交
1117 1118 1119 1120 1121
[assembly: System.Reflection.AssemblyDelaySign(true)]
[assembly: System.Reflection.AssemblySignatureKey(""002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3"", ""a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d"")]
public class C
{
  static void Foo() {}
1122
}",
1123 1124
                new MetadataReference[] { MscorlibRef_v4_0_30316_17626 },
                options: TestOptions.ReleaseDll.WithDelaySign(true).WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1125

1126 1127 1128 1129 1130 1131
            using (var metadata = ModuleMetadata.CreateFromImage(other.EmitToArray()))
            {
                var header = metadata.Module.PEReaderOpt.PEHeaders.CorHeader;
                //confirm header has expected SN signature size
                Assert.Equal(256, header.StrongNameSignatureDirectory.Size);
            }
P
Pilchie 已提交
1132 1133
        }

1134 1135 1136 1137 1138 1139
        [WorkItem(545720, "DevDiv")]
        [WorkItem(530050, "DevDiv")]
        [Fact]
        public void InvalidAssemblyName()
        {
            var il = @"
P
Pilchie 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
.assembly extern mscorlib { }
.assembly asm1
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 09 2F 5C 3A 2A 3F 27 3C 3E 7C 00 00 ) // .../\:*?'<>|..
}

.class private auto ansi beforefieldinit Base
       extends [mscorlib]System.Object
{
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    ldarg.0
    call       instance void [mscorlib]System.Object::.ctor()
    ret
  }
}
";

1159
            var csharp = @"
P
Pilchie 已提交
1160 1161 1162 1163 1164
class Derived : Base 
{
}
";

1165
            var ilRef = CompileIL(il, appendDefaultHeader: false);
P
Pilchie 已提交
1166

1167 1168 1169
            var comp = CreateCompilationWithMscorlib(csharp, new[] { ilRef }, assemblyName: "asm2", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
            comp.VerifyDiagnostics(
                // NOTE: dev10 reports WRN_InvalidAssemblyName, but Roslyn won't (DevDiv #15099).
P
Pilchie 已提交
1170

1171 1172 1173 1174
                // (2,17): error CS0122: 'Base' is inaccessible due to its protection level
                // class Derived : Base 
                Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("Base"));
        }
P
Pilchie 已提交
1175

1176 1177 1178 1179 1180
        [WorkItem(546331, "DevDiv")]
        [Fact]
        public void IvtVirtualCall1()
        {
            var source1 = @"
P
Pilchie 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")]

public class A
{
    internal virtual void M() { }
    internal virtual int P { get { return 0; } }
    internal virtual event System.Action E { add { } remove { } }
}
";
1190
            var source2 = @"
P
Pilchie 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")]

public class B : A
{
    internal override void M() { }
    internal override int P { get { return 0; } }
    internal override event System.Action E { add { } remove { } }
}
";
1200
            var source3 = @"
P
Pilchie 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
using System;
using System.Linq.Expressions;

public class C : B
{
    internal override void M() { }

    void Test()
    {
        C c = new C();
        c.M();
        int x = c.P;
        c.E += null;
    }

    void TestET() 
    {
        C c = new C();
        Expression<Action> expr = () => c.M();
    }
}
";

1224 1225 1226
            var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "asm1");
            comp1.VerifyDiagnostics();
            var ref1 = new CSharpCompilationReference(comp1);
P
Pilchie 已提交
1227

1228 1229 1230
            var comp2 = CreateCompilationWithMscorlib(source2, new[] { ref1 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "asm2");
            comp2.VerifyDiagnostics();
            var ref2 = new CSharpCompilationReference(comp2);
P
Pilchie 已提交
1231

1232 1233
            var comp3 = CreateCompilationWithMscorlib(source3, new[] { SystemCoreRef, ref1, ref2 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "asm3");
            comp3.VerifyDiagnostics();
P
Pilchie 已提交
1234

1235 1236
            // Note: calls B.M, not A.M, since asm1 is not accessible.
            var verifier = CompileAndVerify(comp3, emitOptions: TestEmitters.CCI);
1237

1238
            verifier.VerifyIL("C.Test", @"
P
Pilchie 已提交
1239
{
1240
  // Code size       25 (0x19)
P
Pilchie 已提交
1241 1242
  .maxstack  2
  IL_0000:  newobj     ""C..ctor()""
1243 1244 1245 1246 1247 1248 1249 1250
  IL_0005:  dup
  IL_0006:  callvirt   ""void B.M()""
  IL_000b:  dup
  IL_000c:  callvirt   ""int B.P.get""
  IL_0011:  pop
  IL_0012:  ldnull
  IL_0013:  callvirt   ""void B.E.add""
  IL_0018:  ret
P
Pilchie 已提交
1251 1252
}");

1253
            verifier.VerifyIL("C.TestET", @"
P
Pilchie 已提交
1254
{
1255
  // Code size       85 (0x55)
P
Pilchie 已提交
1256
  .maxstack  3
1257
  IL_0000:  newobj     ""C.<>c__DisplayClass2_0..ctor()""
1258 1259
  IL_0005:  dup
  IL_0006:  newobj     ""C..ctor()""
1260 1261
  IL_000b:  stfld      ""C C.<>c__DisplayClass2_0.c""
  IL_0010:  ldtoken    ""C.<>c__DisplayClass2_0""
1262 1263
  IL_0015:  call       ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
  IL_001a:  call       ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
1264
  IL_001f:  ldtoken    ""C C.<>c__DisplayClass2_0.c""
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
  IL_0024:  call       ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)""
  IL_0029:  call       ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)""
  IL_002e:  ldtoken    ""void B.M()""
  IL_0033:  call       ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
  IL_0038:  castclass  ""System.Reflection.MethodInfo""
  IL_003d:  ldc.i4.0
  IL_003e:  newarr     ""System.Linq.Expressions.Expression""
  IL_0043:  call       ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
  IL_0048:  ldc.i4.0
  IL_0049:  newarr     ""System.Linq.Expressions.ParameterExpression""
  IL_004e:  call       ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
  IL_0053:  pop
  IL_0054:  ret
P
Pilchie 已提交
1278 1279
}
");
1280
        }
P
Pilchie 已提交
1281

1282 1283 1284 1285 1286
        [WorkItem(546331, "DevDiv")]
        [Fact]
        public void IvtVirtualCall2()
        {
            var source1 = @"
P
Pilchie 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")]

public class A
{
    internal virtual void M() { }
    internal virtual int P { get { return 0; } }
    internal virtual event System.Action E { add { } remove { } }
}
";
1297
            var source2 = @"
P
Pilchie 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")]

public class B : A
{
    internal override void M() { }
    internal override int P { get { return 0; } }
    internal override event System.Action E { add { } remove { } }
}
";
1307
            var source3 = @"
P
Pilchie 已提交
1308 1309 1310 1311 1312 1313 1314 1315 1316
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")]

public class C : B
{
    internal override void M() { }
    internal override int P { get { return 0; } }
    internal override event System.Action E { add { } remove { } }
}
";
1317
            var source4 = @"
P
Pilchie 已提交
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
using System;
using System.Linq.Expressions;

public class D : C
{
    internal override void M() { }

    void Test()
    {
        D d = new D();
        d.M();
        int x = d.P;
        d.E += null;
    }

    void TestET() 
    {
        D d = new D();
        Expression<Action> expr = () => d.M();
    }
}
";

1341 1342 1343
            var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "asm1");
            comp1.VerifyDiagnostics();
            var ref1 = new CSharpCompilationReference(comp1);
P
Pilchie 已提交
1344

1345 1346 1347
            var comp2 = CreateCompilationWithMscorlib(source2, new[] { ref1 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "asm2");
            comp2.VerifyDiagnostics();
            var ref2 = new CSharpCompilationReference(comp2);
P
Pilchie 已提交
1348

1349 1350 1351
            var comp3 = CreateCompilationWithMscorlib(source3, new[] { ref1, ref2 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "asm3");
            comp3.VerifyDiagnostics();
            var ref3 = new CSharpCompilationReference(comp3);
P
Pilchie 已提交
1352

1353 1354
            var comp4 = CreateCompilationWithMscorlib(source4, new[] { SystemCoreRef, ref1, ref2, ref3 }, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "asm4");
            comp4.VerifyDiagnostics();
P
Pilchie 已提交
1355

1356 1357 1358
            // Note: calls C.M, not A.M, since asm2 is not accessible (stops search).
            // Confirmed in Dev11.
            var verifier = CompileAndVerify(comp4, emitOptions: TestEmitters.CCI);
1359

1360
            verifier.VerifyIL("D.Test", @"
P
Pilchie 已提交
1361
{
1362
  // Code size       25 (0x19)
P
Pilchie 已提交
1363 1364
  .maxstack  2
  IL_0000:  newobj     ""D..ctor()""
1365 1366 1367 1368 1369 1370 1371 1372
  IL_0005:  dup
  IL_0006:  callvirt   ""void C.M()""
  IL_000b:  dup
  IL_000c:  callvirt   ""int C.P.get""
  IL_0011:  pop
  IL_0012:  ldnull
  IL_0013:  callvirt   ""void C.E.add""
  IL_0018:  ret
P
Pilchie 已提交
1373 1374
}");

1375
            verifier.VerifyIL("D.TestET", @"
P
Pilchie 已提交
1376
{
1377
  // Code size       85 (0x55)
P
Pilchie 已提交
1378
  .maxstack  3
1379
  IL_0000:  newobj     ""D.<>c__DisplayClass2_0..ctor()""
1380 1381
  IL_0005:  dup
  IL_0006:  newobj     ""D..ctor()""
1382 1383
  IL_000b:  stfld      ""D D.<>c__DisplayClass2_0.d""
  IL_0010:  ldtoken    ""D.<>c__DisplayClass2_0""
1384 1385
  IL_0015:  call       ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
  IL_001a:  call       ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
1386
  IL_001f:  ldtoken    ""D D.<>c__DisplayClass2_0.d""
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
  IL_0024:  call       ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)""
  IL_0029:  call       ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)""
  IL_002e:  ldtoken    ""void C.M()""
  IL_0033:  call       ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
  IL_0038:  castclass  ""System.Reflection.MethodInfo""
  IL_003d:  ldc.i4.0
  IL_003e:  newarr     ""System.Linq.Expressions.Expression""
  IL_0043:  call       ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
  IL_0048:  ldc.i4.0
  IL_0049:  newarr     ""System.Linq.Expressions.ParameterExpression""
  IL_004e:  call       ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
  IL_0053:  pop
  IL_0054:  ret
P
Pilchie 已提交
1400
}");
1401
        }
P
Pilchie 已提交
1402

1403 1404 1405 1406
        [Fact]
        public void IvtVirtual_ParamsAndDynamic()
        {
            var source1 = @"
P
Pilchie 已提交
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")]

public class A
{
    internal virtual void F(params int[] a) { }
    internal virtual void G(System.Action<dynamic> a) { }

    [System.Obsolete(""obsolete"", true)]
    internal virtual void H() { }

    internal virtual int this[int x, params int[] a] { get { return 0; } }
}
";
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
            // use IL to generate code that doesn't have synthesized ParamArrayAttribute on int[] parameters:

            // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")]
            // public class B : A
            // {
            //     internal override void F(int[] a) { }                            
            //     internal override void G(System.Action<object> a) { }
            //     internal override void H() { }
            //     internal override int this[int x, int[] a] { get { return 0; } }
            // }

            var source2 = @"
P
Pilchie 已提交
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
.assembly extern asm1
{
  .ver 0:0:0:0
}
.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 4:0:0:0
}
.assembly asm2
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 04 61 73 6D 33 00 00 )                      // ...asm3..
}

.class public auto ansi beforefieldinit B extends [asm1]A
{
  .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 )                      // ...Item..
  
  .method assembly hidebysig strict virtual instance void  F(int32[] a) cil managed 
  {
    nop
    ret
  }

  .method assembly hidebysig strict virtual instance void  G(class [mscorlib]System.Action`1<object> a) cil managed
  {
    nop
    ret
  }

  .method assembly hidebysig strict virtual instance void  H() cil managed
  {
    nop
    ret
  }

  .method assembly hidebysig specialname strict virtual instance int32  get_Item(int32 x, int32[] a) cil managed
  {
    ldloc.0
    ret
  }

  .method public hidebysig specialname rtspecialname instance void  .ctor() cil managed
  {
    ldarg.0
    call       instance void [asm1]A::.ctor()
    ret
  }

  .property instance int32 Item(int32, int32[])
  {
    .get instance int32 B::get_Item(int32,
                                    int32[])
  }
}";

1488
            var source3 = @"
P
Pilchie 已提交
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
public class C : B
{
    void Test()
    {
        C c = new C();
        c.F();
        c.G(x => x.Bar());
        c.H();
        var z = c[1];
    }
}
";

1502 1503 1504 1505
            var comp1 = CreateCompilationWithMscorlib(source1,
                new[] { SystemCoreRef },
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider),
                assemblyName: "asm1");
P
Pilchie 已提交
1506

1507 1508
            comp1.VerifyDiagnostics();
            var ref1 = new CSharpCompilationReference(comp1);
P
Pilchie 已提交
1509

1510
            var ref2 = CompileIL(source2, appendDefaultHeader: false);
P
Pilchie 已提交
1511

1512 1513 1514 1515
            var comp3 = CreateCompilationWithMscorlib(source3,
                new[] { SystemCoreRef, ref1, ref2 },
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider),
                assemblyName: "asm3");
P
Pilchie 已提交
1516

1517 1518 1519 1520 1521 1522 1523 1524
            comp3.VerifyDiagnostics(
                // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.F(int[])'
                Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("a", "B.F(int[])").WithLocation(7, 11),
                // (8,20): error CS1061: 'object' does not contain a definition for 'Bar' and no extension method 'Bar' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
                Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Bar").WithArguments("object", "Bar").WithLocation(8, 20),
                // (10,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.this[int, int[]]'
                Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "c[1]").WithArguments("a", "B.this[int, int[]]").WithLocation(10, 17));
        }
P
Pilchie 已提交
1525

1526 1527 1528 1529 1530 1531
        [Fact]
        [WorkItem(529779, "DevDiv")]
        public void Bug529779_1()
        {
            CSharpCompilation unsigned = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1532 1533
public class C1
{}
1534
", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "Unsigned");
P
Pilchie 已提交
1535

1536 1537
            CSharpCompilation other = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1538 1539 1540 1541 1542 1543 1544 1545
public class C
{
    internal void Foo()
    {
        var x = new System.Guid();
        System.Console.WriteLine(x);
    }
}
1546
", options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1547

1548 1549
            CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), new CSharpCompilationReference(unsigned) }),
                             emitOptions: TestEmitters.CCI).VerifyDiagnostics();
P
Pilchie 已提交
1550

1551 1552 1553
            CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) }),
                             emitOptions: TestEmitters.CCI).VerifyDiagnostics();
        }
P
Pilchie 已提交
1554

1555 1556 1557 1558 1559 1560
        [Fact]
        [WorkItem(529779, "DevDiv")]
        public void Bug529779_2()
        {
            CSharpCompilation unsigned = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1561 1562
public class C1
{}
1563
", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "Unsigned");
P
Pilchie 已提交
1564

1565 1566
            CSharpCompilation other = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1567 1568 1569 1570 1571 1572 1573 1574
public class C
{
    internal void Foo()
    {
        var x = new C1();
        System.Console.WriteLine(x);
    }
}
1575
", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider).WithCryptoKeyFile(s_keyPairFile));
P
Pilchie 已提交
1576

1577
            var comps = new[] {other.WithReferences(new []{other.References.ElementAt(0), new CSharpCompilationReference(unsigned)}),
1578
                            other.WithReferences(new []{other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })};
P
Pilchie 已提交
1579

1580 1581 1582 1583
            foreach (var comp in comps)
            {
                var outStrm = new MemoryStream();
                var emitResult = comp.Emit(outStrm);
P
Pilchie 已提交
1584

1585 1586
                // Dev12 reports an error
                Assert.True(emitResult.Success);
P
Pilchie 已提交
1587

1588 1589 1590 1591
                emitResult.Diagnostics.Verify(
                    // warning CS8002: Referenced assembly 'Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name.
                    Diagnostic(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName).WithArguments("Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"));
            }
P
Pilchie 已提交
1592 1593
        }

1594 1595 1596 1597 1598
        [Fact]
        public void AssemblySignatureKeyAttribute_1()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1599 1600 1601 1602 1603 1604 1605 1606
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

public class C
{
  static void Foo() {}
}",
1607
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 });
P
Pilchie 已提交
1608

1609
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1610

1611 1612 1613 1614 1615
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.True(success.Success);
            }
P
Pilchie 已提交
1616

1617 1618
            AssertFileIsSigned(tempFile);
        }
P
Pilchie 已提交
1619

1620 1621 1622 1623 1624
        [Fact]
        public void AssemblySignatureKeyAttribute_2()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1625 1626 1627 1628 1629 1630 1631 1632
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

public class C
{
  static void Foo() {}
}",
1633
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 });
P
Pilchie 已提交
1634

1635
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1636

1637 1638 1639 1640 1641 1642 1643 1644 1645
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.False(success.Success);
                success.Diagnostics.Verify(
                    // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute.
                    // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb",
                    Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"""));
            }
P
Pilchie 已提交
1646 1647
        }

1648 1649 1650 1651 1652
        [Fact]
        public void AssemblySignatureKeyAttribute_3()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1653 1654 1655 1656 1657 1658 1659 1660
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

public class C
{
  static void Foo() {}
}",
1661
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 });
P
Pilchie 已提交
1662

1663
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1664

1665 1666 1667 1668 1669 1670 1671 1672
            using (var outStrm = tempFile.Open())
            {
                var result = other.Emit(outStrm);
                Assert.False(result.Success);
                result.Diagnostics.VerifyErrorCodes(
                    // error CS7027: Error signing output with public key from file 'KeyPairFile.snk' -- Invalid countersignature specified in AssemblySignatureKeyAttribute. (Exception from HRESULT: 0x80131423)
                    Diagnostic(ErrorCode.ERR_PublicKeyFileFailure));
            }
P
Pilchie 已提交
1673 1674
        }

1675 1676 1677 1678 1679
        [Fact]
        public void AssemblySignatureKeyAttribute_4()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1680 1681 1682 1683 1684 1685 1686 1687
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

public class C
{
  static void Foo() {}
}",
1688
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true).WithStrongNameProvider(s_defaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 });
P
Pilchie 已提交
1689

1690
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1691

1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.False(success.Success);
                success.Diagnostics.Verify(
        // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute.
        // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb",
        Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""")
                    );
            }
P
Pilchie 已提交
1702 1703
        }

1704 1705 1706 1707 1708
        [Fact]
        public void AssemblySignatureKeyAttribute_5()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1709 1710 1711 1712 1713 1714 1715 1716
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

public class C
{
  static void Foo() {}
}",
1717
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true).WithStrongNameProvider(s_defaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 });
P
Pilchie 已提交
1718

1719
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1720

1721 1722 1723 1724 1725
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.True(success.Success);
            }
P
Pilchie 已提交
1726 1727
        }

1728 1729 1730 1731 1732
        [Fact]
        public void AssemblySignatureKeyAttribute_6()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1733 1734 1735 1736 1737 1738 1739 1740
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
null,
""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

public class C
{
  static void Foo() {}
}",
1741
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true).WithStrongNameProvider(s_defaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 });
P
Pilchie 已提交
1742

1743
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1744

1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.False(success.Success);
                success.Diagnostics.Verify(
        // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute.
        // null,
        Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, "null")
                    );
            }
P
Pilchie 已提交
1755 1756
        }

1757 1758 1759 1760 1761
        [Fact]
        public void AssemblySignatureKeyAttribute_7()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1762 1763 1764 1765 1766 1767 1768 1769
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
null)]

public class C
{
  static void Foo() {}
}",
1770
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true).WithStrongNameProvider(s_defaultProvider), references: new[] { MscorlibRef_v4_0_30316_17626 });
P
Pilchie 已提交
1771

1772
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1773

1774 1775 1776 1777 1778
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.True(success.Success);
            }
P
Pilchie 已提交
1779 1780
        }

1781 1782 1783 1784 1785
        [Fact, WorkItem(769840, "DevDiv")]
        public void Bug769840()
        {
            var ca = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1786 1787 1788 1789 1790 1791
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Bug769840_B, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100458a131798af87d9e33088a3ab1c6101cbd462760f023d4f41d97f691033649e60b42001e94f4d79386b5e087b0a044c54b7afce151b3ad19b33b332b83087e3b8b022f45b5e4ff9b9a1077b0572ff0679ce38f884c7bd3d9b4090e4a7ee086b7dd292dc20f81a3b1b8a0b67ee77023131e59831c709c81d11c6856669974cc4"")]

internal class A
{
    public int Value = 3;
}
1792
", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "Bug769840_A");
P
Pilchie 已提交
1793

1794
            CompileAndVerify(ca);
P
Pilchie 已提交
1795

1796 1797
            var cb = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1798 1799 1800 1801 1802 1803
internal class B
{
    public A GetA()
    {
        return new A();
    }
1804
}",
1805 1806 1807
                options: TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider),
                assemblyName: "Bug769840_B",
                references: new[] { new CSharpCompilationReference(ca) });
P
Pilchie 已提交
1808

1809 1810
            CompileAndVerify(cb, verify: false).Diagnostics.Verify();
        }
P
Pilchie 已提交
1811

1812 1813 1814 1815
        [Fact, WorkItem(1072350, "DevDiv")]
        public void Bug1072350()
        {
            const string sourceA = @"
1816 1817 1818 1819 1820 1821
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""X "")]
internal class A
{
    internal static int I = 42;
}";

1822
            const string sourceB = @"
1823 1824 1825 1826 1827 1828 1829 1830
class B
{
    static void Main()
    {
        System.Console.Write(A.I);
    }
}";

1831 1832
            var ca = CreateCompilationWithMscorlib(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2");
            CompileAndVerify(ca);
1833

1834 1835 1836
            var cb = CreateCompilationWithMscorlib(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) });
            CompileAndVerify(cb, expectedOutput: "42", emitOptions: TestEmitters.CCI).Diagnostics.Verify();
        }
1837

1838 1839 1840 1841
        [Fact, WorkItem(1072339, "DevDiv")]
        public void Bug1072339()
        {
            const string sourceA = @"
1842 1843 1844 1845 1846 1847
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""x"")]
internal class A
{
    internal static int I = 42;
}";

1848
            const string sourceB = @"
1849 1850 1851 1852 1853 1854 1855 1856
class B
{
    static void Main()
    {
        System.Console.Write(A.I);
    }
}";

1857 1858
            var ca = CreateCompilationWithMscorlib(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2");
            CompileAndVerify(ca);
1859

1860 1861 1862
            var cb = CreateCompilationWithMscorlib(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) });
            CompileAndVerify(cb, expectedOutput: "42", emitOptions: TestEmitters.CCI).Diagnostics.Verify();
        }
P
Pilchie 已提交
1863

1864 1865 1866 1867
        [Fact, WorkItem(1095618, "DevDiv")]
        public void Bug1095618()
        {
            const string source = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")]";
1868

1869 1870 1871 1872 1873
            var ca = CreateCompilationWithMscorlib(source);
            ca.VerifyDiagnostics(
                // (1,12): warning CS1700: Assembly reference 'System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000' is invalid and cannot be resolved
                // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000")]
                Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")").WithArguments("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000").WithLocation(1, 12));
1874

1875 1876 1877 1878 1879 1880 1881
            var verifier = CompileAndVerify(ca, symbolValidator: module =>
            {
                var assembly = module.ContainingAssembly;
                Assert.NotNull(assembly);
                Assert.False(assembly.GetAttributes().Any(attr => attr.IsTargetAttribute(assembly, AttributeDescription.InternalsVisibleToAttribute)));
            });
        }
1882

1883 1884 1885
        #endregion
    }
}