InternalsVisibleToAndStrongNameTests.cs 93.8 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

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.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;

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

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

30 31 32 33 34 35 36 37 38
        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 已提交
39

40
        #endregion
P
Pilchie 已提交
41

42
        #region Naming Tests
P
Pilchie 已提交
43

J
Jared Parsons 已提交
44
        [Fact, WorkItem(529419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529419")]
45 46 47
        public void AssemblyKeyFileAttributeNotExistFile()
        {
            string source = @"
P
Pilchie 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61
using System;
using System.Reflection;

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

public class Test
{
    public static void Main()
    {
        Console.Write(""Hello World!"");
    }
}
";
62 63 64 65 66 67 68 69 70 71
            // 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 已提交
72

73 74 75 76 77
        [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 已提交
78

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

83
            CompileAndVerify(other, symbolValidator: (ModuleSymbol m) =>
T
Tomas Matousek 已提交
84 85
            {
                bool haveAttribute = false;
86

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

T
Tomas Matousek 已提交
96 97
                Assert.True(haveAttribute);
            });
98
        }
P
Pilchie 已提交
99

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

106 107
            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 已提交
108

109 110 111 112
            // 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 已提交
113

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

116 117 118 119 120 121
            // 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 已提交
122

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

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

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

134 135
            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 已提交
136

137 138 139 140 141
            // 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 已提交
142

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

145 146 147 148 149 150
            // 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\"))));
151

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

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

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

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

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

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

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 186
        [Fact]
        public void PubKeyFromKeyContainerAttribute()
P
Pilchie 已提交
187
        {
188 189 190 191 192 193
            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 已提交
194

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

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

208
                Assert.True(haveAttribute);
T
Tomas Matousek 已提交
209
            });
210
        }
P
Pilchie 已提交
211

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

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

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

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

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

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

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

240 241 242 243 244 245
            // 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 已提交
246

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

251 252 253 254 255 256 257
        [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();
258
            Assert.True(ByteSequenceComparer.Equals(TestResources.General.snPublicKey.AsImmutableOrNull(), other.Assembly.Identity.PublicKey));
259
        }
P
Pilchie 已提交
260

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

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

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

274 275 276 277 278 279
            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 已提交
280

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

283 284 285 286 287 288 289 290 291
            // 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 已提交
292

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

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

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

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

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

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

319
        [WorkItem(5662, "https://github.com/dotnet/roslyn/issues/5662")]
320
        [ConditionalFact(typeof(IsEnglishLocal))]
321 322 323 324 325
        public void PubKeyContainerBogusOptions()
        {
            string s = "public class C {}";
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyContainer("foo").WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
326

327 328
            // 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 已提交
329

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

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

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

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

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

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

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

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

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

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

372 373 374 375 376 377 378 379 380 381
        [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();
        }

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        [Fact]
        public void PublicKeyFromOptions_DelaySigned()
        {
            string source = @"
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C {}";

            var c = CreateCompilationWithMscorlib(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey));
            c.VerifyDiagnostics();
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey));

            var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray());
            var identity = metadata.Module.ReadAssemblyIdentityOrThrow();

            Assert.True(identity.HasPublicKey);
            AssertEx.Equal(identity.PublicKey, s_publicKey);
            Assert.Equal(CorFlags.ILOnly, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags);
        }

        [Fact]
A
Andy Gocke 已提交
402
        public void PublicKeyFromOptions_PublicSign()
403 404 405 406 407 408 409 410
        {
            // attributes are ignored
            string source = @"
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] 
[assembly: System.Reflection.AssemblyKeyFile(""some file"")] 
public class C {}
";

A
Andy Gocke 已提交
411
            var c = CreateCompilationWithMscorlib(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey).WithPublicSign(true));
412 413 414 415 416 417 418 419 420 421 422
            c.VerifyDiagnostics();
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey));

            var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray());
            var identity = metadata.Module.ReadAssemblyIdentityOrThrow();

            Assert.True(identity.HasPublicKey);
            AssertEx.Equal(identity.PublicKey, s_publicKey);
            Assert.Equal(CorFlags.ILOnly | CorFlags.StrongNameSigned, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags);
        }

A
Andy Gocke 已提交
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
        private void VerifySignedBitSetAfterEmit(Compilation comp)
        {
            var outStrm = new MemoryStream();
            var emitResult = comp.Emit(outStrm);
            Assert.True(emitResult.Success);

            outStrm.Position = 0;

            // Verify that the sign bit is set
            using (var reader = new PEReader(outStrm))
            {
                Assert.True(reader.HasMetadata);

                var flags = reader.PEHeaders.CorHeader.Flags;
                Assert.True(flags.HasFlag(CorFlags.StrongNameSigned));
            }
        }

A
Andy Gocke 已提交
441 442 443 444 445 446 447 448 449 450
        [Fact]
        public void SnkFile_PublicSign()
        {
            var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey);

            var comp = CreateCompilationWithMscorlib("public class C{}",
                options: TestOptions.ReleaseDll
                    .WithCryptoKeyFile(snk.Path)
                    .WithPublicSign(true));

451
            comp.VerifyDiagnostics();
A
Andy Gocke 已提交
452 453 454

            Assert.True(comp.Options.PublicSign);
            Assert.Null(comp.Options.DelaySign);
455
            Assert.False(comp.IsRealSigned);
A
Andy Gocke 已提交
456
            Assert.NotNull(comp.Options.CryptoKeyFile);
457

A
Andy Gocke 已提交
458
            VerifySignedBitSetAfterEmit(comp);
A
Andy Gocke 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        }

        [Fact]
        public void PublicKeyFile_PublicSign()
        {
            var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey);

            var comp = CreateCompilationWithMscorlib("public class C {}",
                options: TestOptions.ReleaseDll
                    .WithCryptoKeyFile(pubKeyFile.Path)
                    .WithPublicSign(true));

            comp.VerifyDiagnostics();

            Assert.True(comp.Options.PublicSign);
            Assert.Null(comp.Options.DelaySign);
            Assert.False(comp.IsRealSigned);
            Assert.NotNull(comp.Options.CryptoKeyFile);

A
Andy Gocke 已提交
478
            VerifySignedBitSetAfterEmit(comp);
A
Andy Gocke 已提交
479 480
        }

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
        [Fact]
        public void PublicSign_DelaySignAttribute()
        {
            var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey);

            var comp = CreateCompilationWithMscorlib(@"
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C {}",
                options: TestOptions.ReleaseDll
                    .WithCryptoKeyFile(pubKeyFile.Path)
                    .WithPublicSign(true));

            comp.VerifyDiagnostics(
    // warning CS1616: Option 'PublicSign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module
    Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("PublicSign", "System.Reflection.AssemblyDelaySignAttribute").WithLocation(1, 1));

            Assert.True(comp.Options.PublicSign);
            Assert.Null(comp.Options.DelaySign);
            Assert.False(comp.IsRealSigned);
            Assert.NotNull(comp.Options.CryptoKeyFile);

A
Andy Gocke 已提交
502
            VerifySignedBitSetAfterEmit(comp);
503 504
        }

A
Andy Gocke 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        [Fact]
        public void KeyContainerNoSNProvider_PublicSign()
        {
            var comp = CreateCompilationWithMscorlib("public class C {}",
                options: TestOptions.ReleaseDll
                    .WithCryptoKeyContainer("roslynTestContainer")
                    .WithPublicSign(true));

            comp.VerifyDiagnostics(
    // error CS7028: Error signing output with public key from container 'roslynTestContainer' -- Assembly signing not supported.
    Diagnostic(ErrorCode.ERR_PublicKeyContainerFailure).WithArguments("roslynTestContainer", "Assembly signing not supported.").WithLocation(1, 1),
    // error CS8102: Public signing was specified and requires a public key, but no public key was specified.
    Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1));
        }

        [Fact]
        public void KeyContainerDesktopProvider_PublicSign()
        {
            var comp = CreateCompilationWithMscorlib("public class C {}",
                options: TestOptions.ReleaseDll
                    .WithCryptoKeyContainer("roslynTestContainer")
                    .WithStrongNameProvider(s_defaultProvider)
                    .WithPublicSign(true));

            comp.VerifyDiagnostics();

            Assert.True(comp.Options.PublicSign);
            Assert.Null(comp.Options.DelaySign);
            Assert.False(comp.IsRealSigned);
            Assert.NotNull(comp.Options.CryptoKeyContainer);

A
Andy Gocke 已提交
536
            VerifySignedBitSetAfterEmit(comp);
A
Andy Gocke 已提交
537 538
        }

539 540 541 542 543 544 545 546 547 548 549 550 551 552
        [Fact]
        public void PublicSignAndDelaySign()
        {
            var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey);

            var comp = CreateCompilationWithMscorlib("public class C {}",
                options: TestOptions.ReleaseDll
                    .WithPublicSign(true)
                    .WithDelaySign(true)
                    .WithCryptoKeyFile(snk.Path));

            comp.VerifyDiagnostics(
    // error CS7102: Compilation options 'PublicSign' and 'DelaySign' can't both be specified at the same time.
    Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "DelaySign").WithLocation(1, 1));
A
Andy Gocke 已提交
553 554 555

            Assert.True(comp.Options.PublicSign);
            Assert.True(comp.Options.DelaySign);
556 557
        }

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
        [Fact]
        public void PublicSignAndDelaySignFalse()
        {
            var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey);

            var comp = CreateCompilationWithMscorlib("public class C {}",
                options: TestOptions.ReleaseDll
                    .WithPublicSign(true)
                    .WithDelaySign(false)
                    .WithCryptoKeyFile(snk.Path));

            comp.VerifyDiagnostics();

            Assert.True(comp.Options.PublicSign);
            Assert.False(comp.Options.DelaySign);
        }

A
Andy Gocke 已提交
575 576 577 578 579 580 581 582 583
        [Fact]
        public void PublicSignNoKey()
        {
            var comp = CreateCompilationWithMscorlib("public class C {}",
                options: TestOptions.ReleaseDll
                    .WithPublicSign(true));

            comp.VerifyDiagnostics(
    // error CS8102: Public signing was specified and requires a public key, but no public key was specified.
C
CyrusNajmabadi 已提交
584
    Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1));
A
Andy Gocke 已提交
585 586 587
            Assert.True(comp.Options.PublicSign);
            Assert.True(comp.Assembly.PublicKey.IsDefaultOrEmpty);
        }
588

589 590 591 592 593 594
        [Fact]
        public void PublicKeyFromOptions_InvalidCompilationOptions()
        {
            string source = @"public class C {}";

            var c = CreateCompilationWithMscorlib(source, options: TestOptions.ReleaseDll.
J
Jared Parsons 已提交
595
                WithCryptoPublicKey(ImmutableArray.Create<byte>(1, 2, 3)).
596 597 598 599 600 601 602 603 604 605 606 607 608
                WithCryptoKeyContainer("roslynTestContainer").
                WithCryptoKeyFile("file.snk").
                WithStrongNameProvider(s_defaultProvider));

            c.VerifyDiagnostics(
                // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyFile' can't both be specified at the same time.
                Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyFile").WithLocation(1, 1),
                // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyContainer' can't both be specified at the same time.
                Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyContainer").WithLocation(1, 1),
                // error CS7088: Invalid 'CryptoPublicKey' value: '01-02-03'.
                Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("CryptoPublicKey", "01-02-03").WithLocation(1, 1));
        }

609 610 611 612 613 614 615 616
        #endregion

        #region IVT Access Checking

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

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

621 622
            var c = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
623 624 625 626 627 628 629 630 631
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
632 633 634
                new[] { new CSharpCompilationReference(other) },
                assemblyName: "WantsIVTAccessButCantHave",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
635

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

639 640
            var c2 = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
641 642 643 644 645 646 647 648 649
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
650 651 652
                new[] { new CSharpCompilationReference(other) },
                assemblyName: "WantsIVTAccess",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
653

654 655
            Assert.Empty(c2.GetDiagnostics());
        }
P
Pilchie 已提交
656

657 658 659 660
        [Fact]
        public void IVTBasicMetadata()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")]
P
Pilchie 已提交
661 662
            public class C { internal void Foo() {} }";

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

665 666
            var c = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
667 668 669 670 671 672 673 674 675
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
676 677 678
            references: new[] { AssemblyMetadata.CreateFromStream(otherStream, leaveOpen: true).GetReference() },
            assemblyName: "WantsIVTAccessButCantHave",
            options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
679

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

683
            otherStream.Position = 0;
P
Pilchie 已提交
684

685 686
            var c2 = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
687 688 689 690 691 692 693 694 695
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
696 697 698
                new[] { MetadataReference.CreateFromStream(otherStream) },
                assemblyName: "WantsIVTAccess",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
699

700 701
            Assert.Empty(c2.GetDiagnostics());
        }
P
Pilchie 已提交
702

703 704 705 706
        [Fact]
        public void IVTSigned()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
707 708
            public class C { internal void Foo() {} }";

709 710 711
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider),
                assemblyName: "Paul");
P
Pilchie 已提交
712

713
            other.VerifyDiagnostics();
P
Pilchie 已提交
714

715 716
            var requestor = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
717 718 719 720 721 722 723 724 725
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
726 727 728
                new MetadataReference[] { new CSharpCompilationReference(other) },
                TestOptions.ReleaseDll.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider),
                assemblyName: "John");
P
Pilchie 已提交
729

730 731
            Assert.Empty(requestor.GetDiagnostics());
        }
P
Pilchie 已提交
732

733 734 735 736
        [Fact]
        public void IVTErrorNotBothSigned()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
737 738
            public class C { internal void Foo() {} }";

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

742 743
            var requestor = CreateCompilationWithMscorlib(
    @"public class A
P
Pilchie 已提交
744 745 746 747 748 749 750 751 752
{
    internal class B
    {
        protected B(C o)
        {
            o.Foo();
        }
    }
}",
753 754 755
                references: new[] { new CSharpCompilationReference(other) },
                assemblyName: "John",
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
756

757 758
            // 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 已提交
759

760 761 762 763
            // 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 已提交
764

765 766 767 768
        [Fact]
        public void IVTDeferredSuccess()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
769 770
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

771 772 773
            var other = CreateCompilationWithMscorlib(s,
                assemblyName: "Paul",
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
774

775
            other.VerifyDiagnostics();
P
Pilchie 已提交
776

777 778
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
779 780 781 782 783
[assembly: C()]  //causes optimistic granting
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class A
{
}",
784 785 786
                new[] { new CSharpCompilationReference(other) },
                assemblyName: "John",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
787

788 789 790
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey));
            Assert.Empty(requestor.GetDiagnostics());
        }
P
Pilchie 已提交
791

792 793 794 795
        [Fact]
        public void IVTDeferredFailSignMismatch()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
796 797
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

798 799 800
            var other = CreateCompilationWithMscorlib(s,
                assemblyName: "Paul",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)); //not signed. cryptoKeyFile: KeyPairFile,
P
Pilchie 已提交
801

802
            other.VerifyDiagnostics();
P
Pilchie 已提交
803

804 805
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
806 807 808 809 810
[assembly: C()] //causes optimistic granting
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class A
{
}",
811 812 813
                new[] { new CSharpCompilationReference(other) },
                assemblyName: "John",
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
814

815
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey));
T
Tomas Matousek 已提交
816 817
            requestor.VerifyDiagnostics(
                Diagnostic(ErrorCode.ERR_FriendRefSigningMismatch, arguments: new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" }));
818
        }
P
Pilchie 已提交
819

820 821 822 823 824
        [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 已提交
825 826
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

827 828 829
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider),
                assemblyName: "Paul");
P
Pilchie 已提交
830

831
            other.VerifyDiagnostics();
P
Pilchie 已提交
832

833 834
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
835 836 837 838 839
[assembly: C()]  //causes optimistic granting
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class A
{
}",
840 841 842
              new MetadataReference[] { new CSharpCompilationReference(other) },
              assemblyName: "John",
              options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
843

844
            Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey));
T
Tomas Matousek 已提交
845
            requestor.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, arguments: new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2" }));
846
        }
P
Pilchie 已提交
847

848 849 850 851
        [Fact]
        public void IVTSuccessThroughIAssembly()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
852 853
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

854 855 856
            var other = CreateCompilationWithMscorlib(s,
                assemblyName: "Paul",
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
857

858
            other.VerifyDiagnostics();
P
Pilchie 已提交
859

860 861
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
862 863 864 865 866
[assembly: C()]  //causes optimistic granting
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class A
{
}",
867 868 869
                new MetadataReference[] { new CSharpCompilationReference(other) },
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider),
                assemblyName: "John");
P
Pilchie 已提交
870

871 872 873
            Assert.True(((IAssemblySymbol)other.Assembly).GivesAccessTo(requestor.Assembly));
            Assert.Empty(requestor.GetDiagnostics());
        }
P
Pilchie 已提交
874

875 876 877 878 879
        [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 已提交
880 881
            internal class CAttribute : System.Attribute { public CAttribute() {} }";

882 883 884
            var other = CreateCompilationWithMscorlib(s,
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider),
                assemblyName: "Paul");
P
Pilchie 已提交
885

886
            other.VerifyDiagnostics();
P
Pilchie 已提交
887

888 889
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
890 891 892 893 894 895

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

900
            Assert.False(((IAssemblySymbol)other.Assembly).GivesAccessTo(requestor.Assembly));
T
Tomas Matousek 已提交
901
            requestor.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, arguments: new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2" }));
902
        }
P
Pilchie 已提交
903

J
Jared Parsons 已提交
904
        [WorkItem(820450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820450")]
905 906 907 908
        [Fact]
        public void IVTGivesAccessToUsingDifferentKeys()
        {
            string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
P
Pilchie 已提交
909 910
            namespace ClassLibrary1 { internal class Class1 { } } ";

911 912 913
            var giver = CreateCompilationWithMscorlib(s,
                assemblyName: "Paul",
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile2).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
914

915
            giver.VerifyDiagnostics();
P
Pilchie 已提交
916

917 918
            var requestor = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
919 920 921 922 923 924 925 926 927
namespace ClassLibrary2
{
    internal class A
    {
        public void Foo(ClassLibrary1.Class1 a)
        {   
        }
    }
}",
928 929 930
                new MetadataReference[] { new CSharpCompilationReference(giver) },
                options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider),
                assemblyName: "John");
P
Pilchie 已提交
931

932 933 934 935
            Assert.True(((IAssemblySymbol)giver.Assembly).GivesAccessTo(requestor.Assembly));
            Assert.Empty(requestor.GetDiagnostics());
        }
        #endregion
P
Pilchie 已提交
936

937
        #region IVT instantiations
P
Pilchie 已提交
938

939 940 941 942 943
        [Fact]
        public void IVTHasCulture()
        {
            var other = CreateCompilationWithMscorlib(
            @"
P
Pilchie 已提交
944 945 946 947 948 949
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")]
public class C
{
  static void Foo() {}
}
950
", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
951

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

955 956 957 958 959
        [Fact]
        public void IVTNoKey()
        {
            var other = CreateCompilationWithMscorlib(
            @"
P
Pilchie 已提交
960 961 962 963 964 965
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""WantsIVTAccess"")]
public class C
{
  static void Main() {}
}
966
", options: TestOptions.ReleaseExe.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
967

968 969
            other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblySNReq, @"InternalsVisibleTo(""WantsIVTAccess"")").WithArguments("WantsIVTAccess"));
        }
P
Pilchie 已提交
970

971
        #endregion
P
Pilchie 已提交
972

973
        #region Signing
P
Pilchie 已提交
974

975 976 977 978 979
        [Fact]
        public void SignIt()
        {
            var other = CreateCompilationWithMscorlib(
            @"
P
Pilchie 已提交
980 981 982 983
public class C
{
  static void Foo() {}
}",
984
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
985

986
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
987

988 989 990 991 992
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.True(success.Success);
            }
P
Pilchie 已提交
993

994 995
            AssertFileIsSigned(tempFile);
        }
P
Pilchie 已提交
996

997
        private static void AssertFileIsSigned(TempFile file)
P
Pilchie 已提交
998
        {
999 1000 1001 1002 1003 1004
            //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 已提交
1005 1006
        }

1007
        private void ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(MemoryStream moduleContents, AttributeDescription expectedModuleAttr)
P
Pilchie 已提交
1008
        {
1009 1010 1011
            //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 已提交
1012

1013 1014 1015 1016 1017 1018 1019 1020 1021
            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));
1022
                EntityHandle token = metadata.Module.GetTypeRef(metadata.Module.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere");
1023 1024 1025 1026 1027
                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 已提交
1028 1029 1030 1031
public class Z
{
}";

1032
                //now that the module checks out, ensure that adding it to a compilation outputting a dll
1033 1034 1035 1036
                //results in a signed assembly.
                var assemblyComp = CreateCompilationWithMscorlib(source,
                    new[] { metadata.GetReference() },
                    TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1037

1038 1039 1040 1041
                using (var finalStrm = tempFile.Open())
                {
                    success = assemblyComp.Emit(finalStrm);
                }
P
Pilchie 已提交
1042 1043
            }

1044
            success.Diagnostics.Verify();
P
Pilchie 已提交
1045

1046 1047 1048
            Assert.True(success.Success);
            AssertFileIsSigned(tempFile);
        }
P
Pilchie 已提交
1049

1050 1051 1052 1053 1054
        [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 已提交
1055

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

1058 1059 1060
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
1061

1062 1063
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute);
        }
P
Pilchie 已提交
1064

1065 1066 1067 1068
        [Fact]
        public void SignModuleKeyContainerAttr()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}";
P
Pilchie 已提交
1069

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

1072 1073 1074
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
1075

1076 1077
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute);
        }
P
Pilchie 已提交
1078

1079
        [WorkItem(5665, "https://github.com/dotnet/roslyn/issues/5665")]
1080
        [ConditionalFact(typeof(IsEnglishLocal))]
1081 1082 1083
        public void SignModuleKeyContainerBogus()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}";
P
Pilchie 已提交
1084

1085 1086 1087
            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 已提交
1088

1089
            s = @"class D {}";
P
Pilchie 已提交
1090

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

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

1096 1097 1098
            Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code);
            Assert.Equal(2, err.Arguments.Count);
            Assert.Equal("bogus", err.Arguments[0]);
1099
            Assert.True(((string)err.Arguments[1]).EndsWith(" HRESULT: 0x80090016)", StringComparison.Ordinal));
1100
        }
P
Pilchie 已提交
1101

1102 1103 1104 1105
        [Fact]
        public void SignModuleKeyFileBogus()
        {
            string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}";
P
Pilchie 已提交
1106

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

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

1112
            s = @"class D {}";
P
Pilchie 已提交
1113

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

J
Jared Parsons 已提交
1118
        [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")]
1119 1120 1121 1122
        [Fact()]
        public void SignModuleKeyContainerCmdLine()
        {
            string s = "public class C {}";
P
Pilchie 已提交
1123

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

1126 1127 1128
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
1129

1130 1131
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute);
        }
P
Pilchie 已提交
1132

J
Jared Parsons 已提交
1133
        [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")]
1134 1135 1136 1137
        [Fact()]
        public void SignModuleKeyContainerCmdLine_1()
        {
            string s = @"
P
Pilchie 已提交
1138 1139 1140
[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")]
public class C {}";

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

1144 1145 1146
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
1147

1148 1149
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute);
        }
P
Pilchie 已提交
1150

J
Jared Parsons 已提交
1151
        [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")]
1152 1153 1154 1155
        [Fact()]
        public void SignModuleKeyContainerCmdLine_2()
        {
            string s = @"
P
Pilchie 已提交
1156 1157 1158
[assembly: System.Reflection.AssemblyKeyName(""bogus"")]
public class C {}";

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

1161 1162 1163 1164 1165 1166 1167 1168
            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 已提交
1169

J
Jared Parsons 已提交
1170
        [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")]
1171 1172 1173 1174
        [Fact()]
        public void SignModuleKeyFileCmdLine()
        {
            string s = "public class C {}";
P
Pilchie 已提交
1175

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

1178 1179 1180
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
1181

1182 1183
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute);
        }
P
Pilchie 已提交
1184

J
Jared Parsons 已提交
1185
        [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")]
1186 1187 1188 1189 1190
        [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 已提交
1191

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

1194 1195 1196
            var outStrm = new MemoryStream();
            var success = other.Emit(outStrm);
            Assert.True(success.Success);
P
Pilchie 已提交
1197

1198 1199
            ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute);
        }
P
Pilchie 已提交
1200

J
Jared Parsons 已提交
1201
        [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")]
1202 1203 1204 1205 1206
        [Fact()]
        public void SignModuleKeyFileCmdLine_2()
        {
            var x = s_keyPairFile;
            string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}";
P
Pilchie 已提交
1207

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

1210 1211 1212 1213 1214 1215 1216
            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 已提交
1217

1218 1219 1220 1221 1222
        [Fact]
        public void SignItWithOnlyPublicKey()
        {
            var other = CreateCompilationWithMscorlib(
            @"
P
Pilchie 已提交
1223 1224 1225 1226
public class C
{
  static void Foo() {}
}",
1227
      options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1228

1229 1230 1231
            var outStrm = new MemoryStream();
            var emitResult = other.Emit(outStrm);
            other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile));
P
Pilchie 已提交
1232

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

1235 1236 1237
            var assembly = CreateCompilationWithMscorlib("",
                references: new[] { other.EmitToImageReference() },
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1238

1239 1240
            assembly.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile));
        }
P
Pilchie 已提交
1241

1242 1243 1244 1245 1246
        [Fact]
        public void DelaySignItWithOnlyPublicKey()
        {
            var other = CreateCompilationWithMscorlib(
                @"
P
Pilchie 已提交
1247 1248 1249 1250
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C
{
  static void Foo() {}
1251
}", options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1252

1253 1254 1255 1256 1257
            using (var outStrm = new MemoryStream())
            {
                var emitResult = other.Emit(outStrm);
                Assert.True(emitResult.Success);
            }
P
Pilchie 已提交
1258 1259
        }

1260 1261 1262 1263 1264
        [Fact]
        public void DelaySignButNoKey()
        {
            var other = CreateCompilationWithMscorlib(
                @"
P
Pilchie 已提交
1265 1266 1267 1268 1269
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C
{
  static void Foo() {}
}",
1270
      options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1271

1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
            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 已提交
1286 1287 1288 1289
public class C
{
  static void Foo() {}
}",
1290 1291 1292 1293 1294
    options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
            var outStrm = new MemoryStream();
            var emitResult = other.Emit(outStrm);
            Assert.True(emitResult.Success);
        }
P
Pilchie 已提交
1295

1296 1297 1298 1299 1300
        [Fact]
        public void DelaySignConflict()
        {
            var other = CreateCompilationWithMscorlib(
                @"
P
Pilchie 已提交
1301 1302 1303 1304
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C
{
  static void Foo() {}
1305
}", options: TestOptions.ReleaseDll.WithDelaySign(false).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1306

1307 1308 1309 1310 1311 1312
            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 已提交
1313

1314 1315 1316 1317 1318
        [Fact]
        public void DelaySignNoConflict()
        {
            var other = CreateCompilationWithMscorlib(
                @"
P
Pilchie 已提交
1319 1320 1321 1322
[assembly: System.Reflection.AssemblyDelaySign(true)]
public class C
{
  static void Foo() {}
1323
}", options: TestOptions.ReleaseDll.WithDelaySign(true).WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1324

1325 1326 1327 1328 1329 1330
            var outStrm = new MemoryStream();
            //shouldn't get any key warning.
            other.VerifyDiagnostics();
            var emitResult = other.Emit(outStrm);
            Assert.True(emitResult.Success);
        }
P
Pilchie 已提交
1331

1332 1333 1334 1335 1336
        [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 已提交
1337

1338 1339 1340 1341
            //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 已提交
1342

1343 1344
            var other = CreateCompilation(
                @"
P
Pilchie 已提交
1345 1346 1347 1348 1349
[assembly: System.Reflection.AssemblyDelaySign(true)]
[assembly: System.Reflection.AssemblySignatureKey(""002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3"", ""a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d"")]
public class C
{
  static void Foo() {}
1350
}",
1351 1352
                new MetadataReference[] { MscorlibRef_v4_0_30316_17626 },
                options: TestOptions.ReleaseDll.WithDelaySign(true).WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1353

1354 1355 1356 1357 1358 1359
            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 已提交
1360 1361
        }

J
Jared Parsons 已提交
1362 1363
        [WorkItem(545720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545720")]
        [WorkItem(530050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530050")]
1364 1365 1366 1367
        [Fact]
        public void InvalidAssemblyName()
        {
            var il = @"
P
Pilchie 已提交
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
.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
  }
}
";

1387
            var csharp = @"
P
Pilchie 已提交
1388 1389 1390 1391 1392
class Derived : Base 
{
}
";

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

1395 1396 1397
            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 已提交
1398

1399 1400 1401 1402
                // (2,17): error CS0122: 'Base' is inaccessible due to its protection level
                // class Derived : Base 
                Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("Base"));
        }
P
Pilchie 已提交
1403

J
Jared Parsons 已提交
1404
        [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")]
1405 1406 1407 1408
        [Fact]
        public void IvtVirtualCall1()
        {
            var source1 = @"
P
Pilchie 已提交
1409 1410 1411 1412 1413 1414 1415 1416 1417
[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 { } }
}
";
1418
            var source2 = @"
P
Pilchie 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427
[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 { } }
}
";
1428
            var source3 = @"
P
Pilchie 已提交
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
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();
    }
}
";

1452 1453 1454
            var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "asm1");
            comp1.VerifyDiagnostics();
            var ref1 = new CSharpCompilationReference(comp1);
P
Pilchie 已提交
1455

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

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

1463
            // Note: calls B.M, not A.M, since asm1 is not accessible.
T
Tomas Matousek 已提交
1464
            var verifier = CompileAndVerify(comp3);
1465

1466
            verifier.VerifyIL("C.Test", @"
P
Pilchie 已提交
1467
{
1468
  // Code size       25 (0x19)
P
Pilchie 已提交
1469 1470
  .maxstack  2
  IL_0000:  newobj     ""C..ctor()""
1471 1472 1473 1474 1475 1476 1477 1478
  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 已提交
1479 1480
}");

1481
            verifier.VerifyIL("C.TestET", @"
P
Pilchie 已提交
1482
{
1483
  // Code size       85 (0x55)
P
Pilchie 已提交
1484
  .maxstack  3
1485
  IL_0000:  newobj     ""C.<>c__DisplayClass2_0..ctor()""
1486 1487
  IL_0005:  dup
  IL_0006:  newobj     ""C..ctor()""
1488 1489
  IL_000b:  stfld      ""C C.<>c__DisplayClass2_0.c""
  IL_0010:  ldtoken    ""C.<>c__DisplayClass2_0""
1490 1491
  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)""
1492
  IL_001f:  ldtoken    ""C C.<>c__DisplayClass2_0.c""
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
  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 已提交
1506 1507
}
");
1508
        }
P
Pilchie 已提交
1509

J
Jared Parsons 已提交
1510
        [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")]
1511 1512 1513 1514
        [Fact]
        public void IvtVirtualCall2()
        {
            var source1 = @"
P
Pilchie 已提交
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
[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 { } }
}
";
1525
            var source2 = @"
P
Pilchie 已提交
1526 1527 1528 1529 1530 1531 1532 1533 1534
[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 { } }
}
";
1535
            var source3 = @"
P
Pilchie 已提交
1536 1537 1538 1539 1540 1541 1542 1543 1544
[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 { } }
}
";
1545
            var source4 = @"
P
Pilchie 已提交
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
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();
    }
}
";

1569 1570 1571
            var comp1 = CreateCompilationWithMscorlib(source1, options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "asm1");
            comp1.VerifyDiagnostics();
            var ref1 = new CSharpCompilationReference(comp1);
P
Pilchie 已提交
1572

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

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

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

1584 1585
            // Note: calls C.M, not A.M, since asm2 is not accessible (stops search).
            // Confirmed in Dev11.
T
Tomas Matousek 已提交
1586
            var verifier = CompileAndVerify(comp4);
1587

1588
            verifier.VerifyIL("D.Test", @"
P
Pilchie 已提交
1589
{
1590
  // Code size       25 (0x19)
P
Pilchie 已提交
1591 1592
  .maxstack  2
  IL_0000:  newobj     ""D..ctor()""
1593 1594 1595 1596 1597 1598 1599 1600
  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 已提交
1601 1602
}");

1603
            verifier.VerifyIL("D.TestET", @"
P
Pilchie 已提交
1604
{
1605
  // Code size       85 (0x55)
P
Pilchie 已提交
1606
  .maxstack  3
1607
  IL_0000:  newobj     ""D.<>c__DisplayClass2_0..ctor()""
1608 1609
  IL_0005:  dup
  IL_0006:  newobj     ""D..ctor()""
1610 1611
  IL_000b:  stfld      ""D D.<>c__DisplayClass2_0.d""
  IL_0010:  ldtoken    ""D.<>c__DisplayClass2_0""
1612 1613
  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)""
1614
  IL_001f:  ldtoken    ""D D.<>c__DisplayClass2_0.d""
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
  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 已提交
1628
}");
1629
        }
P
Pilchie 已提交
1630

1631 1632 1633 1634
        [Fact]
        public void IvtVirtual_ParamsAndDynamic()
        {
            var source1 = @"
P
Pilchie 已提交
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
[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; } }
}
";
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
            // 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 已提交
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
.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[])
  }
}";

1716
            var source3 = @"
P
Pilchie 已提交
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
public class C : B
{
    void Test()
    {
        C c = new C();
        c.F();
        c.G(x => x.Bar());
        c.H();
        var z = c[1];
    }
}
";

1730 1731 1732 1733
            var comp1 = CreateCompilationWithMscorlib(source1,
                new[] { SystemCoreRef },
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider),
                assemblyName: "asm1");
P
Pilchie 已提交
1734

1735 1736
            comp1.VerifyDiagnostics();
            var ref1 = new CSharpCompilationReference(comp1);
P
Pilchie 已提交
1737

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

1740 1741 1742 1743
            var comp3 = CreateCompilationWithMscorlib(source3,
                new[] { SystemCoreRef, ref1, ref2 },
                options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider),
                assemblyName: "asm3");
P
Pilchie 已提交
1744

1745 1746 1747 1748 1749 1750 1751 1752
            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 已提交
1753

1754
        [Fact]
J
Jared Parsons 已提交
1755
        [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")]
1756 1757 1758 1759
        public void Bug529779_1()
        {
            CSharpCompilation unsigned = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1760 1761
public class C1
{}
1762
", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "Unsigned");
P
Pilchie 已提交
1763

1764 1765
            CSharpCompilation other = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1766 1767 1768 1769 1770 1771 1772 1773
public class C
{
    internal void Foo()
    {
        var x = new System.Guid();
        System.Console.WriteLine(x);
    }
}
1774
", options: TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider));
P
Pilchie 已提交
1775

T
Tomas Matousek 已提交
1776
            CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), new CSharpCompilationReference(unsigned) })).VerifyDiagnostics();
P
Pilchie 已提交
1777

T
Tomas Matousek 已提交
1778
            CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })).VerifyDiagnostics();
1779
        }
P
Pilchie 已提交
1780

1781
        [Fact]
J
Jared Parsons 已提交
1782
        [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")]
1783 1784 1785 1786
        public void Bug529779_2()
        {
            CSharpCompilation unsigned = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1787 1788
public class C1
{}
1789
", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider), assemblyName: "Unsigned");
P
Pilchie 已提交
1790

1791 1792
            CSharpCompilation other = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
1793 1794 1795 1796 1797 1798 1799 1800
public class C
{
    internal void Foo()
    {
        var x = new C1();
        System.Console.WriteLine(x);
    }
}
1801
", options: TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider).WithCryptoKeyFile(s_keyPairFile));
P
Pilchie 已提交
1802

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

1806 1807 1808 1809
            foreach (var comp in comps)
            {
                var outStrm = new MemoryStream();
                var emitResult = comp.Emit(outStrm);
P
Pilchie 已提交
1810

1811 1812
                // Dev12 reports an error
                Assert.True(emitResult.Success);
P
Pilchie 已提交
1813

1814 1815 1816 1817
                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 已提交
1818 1819
        }

1820 1821
        [Fact]
        [WorkItem(399, "https://github.com/dotnet/roslyn/issues/399")]
V
Vladimir Reshetnikov 已提交
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
        public void Bug399()
        {
            // The referenced assembly Signed.dll from the repro steps
            var signed = CreateMetadataReferenceFromHexGZipImage(@"
1f8b0800000000000400f38d9ac0c0ccc0c0c002c4ffff3330ec6080000706c2a00188f9e477f1316ce13cabb883d1e7ac62
484666b14241517e7a5162ae4272625e5e7e894252aa4251699e42669e828b7fb0426e7e4aaa1e2f2f970ad48c005706061f
4626869e0db74260e63e606052e466e486388a0922f64f094828c01d26006633419430302068860488f8790f06a0bf1c5a41
4a410841c32930580334d71f9f2781f6f11011161800e83e0e242e0790ef81c4d72b49ad2801b99b19a216d9af484624e815
a5e6e42743dde00055c386e14427729c08020f9420b407d86856860b404bef30323070a2a90b5080c4372120f781b1f3ada8
5ec1078b0a8f606f87dacdfeae3b162edb7de055d1af12c942bde5a267ef37e6c6b787945936b0ece367e8f6f87566c6f7bd
46a67f5da4f50d2f8a7e95e159552d1bf747b3ccdae1679c666dd10626bb1bf9815ad1c1876d04a76d78163e4b32a8a77fb3
a77adbec4d15c75de79cd9a3a4a5155dd1fc50b86ce5bd7797cce73b057b3931323082dd020ab332133d033d630363434b90
082b430e90ac0162e53a06861740da00c40e2e29cacc4b2f06a9906084c49b72683083022324ad28bb877aba80d402f96b40
7ca79cfc24a87f81d1c1c8ca000daf5faac60c620c60db41d1c408c50c0c5c509a012e0272e3425078c1792c0d0c48aa407a
d41890d2355895288263e39b9f529a936ac7109c999e979aa2979293c3905b9c9c5f949399c4e0091184ca81d5332b80a9a9
8764e24b67aff2dff0feb1f6c7b7e6d50c1cdbab62c2244d1e74362c6000664a902ba600d5b1813c00e407053b1a821c0172
e1dddd9665aa576abb26acf9f6e2eaeaab7527ed1f49174726fc8f395ad7c676f650da9c159bbcd6a73cd031d8a9762d8d6b
47f9eac4955b0566f61fbc9010e4bbf0c405d6e6cc8392f63e6f4bc5339f2d9bb9725d79c0d5cecbacacc9af4522debeb30a
bebd207fe9963cbbe995f66bb227ac4c0cfd91c3dce095617a66ce0e9d0b9e8eae9b25965c514278ff1dac3cc0021e2821f3
e29df38b5c72727c1333f32001949a0a0e2c10f8af0a344300ab2123052840cb16e30176c72818100000c85fc49900080000", filePath: "Signed.dll");

            var compilation = CreateCompilationWithMscorlib(
B
beep boop 已提交
1844
                "interface IDerived : ISigned { }",
V
Vladimir Reshetnikov 已提交
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
                references: new[] { signed },
                options: TestOptions.ReleaseDll
                    .WithGeneralDiagnosticOption(ReportDiagnostic.Error)
                    .WithStrongNameProvider(s_defaultProvider)
                    .WithCryptoKeyFile(s_keyPairFile));

            // ACTUAL: error CS8002: Referenced assembly 'Signed, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name.
            // EXPECTED: no errors
            compilation.VerifyEmitDiagnostics();
        }

1856 1857 1858 1859 1860
        [Fact]
        public void AssemblySignatureKeyAttribute_1()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1861 1862 1863 1864 1865 1866 1867 1868
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

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

1871
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1872

1873 1874 1875 1876 1877
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.True(success.Success);
            }
P
Pilchie 已提交
1878

1879 1880
            AssertFileIsSigned(tempFile);
        }
P
Pilchie 已提交
1881

1882 1883 1884 1885 1886
        [Fact]
        public void AssemblySignatureKeyAttribute_2()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1887 1888 1889 1890 1891 1892 1893 1894
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

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

1897
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1898

1899 1900 1901 1902 1903 1904 1905 1906 1907
            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 已提交
1908 1909
        }

1910
        [ConditionalFact(typeof(IsEnglishLocal))]
1911 1912 1913 1914
        public void AssemblySignatureKeyAttribute_3()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1915 1916 1917 1918 1919 1920 1921 1922
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

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

1925
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1926

1927 1928 1929 1930 1931 1932 1933 1934
            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 已提交
1935 1936
        }

1937 1938 1939 1940 1941
        [Fact]
        public void AssemblySignatureKeyAttribute_4()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1942 1943 1944 1945 1946 1947 1948 1949
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

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

1952
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1953

1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
            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 已提交
1964 1965
        }

1966 1967 1968 1969 1970
        [Fact]
        public void AssemblySignatureKeyAttribute_5()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1971 1972 1973 1974 1975 1976 1977 1978
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

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

1981
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
1982

1983 1984 1985 1986 1987
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.True(success.Success);
            }
P
Pilchie 已提交
1988 1989
        }

1990 1991 1992 1993 1994
        [Fact]
        public void AssemblySignatureKeyAttribute_6()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
1995 1996 1997 1998 1999 2000 2001 2002
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
null,
""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")]

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

2005
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
2006

2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
            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 已提交
2017 2018
        }

2019 2020 2021 2022 2023
        [Fact]
        public void AssemblySignatureKeyAttribute_7()
        {
            var other = CreateCompilation(
            @"
P
Pilchie 已提交
2024 2025 2026 2027 2028 2029 2030 2031
[assembly: System.Reflection.AssemblySignatureKeyAttribute(
""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"",
null)]

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

2034
            var tempFile = Temp.CreateFile();
P
Pilchie 已提交
2035

2036 2037 2038 2039 2040
            using (var outStrm = tempFile.Open())
            {
                var success = other.Emit(outStrm);
                Assert.True(success.Success);
            }
P
Pilchie 已提交
2041 2042
        }

J
Jared Parsons 已提交
2043
        [Fact, WorkItem(769840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769840")]
2044 2045 2046 2047
        public void Bug769840()
        {
            var ca = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
2048 2049 2050 2051 2052 2053
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Bug769840_B, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100458a131798af87d9e33088a3ab1c6101cbd462760f023d4f41d97f691033649e60b42001e94f4d79386b5e087b0a044c54b7afce151b3ad19b33b332b83087e3b8b022f45b5e4ff9b9a1077b0572ff0679ce38f884c7bd3d9b4090e4a7ee086b7dd292dc20f81a3b1b8a0b67ee77023131e59831c709c81d11c6856669974cc4"")]

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

2056
            CompileAndVerify(ca);
P
Pilchie 已提交
2057

2058 2059
            var cb = CreateCompilationWithMscorlib(
    @"
P
Pilchie 已提交
2060 2061 2062 2063 2064 2065
internal class B
{
    public A GetA()
    {
        return new A();
    }
2066
}",
2067 2068 2069
                options: TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider),
                assemblyName: "Bug769840_B",
                references: new[] { new CSharpCompilationReference(ca) });
P
Pilchie 已提交
2070

2071 2072
            CompileAndVerify(cb, verify: false).Diagnostics.Verify();
        }
P
Pilchie 已提交
2073

J
Jared Parsons 已提交
2074
        [Fact, WorkItem(1072350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072350")]
2075 2076 2077
        public void Bug1072350()
        {
            const string sourceA = @"
2078 2079 2080 2081 2082 2083
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""X "")]
internal class A
{
    internal static int I = 42;
}";

2084
            const string sourceB = @"
2085 2086 2087 2088 2089 2090 2091 2092
class B
{
    static void Main()
    {
        System.Console.Write(A.I);
    }
}";

2093 2094
            var ca = CreateCompilationWithMscorlib(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2");
            CompileAndVerify(ca);
2095

2096
            var cb = CreateCompilationWithMscorlib(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) });
T
Tomas Matousek 已提交
2097
            CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify();
2098
        }
2099

J
Jared Parsons 已提交
2100
        [Fact, WorkItem(1072339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072339")]
2101 2102 2103
        public void Bug1072339()
        {
            const string sourceA = @"
2104 2105 2106 2107 2108 2109
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""x"")]
internal class A
{
    internal static int I = 42;
}";

2110
            const string sourceB = @"
2111 2112 2113 2114 2115 2116 2117 2118
class B
{
    static void Main()
    {
        System.Console.Write(A.I);
    }
}";

2119 2120
            var ca = CreateCompilationWithMscorlib(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2");
            CompileAndVerify(ca);
2121

2122
            var cb = CreateCompilationWithMscorlib(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) });
T
Tomas Matousek 已提交
2123
            CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify();
2124
        }
P
Pilchie 已提交
2125

J
Jared Parsons 已提交
2126
        [Fact, WorkItem(1095618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095618")]
2127 2128 2129
        public void Bug1095618()
        {
            const string source = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")]";
2130

2131 2132 2133 2134 2135
            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));
2136

2137 2138 2139 2140 2141 2142 2143
            var verifier = CompileAndVerify(ca, symbolValidator: module =>
            {
                var assembly = module.ContainingAssembly;
                Assert.NotNull(assembly);
                Assert.False(assembly.GetAttributes().Any(attr => attr.IsTargetAttribute(assembly, AttributeDescription.InternalsVisibleToAttribute)));
            });
        }
2144

2145 2146 2147
        #endregion
    }
}