CvtRes.cs 40.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Text;
using System.Diagnostics;
using BYTE = System.Byte;
using DWORD = System.UInt32;
using WCHAR = System.Char;
using WORD = System.UInt16;
using System.Reflection.PortableExecutable;
15
using Roslyn.Utilities;
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

namespace Microsoft.CodeAnalysis
{
    internal class RESOURCE
    {
        internal RESOURCE_STRING pstringType;
        internal RESOURCE_STRING pstringName;

        internal DWORD DataSize;               // size of data without header
        internal DWORD HeaderSize;     // Length of the header
        // [Ordinal or Name TYPE]
        // [Ordinal or Name NAME]
        internal DWORD DataVersion;    // version of data struct
        internal WORD MemoryFlags;    // state of the resource
        internal WORD LanguageId;     // Unicode support for NLS
        internal DWORD Version;        // Version of the resource data
        internal DWORD Characteristics;        // Characteristics of the data
        internal byte[] data;       //data
    };

    internal class RESOURCE_STRING
    {
        internal WORD Ordinal;
        internal string theString;
    };

    /// <summary>
    /// Parses .RES a file into its constituent resource elements.
    /// Mostly translated from cvtres.cpp.
    /// </summary>
    internal class CvtResFile
    {
        private const WORD RT_DLGINCLUDE = 17;

        static internal List<RESOURCE> ReadResFile(Stream stream)
        {
            var reader = new BinaryReader(stream, Encoding.Unicode);
            var resourceNames = new List<RESOURCE>();

            var startPos = stream.Position;

            var initial32Bits = reader.ReadUInt32();

            //RC.EXE output starts with a resource that contains no data.
            if (initial32Bits != 0)
                throw new ResourceException("Stream does not begin with a null resource and is not in .RES format.");

            stream.Position = startPos;

            // Build up Type and Name directories

            while (stream.Position < stream.Length)
            {
                // Get the sizes from the file

                var cbData = reader.ReadUInt32();
                var cbHdr = reader.ReadUInt32();

                if (cbHdr < 2 * sizeof(DWORD))
                {
                    throw new ResourceException(String.Format("Resource header beginning at offset 0x{0:x} is malformed.", stream.Position - 8));
                    //ErrorPrint(ERR_FILECORRUPT, szFilename);
                }

                // Discard null resource

                if (cbData == 0)
                {
                    stream.Position += cbHdr - 2 * sizeof(DWORD);
                    continue;
                }

                var pAdditional = new RESOURCE()
                {
                    HeaderSize = cbHdr,
                    DataSize = cbData
                };

                // Read the TYPE and NAME

                pAdditional.pstringType = ReadStringOrID(reader);
                pAdditional.pstringName = ReadStringOrID(reader);

                //round up to dword boundary.
                stream.Position = (stream.Position + 3) & ~3;

                // Read the rest of the header
                pAdditional.DataVersion = reader.ReadUInt32();
                pAdditional.MemoryFlags = reader.ReadUInt16();
                pAdditional.LanguageId = reader.ReadUInt16();
                pAdditional.Version = reader.ReadUInt32();
                pAdditional.Characteristics = reader.ReadUInt32();

                pAdditional.data = new byte[pAdditional.DataSize];
                reader.Read(pAdditional.data, 0, pAdditional.data.Length);

                stream.Position = (stream.Position + 3) & ~3;

                if (pAdditional.pstringType.theString == null && (pAdditional.pstringType.Ordinal == (WORD)RT_DLGINCLUDE))
                {
                    // Ignore DLGINCLUDE resources
                    continue;
                }

                resourceNames.Add(pAdditional);
            }

            return resourceNames;
        }

        private static RESOURCE_STRING ReadStringOrID(BinaryReader fhIn)
        {
            // Reads a String structure from fhIn
            // If the first word is 0xFFFF then this is an ID
            // return the ID instead

            RESOURCE_STRING pstring = new RESOURCE_STRING();

            WCHAR firstWord = fhIn.ReadChar();

            if (firstWord == 0xFFFF)
            {
                // An ID

                pstring.Ordinal = fhIn.ReadUInt16();
            }
            else
            {
                // A string
                pstring.Ordinal = 0xFFFF;

                //keep reading until null reached.

                StringBuilder sb = new StringBuilder();

                WCHAR curChar = firstWord;

                do
                {
                    sb.Append(curChar);
                    curChar = fhIn.ReadChar();
                }
                while (curChar != 0);


                pstring.theString = sb.ToString();
            }

            return (pstring);
        }
    }

    internal static class COFFResourceReader
    {
        private static void ConfirmSectionValues(SectionHeader hdr, long fileSize)
        {
            if ((long)hdr.PointerToRawData + hdr.SizeOfRawData > fileSize)
                throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSectionSize);
        }

        static internal Microsoft.Cci.ResourceSection ReadWin32ResourcesFromCOFF(Stream stream)
        {
            var peHeaders = new PEHeaders(stream);
            var rsrc1 = new SectionHeader();
            var rsrc2 = new SectionHeader();

            int foundCount = 0;
            foreach (var sectionHeader in peHeaders.SectionHeaders)
            {
                if (sectionHeader.Name == ".rsrc$01")
                {
                    rsrc1 = sectionHeader;
                    foundCount++;
                }
                else if (sectionHeader.Name == ".rsrc$02")
                {
                    rsrc2 = sectionHeader;
                    foundCount++;
                }
            }

            if (foundCount != 2)
                throw new ResourceException(CodeAnalysisResources.CoffResourceMissingSection);

            ConfirmSectionValues(rsrc1, stream.Length);
            ConfirmSectionValues(rsrc2, stream.Length);

            //This will be the final resource section bytes without a header. It contains the concatenation
            //of .rsrc$02 on to the end of .rsrc$01.
            var imageResourceSectionBytes = new byte[checked(rsrc1.SizeOfRawData + rsrc2.SizeOfRawData)];

            stream.Seek(rsrc1.PointerToRawData, SeekOrigin.Begin);
208
            stream.TryReadAll(imageResourceSectionBytes, 0, rsrc1.SizeOfRawData); // ConfirmSectionValues ensured that data are available
209
            stream.Seek(rsrc2.PointerToRawData, SeekOrigin.Begin);
210
            stream.TryReadAll(imageResourceSectionBytes, rsrc1.SizeOfRawData, rsrc2.SizeOfRawData); // ConfirmSectionValues ensured that data are available
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866

            const int SizeOfRelocationEntry = 10;

            try
            {
                var relocLastAddress = checked(rsrc1.PointerToRelocations + (rsrc1.NumberOfRelocations * SizeOfRelocationEntry));

                if (relocLastAddress > stream.Length)
                    throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation);
            }
            catch (OverflowException)
            {
                throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation);
            }

            //.rsrc$01 contains the directory tree. .rsrc$02 contains the raw resource data.
            //.rsrc$01 has references to spots in .rsrc$02. Those spots are expressed as relocations.
            //These will need to be fixed up when the RVA of the .rsrc section in the final image is known.
            var relocationOffsets = new uint[rsrc1.NumberOfRelocations];    //offsets into .rsrc$01

            var relocationSymbolIndices = new uint[rsrc1.NumberOfRelocations];

            var reader = new BinaryReader(stream, Encoding.Unicode);
            stream.Position = rsrc1.PointerToRelocations;

            for (int i = 0; i < rsrc1.NumberOfRelocations; i++)
            {
                relocationOffsets[i] = reader.ReadUInt32();
                //What is being read and stored is the reloc's "Value"
                //This is the symbol's index.
                relocationSymbolIndices[i] = reader.ReadUInt32();
                reader.ReadUInt16(); //we do nothing with the "Type"
            }

            //now that symbol indices are gathered, begin indexing the symbols
            stream.Position = peHeaders.CoffHeader.PointerToSymbolTable;
            const uint ImageSizeOfSymbol = 18;

            try
            {
                var lastSymAddress = checked(peHeaders.CoffHeader.PointerToSymbolTable + peHeaders.CoffHeader.NumberOfSymbols * ImageSizeOfSymbol);

                if (lastSymAddress > stream.Length)
                    throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol);
            }
            catch (OverflowException)
            {
                throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol);
            }

            var outputStream = new MemoryStream(imageResourceSectionBytes);
            var writer = new BinaryWriter(outputStream);  //encoding shouldn't matter. There are no strings being written.

            for (int i = 0; i < relocationSymbolIndices.Length; i++)
            {
                if (relocationSymbolIndices[i] > peHeaders.CoffHeader.NumberOfSymbols)
                    throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation);

                var offsetOfSymbol = peHeaders.CoffHeader.PointerToSymbolTable + relocationSymbolIndices[i] * ImageSizeOfSymbol;

                stream.Position = offsetOfSymbol;
                stream.Position += 8; //skip over symbol name
                var symValue = reader.ReadUInt32();
                var symSection = reader.ReadInt16();
                var symType = reader.ReadUInt16();
                //ignore the rest of the fields.

                const ushort IMAGE_SYM_TYPE_NULL = 0x0000;

                if (symType != IMAGE_SYM_TYPE_NULL ||
                    symSection != 3)  //3rd section is .rsrc$02
                    throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol);

                //perform relocation. We are concatenating the contents of .rsrc$02 (the raw resource data)
                //on to the end of .rsrc$01 (the directory tree) to yield the final resource section for the image.
                //The directory tree has references into the raw resource data. These references are expressed
                //in the final image as file positions, not positions relative to the beginning of the section.
                //First make the resources be relative to the beginning of the section by adding the size
                //of .rsrc$01 to them. They will ultimately need the RVA of the final image resource section added 
                //to them. We don't know that yet. That is why the array of offsets is preserved. 

                outputStream.Position = relocationOffsets[i];
                writer.Write((uint)(symValue + rsrc1.SizeOfRawData));
            }

            return new Cci.ResourceSection(imageResourceSectionBytes, relocationOffsets);
        }
    }

    internal static class Win32ResourceConversions
    {
        private struct ICONDIRENTRY
        {
            internal BYTE bWidth;
            internal BYTE bHeight;
            internal BYTE bColorCount;
            internal BYTE bReserved;
            internal WORD wPlanes;
            internal WORD wBitCount;
            internal DWORD dwBytesInRes;
            internal DWORD dwImageOffset;
        };

        internal static void AppendIconToResourceStream(Stream resStream, Stream iconStream)
        {
            var iconReader = new BinaryReader(iconStream);

            //read magic reserved WORD
            var reserved = iconReader.ReadUInt16();
            if (reserved != 0)
                throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat);

            var type = iconReader.ReadUInt16();
            if (type != 1)
                throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat);

            var count = iconReader.ReadUInt16();
            if (count == 0)
                throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat);

            var iconDirEntries = new ICONDIRENTRY[count];
            for (ushort i = 0; i < count; i++)
            {
                // Read the Icon header
                iconDirEntries[i].bWidth = iconReader.ReadByte();
                iconDirEntries[i].bHeight = iconReader.ReadByte();
                iconDirEntries[i].bColorCount = iconReader.ReadByte();
                iconDirEntries[i].bReserved = iconReader.ReadByte();
                iconDirEntries[i].wPlanes = iconReader.ReadUInt16();
                iconDirEntries[i].wBitCount = iconReader.ReadUInt16();
                iconDirEntries[i].dwBytesInRes = iconReader.ReadUInt32();
                iconDirEntries[i].dwImageOffset = iconReader.ReadUInt32();
            }

            // Because Icon files don't seem to record the actual w and BitCount in
            // the ICONDIRENTRY, get the info from the BITMAPINFOHEADER at the beginning
            // of the data here:
            //EDMAURER: PNG compressed icons must be treated differently. Do what has always
            //been done for uncompressed icons. Assume modern, compressed icons set the 
            //ICONDIRENTRY fields correctly.
            //if (*(DWORD*)icoBuffer == sizeof(BITMAPINFOHEADER))
            //{
            //    grp[i].Planes = ((BITMAPINFOHEADER*)icoBuffer)->biPlanes;
            //    grp[i].BitCount = ((BITMAPINFOHEADER*)icoBuffer)->biBitCount;
            //}

            for (ushort i = 0; i < count; i++)
            {
                iconStream.Position = iconDirEntries[i].dwImageOffset;
                if (iconReader.ReadUInt32() == 40)
                {
                    iconStream.Position += 8;
                    iconDirEntries[i].wPlanes = iconReader.ReadUInt16();
                    iconDirEntries[i].wBitCount = iconReader.ReadUInt16();
                }
            }

            //read everything and no exceptions. time to write.
            var resWriter = new BinaryWriter(resStream);

            //write all of the icon images as individual resources, then follow up with
            //a resource that groups them.
            const WORD RT_ICON = 3;

            for (ushort i = 0; i < count; i++)
            {
                /* write resource header.
                struct RESOURCEHEADER
                {
                    DWORD DataSize;
                    DWORD HeaderSize;
                    WORD Magic1;
                    WORD Type;
                    WORD Magic2;
                    WORD Name;
                    DWORD DataVersion;
                    WORD MemoryFlags;
                    WORD LanguageId;
                    DWORD Version;
                    DWORD Characteristics;
                };
                */

                resStream.Position = (resStream.Position + 3) & ~3; //headers begin on 4-byte boundaries.
                resWriter.Write((DWORD)iconDirEntries[i].dwBytesInRes);
                resWriter.Write((DWORD)0x00000020);
                resWriter.Write((WORD)0xFFFF);
                resWriter.Write((WORD)RT_ICON);
                resWriter.Write((WORD)0xFFFF);
                resWriter.Write((WORD)(i + 1));       //EDMAURER this is not general. Implies you can only append one icon to the resources.
                                                      //This icon ID would seem to be global among all of the icons not just this group.
                                                      //Zero appears to not be an acceptable ID. Note that this ID is referred to below.
                resWriter.Write((DWORD)0x00000000);
                resWriter.Write((WORD)0x1010);
                resWriter.Write((WORD)0x0000);
                resWriter.Write((DWORD)0x00000000);
                resWriter.Write((DWORD)0x00000000);

                //write the data.
                iconStream.Position = iconDirEntries[i].dwImageOffset;
                resWriter.Write(iconReader.ReadBytes(checked((int)iconDirEntries[i].dwBytesInRes)));
            }

            /*
            
            struct ICONDIR
            {
                WORD           idReserved;   // Reserved (must be 0)
                WORD           idType;       // Resource Type (1 for icons)
                WORD           idCount;      // How many images?
                ICONDIRENTRY   idEntries[1]; // An entry for each image (idCount of 'em)
            }/
             
            struct ICONRESDIR
            {
                BYTE Width;        // = ICONDIRENTRY.bWidth;
                BYTE Height;       // = ICONDIRENTRY.bHeight;
                BYTE ColorCount;   // = ICONDIRENTRY.bColorCount;
                BYTE reserved;     // = ICONDIRENTRY.bReserved;
                WORD Planes;       // = ICONDIRENTRY.wPlanes;
                WORD BitCount;     // = ICONDIRENTRY.wBitCount;
                DWORD BytesInRes;   // = ICONDIRENTRY.dwBytesInRes;
                WORD IconId;       // = RESOURCEHEADER.Name
            };
            */

            const WORD RT_GROUP_ICON = RT_ICON + 11;

            resStream.Position = (resStream.Position + 3) & ~3; //align 4-byte boundary
            //write the icon group. first a RESOURCEHEADER. the data is the ICONDIR
            resWriter.Write((DWORD)(3 * sizeof(WORD) + count * /*sizeof(ICONRESDIR)*/ 14));
            resWriter.Write((DWORD)0x00000020);
            resWriter.Write((WORD)0xFFFF);
            resWriter.Write((WORD)RT_GROUP_ICON);
            resWriter.Write((WORD)0xFFFF);
            resWriter.Write((WORD)0x7F00);  //IDI_APPLICATION
            resWriter.Write((DWORD)0x00000000);
            resWriter.Write((WORD)0x1030);
            resWriter.Write((WORD)0x0000);
            resWriter.Write((DWORD)0x00000000);
            resWriter.Write((DWORD)0x00000000);

            //the ICONDIR
            resWriter.Write((WORD)0x0000);
            resWriter.Write((WORD)0x0001);
            resWriter.Write((WORD)count);

            for (ushort i = 0; i < count; i++)
            {
                resWriter.Write((BYTE)iconDirEntries[i].bWidth);
                resWriter.Write((BYTE)iconDirEntries[i].bHeight);
                resWriter.Write((BYTE)iconDirEntries[i].bColorCount);
                resWriter.Write((BYTE)iconDirEntries[i].bReserved);
                resWriter.Write((WORD)iconDirEntries[i].wPlanes);
                resWriter.Write((WORD)iconDirEntries[i].wBitCount);
                resWriter.Write((DWORD)iconDirEntries[i].dwBytesInRes);
                resWriter.Write((WORD)(i + 1));   //ID
            }
        }

        /*
         * Dev10 alink had the following fallback behavior.
                private uint[] FileVersion
                {
                    get
                    {
                        if (fileVersionContents != null)
                            return fileVersionContents;
                        else
                        {
                            System.Diagnostics.Debug.Assert(assemblyVersionContents != null);
                            return assemblyVersionContents;
                        }
                    }
                }

                private uint[] ProductVersion
                {
                    get
                    {
                        if (productVersionContents != null)
                            return productVersionContents;
                        else
                            return this.FileVersion;
                    }
                }
                */

        internal static void AppendVersionToResourceStream(Stream resStream, bool isDll,
            string fileVersion, //should be [major.minor.build.rev] but doesn't have to be
            string originalFileName,
            string internalName,
            string productVersion,  //4 ints
            Version assemblyVersion, //individual values must be smaller than 65535
            string fileDescription = " ",   //the old compiler put blank here if nothing was user-supplied
            string legalCopyright = " ",    //the old compiler put blank here if nothing was user-supplied
            string legalTrademarks = null,
            string productName = null,
            string comments = null,
            string companyName = null)
        {
            var resWriter = new BinaryWriter(resStream, Encoding.Unicode);
            resStream.Position = (resStream.Position + 3) & ~3;

            const DWORD RT_VERSION = 16;

            var ver = new VersionResourceSerializer(isDll,
                comments,
                companyName,
                fileDescription,
                fileVersion,
                internalName,
                legalCopyright,
                legalTrademarks,
                originalFileName,
                productName,
                productVersion,
                assemblyVersion);

            var startPos = resStream.Position;
            var dataSize = ver.GetDataSize();
            const int headerSize = 0x20;

            resWriter.Write((DWORD)dataSize);    //data size
            resWriter.Write((DWORD)headerSize);                 //header size
            resWriter.Write((WORD)0xFFFF);                      //identifies type as ordinal.
            resWriter.Write((WORD)RT_VERSION);                 //type
            resWriter.Write((WORD)0xFFFF);                      //identifies name as ordinal.
            resWriter.Write((WORD)0x0001);                      //only ever 1 ver resource (what Dev10 does)
            resWriter.Write((DWORD)0x00000000);                 //data version
            resWriter.Write((WORD)0x0030);                      //memory flags (this is what the Dev10 compiler uses)
            resWriter.Write((WORD)0x0000);                      //languageId
            resWriter.Write((DWORD)0x00000000);                 //version
            resWriter.Write((DWORD)0x00000000);                 //characteristics

            ver.WriteVerResource(resWriter);

            System.Diagnostics.Debug.Assert(resStream.Position - startPos == dataSize + headerSize);
        }

        internal static void AppendManifestToResourceStream(Stream resStream, Stream manifestStream, bool isDll)
        {
            resStream.Position = (resStream.Position + 3) & ~3;
            const WORD RT_MANIFEST = 24;

            var resWriter = new BinaryWriter(resStream);
            resWriter.Write((DWORD)(manifestStream.Length));    //data size
            resWriter.Write((DWORD)0x00000020);                 //header size
            resWriter.Write((WORD)0xFFFF);                      //identifies type as ordinal.
            resWriter.Write((WORD)RT_MANIFEST);                 //type
            resWriter.Write((WORD)0xFFFF);                      //identifies name as ordinal.
            resWriter.Write((WORD)((isDll) ? 0x0002 : 0x0001));  //EDMAURER executables are named "1", DLLs "2"
            resWriter.Write((DWORD)0x00000000);                 //data version
            resWriter.Write((WORD)0x1030);                      //memory flags
            resWriter.Write((WORD)0x0000);                      //languageId
            resWriter.Write((DWORD)0x00000000);                 //version
            resWriter.Write((DWORD)0x00000000);                 //characteristics

            manifestStream.CopyTo(resStream);
        }

        private class VersionResourceSerializer
        {
            private readonly string _commentsContents;
            private readonly string _companyNameContents;
            private readonly string _fileDescriptionContents;
            private readonly string _fileVersionContents;
            private readonly string _internalNameContents;
            private readonly string _legalCopyrightContents;
            private readonly string _legalTrademarksContents;
            private readonly string _originalFileNameContents;
            private readonly string _productNameContents;
            private readonly string _productVersionContents;
            private readonly Version _assemblyVersionContents;

            private const string vsVersionInfoKey = "VS_VERSION_INFO";
            private const string varFileInfoKey = "VarFileInfo";
            private const string translationKey = "Translation";
            private const string stringFileInfoKey = "StringFileInfo";
            private readonly string _langIdAndCodePageKey; //should be 8 characters
            private const DWORD CP_WINUNICODE = 1200;

            private const ushort sizeVS_FIXEDFILEINFO = sizeof(DWORD) * 13;
            private readonly bool _isDll;

            internal VersionResourceSerializer(bool isDll, string comments, string companyName, string fileDescription, string fileVersion,
                string internalName, string legalCopyright, string legalTrademark, string originalFileName, string productName, string productVersion,
                Version assemblyVersion)
            {
                _isDll = isDll;
                _commentsContents = comments;
                _companyNameContents = companyName;
                _fileDescriptionContents = fileDescription;
                _fileVersionContents = fileVersion;
                _internalNameContents = internalName;
                _legalCopyrightContents = legalCopyright;
                _legalTrademarksContents = legalTrademark;
                _originalFileNameContents = originalFileName;
                _productNameContents = productName;
                _productVersionContents = productVersion;
                _assemblyVersionContents = assemblyVersion;
                _langIdAndCodePageKey = System.String.Format("{0:x4}{1:x4}", 0 /*langId*/, CP_WINUNICODE /*codepage*/);
            }

            private const uint VFT_APP = 0x00000001;
            private const uint VFT_DLL = 0x00000002;

            private IEnumerable<KeyValuePair<string, string>> GetVerStrings()
            {
                if (_commentsContents != null) yield return new KeyValuePair<string, string>("Comments", _commentsContents);
                if (_companyNameContents != null) yield return new KeyValuePair<string, string>("CompanyName", _companyNameContents);
                if (_fileDescriptionContents != null) yield return new KeyValuePair<string, string>("FileDescription", _fileDescriptionContents);

                yield return new KeyValuePair<string, string>("FileVersion", _fileVersionContents);

                if (_internalNameContents != null) yield return new KeyValuePair<string, string>("InternalName", _internalNameContents);
                if (_legalCopyrightContents != null) yield return new KeyValuePair<string, string>("LegalCopyright", _legalCopyrightContents);
                if (_legalTrademarksContents != null) yield return new KeyValuePair<string, string>("LegalTrademarks", _legalTrademarksContents);
                if (_originalFileNameContents != null) yield return new KeyValuePair<string, string>("OriginalFilename", _originalFileNameContents);
                if (_productNameContents != null) yield return new KeyValuePair<string, string>("ProductName", _productNameContents);

                yield return new KeyValuePair<string, string>("ProductVersion", _productVersionContents);

                if (_assemblyVersionContents != null) yield return new KeyValuePair<string, string>("Assembly Version", _assemblyVersionContents.ToString());
            }

            private uint FileType { get { return (_isDll) ? VFT_DLL : VFT_APP; } }

            private void WriteVSFixedFileInfo(BinaryWriter writer)
            {
                //There's nothing guaranteeing that these are n.n.n.n format.
                //The documentation says that if they're not that format the behavior is undefined.
                Version fileVersion;
                if (!VersionHelper.TryParse(_fileVersionContents, version: out fileVersion))
                {
                    fileVersion = new Version(0, 0, 0, 0);
                }

                Version productVersion;
                if (!VersionHelper.TryParse(_productVersionContents, version: out productVersion))
                {
                    productVersion = new Version(0, 0, 0, 0);
                }

                writer.Write((DWORD)0xFEEF04BD);
                writer.Write((DWORD)0x00010000);
                writer.Write((DWORD)((uint)fileVersion.Major << 16) | (uint)fileVersion.Minor);
                writer.Write((DWORD)((uint)fileVersion.Build << 16) | (uint)fileVersion.Revision);
                writer.Write((DWORD)((uint)productVersion.Major << 16) | (uint)productVersion.Minor);
                writer.Write((DWORD)((uint)productVersion.Build << 16) | (uint)productVersion.Revision);
                writer.Write((DWORD)0x0000003F);   //VS_FFI_FILEFLAGSMASK  (EDMAURER) really? all these bits are valid?
                writer.Write((DWORD)0);    //file flags
                writer.Write((DWORD)0x00000004);   //VOS__WINDOWS32
                writer.Write((DWORD)this.FileType);
                writer.Write((DWORD)0);    //file subtype
                writer.Write((DWORD)0);    //date most sig
                writer.Write((DWORD)0);    //date least sig
            }

            /// <summary>
            /// Assume that 3 WORDs preceded this string and that they began 32-bit aligned.
            /// Given the string length compute the number of bytes that should be written to end
            /// the buffer on a 32-bit boundary</summary>
            /// <param name="cb"></param>
            /// <returns></returns>
            private static int PadKeyLen(int cb)
            {
                //add previously written 3 WORDS, round up, then subtract the 3 WORDS.
                return PadToDword(cb + 3 * sizeof(WORD)) - 3 * sizeof(WORD);
            }
            /// <summary>
            /// assuming the length of bytes submitted began on a 32-bit boundary,
            /// round up this length as necessary so that it ends at a 32-bit boundary.
            /// </summary>
            /// <param name="cb"></param>
            /// <returns></returns>
            private static int PadToDword(int cb)
            {
                return (cb + 3) & ~3;
            }

            private const int HDRSIZE = 3 * sizeof(ushort);

            private static ushort SizeofVerString(string lpszKey, string lpszValue)
            {
                int cbKey, cbValue;

                cbKey = (lpszKey.Length + 1) * 2;  // Make room for the NULL
                cbValue = (lpszValue.Length + 1) * 2;

                return checked((ushort)(PadKeyLen(cbKey) +    // key, 0 padded to DWORD boundary
                                cbValue +               // value
                                HDRSIZE));             // block header.
            }

            private static void WriteVersionString(KeyValuePair<string, string> keyValuePair, BinaryWriter writer)
            {
                System.Diagnostics.Debug.Assert(keyValuePair.Value != null);

                ushort cbBlock = SizeofVerString(keyValuePair.Key, keyValuePair.Value);
                int cbKey = (keyValuePair.Key.Length + 1) * 2;     // includes terminating NUL
                int cbVal = (keyValuePair.Value.Length + 1) * 2;     // includes terminating NUL

                var startPos = writer.BaseStream.Position;
                Debug.Assert((startPos & 3) == 0);

                writer.Write((WORD)cbBlock);
                writer.Write((WORD)(keyValuePair.Value.Length + 1)); //add 1 for nul
                writer.Write((WORD)1);
                writer.Write(keyValuePair.Key.ToCharArray());
                writer.Write((WORD)'\0');
                writer.Write(new byte[PadKeyLen(cbKey) - cbKey]);
                Debug.Assert((writer.BaseStream.Position & 3) == 0);
                writer.Write(keyValuePair.Value.ToCharArray());
                writer.Write((WORD)'\0');
                //writer.Write(new byte[PadToDword(cbVal) - cbVal]);

                System.Diagnostics.Debug.Assert(cbBlock == writer.BaseStream.Position - startPos);
            }

            /// <summary>
            /// compute number of chars needed to end up on a 32-bit boundary assuming that three
            /// WORDS preceded this string.
            /// </summary>
            /// <param name="sz"></param>
            /// <returns></returns>
            private static int KEYSIZE(string sz)
            {
                return PadKeyLen((sz.Length + 1) * sizeof(WCHAR)) / sizeof(WCHAR);
            }
            private static int KEYBYTES(string sz)
            {
                return KEYSIZE(sz) * sizeof(WCHAR);
            }

            private int GetStringsSize()
            {
                int sum = 0;

                foreach (var verString in GetVerStrings())
                {
                    sum = (sum + 3) & ~3;   //ensure that each String data structure starts on a 32bit boundary.
                    sum += SizeofVerString(verString.Key, verString.Value);
                }

                return sum;
            }

            internal int GetDataSize()
            {
                int sizeEXEVERRESOURCE = sizeof(WORD) * 3 * 5 + 2 * sizeof(WORD) + //five headers + two words for CP and lang
                    KEYBYTES(vsVersionInfoKey) +
                    KEYBYTES(varFileInfoKey) +
                    KEYBYTES(translationKey) +
                    KEYBYTES(stringFileInfoKey) +
                    KEYBYTES(_langIdAndCodePageKey) +
                    sizeVS_FIXEDFILEINFO;

                return GetStringsSize() + sizeEXEVERRESOURCE;
            }

            internal void WriteVerResource(BinaryWriter writer)
            {
                /*
                    must be assumed to start on a 32-bit boundary.
                 * 
                 * the sub-elements of the VS_VERSIONINFO consist of a header (3 WORDS) a string
                 * and then beginning on the next 32-bit boundary, the elements children
                 
                    struct VS_VERSIONINFO
                    {
                        WORD cbRootBlock;                                     // size of whole resource
                        WORD cbRootValue;                                     // size of VS_FIXEDFILEINFO structure
                        WORD fRootText;                                       // root is text?
                        WCHAR szRootKey[KEYSIZE("VS_VERSION_INFO")];          // Holds "VS_VERSION_INFO"
                        VS_FIXEDFILEINFO vsFixed;                             // fixed information.
                          WORD cbVarBlock;                                      //   size of VarFileInfo block
                          WORD cbVarValue;                                      //   always 0
                          WORD fVarText;                                        //   VarFileInfo is text?
                          WCHAR szVarKey[KEYSIZE("VarFileInfo")];               //   Holds "VarFileInfo"
                            WORD cbTransBlock;                                    //     size of Translation block
                            WORD cbTransValue;                                    //     size of Translation value
                            WORD fTransText;                                      //     Translation is text?
                            WCHAR szTransKey[KEYSIZE("Translation")];             //     Holds "Translation"
                              WORD langid;                                          //     language id
                              WORD codepage;                                        //     codepage id
                          WORD cbStringBlock;                                   //   size of StringFileInfo block
                          WORD cbStringValue;                                   //   always 0
                          WORD fStringText;                                     //   StringFileInfo is text?
                          WCHAR szStringKey[KEYSIZE("StringFileInfo")];         //   Holds "StringFileInfo"
                            WORD cbLangCpBlock;                                   //     size of language/codepage block
                            WORD cbLangCpValue;                                   //     always 0
                            WORD fLangCpText;                                     //     LangCp is text?
                            WCHAR szLangCpKey[KEYSIZE("12345678")];               //     Holds hex version of language/codepage
                        // followed by strings
                    };
                */

                var debugPos = writer.BaseStream.Position;
                var dataSize = GetDataSize();

                writer.Write((WORD)dataSize);
                writer.Write((WORD)sizeVS_FIXEDFILEINFO);
                writer.Write((WORD)0);
                writer.Write(vsVersionInfoKey.ToCharArray());
                writer.Write(new byte[KEYBYTES(vsVersionInfoKey) - vsVersionInfoKey.Length * 2]);
                System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0);
                WriteVSFixedFileInfo(writer);
                writer.Write((WORD)(sizeof(WORD) * 2 + 2 * HDRSIZE + KEYBYTES(varFileInfoKey) + KEYBYTES(translationKey)));
                writer.Write((WORD)0);
                writer.Write((WORD)1);
                writer.Write(varFileInfoKey.ToCharArray());
                writer.Write(new byte[KEYBYTES(varFileInfoKey) - varFileInfoKey.Length * 2]);   //padding
                System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0);
                writer.Write((WORD)(sizeof(WORD) * 2 + HDRSIZE + KEYBYTES(translationKey)));
                writer.Write((WORD)(sizeof(WORD) * 2));
                writer.Write((WORD)0);
                writer.Write(translationKey.ToCharArray());
                writer.Write(new byte[KEYBYTES(translationKey) - translationKey.Length * 2]);   //padding
                System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0);
                writer.Write((WORD)0);      //langId; MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)) = 0
                writer.Write((WORD)CP_WINUNICODE);   //codepage; 1200 = CP_WINUNICODE
                System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0);
                writer.Write((WORD)(2 * HDRSIZE + KEYBYTES(stringFileInfoKey) + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize()));
                writer.Write((WORD)0);
                writer.Write((WORD)1);
                writer.Write(stringFileInfoKey.ToCharArray());      //actually preceded by 5 WORDS so not consistent with the
                                                                    //assumptions of KEYBYTES, but equivalent.
                writer.Write(new byte[KEYBYTES(stringFileInfoKey) - stringFileInfoKey.Length * 2]); //padding. 
                System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0);
                writer.Write((WORD)(HDRSIZE + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize()));
                writer.Write((WORD)0);
                writer.Write((WORD)1);
                writer.Write(_langIdAndCodePageKey.ToCharArray());
                writer.Write(new byte[KEYBYTES(_langIdAndCodePageKey) - _langIdAndCodePageKey.Length * 2]); //padding
                System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0);

                System.Diagnostics.Debug.Assert(writer.BaseStream.Position - debugPos == dataSize - GetStringsSize());
                debugPos = writer.BaseStream.Position;

                foreach (var entry in GetVerStrings())
                {
                    var writerPos = writer.BaseStream.Position;

                    //write any padding necessary to align the String struct on a 32 bit boundary.
                    writer.Write(new byte[((writerPos + 3) & ~3) - writerPos]);

                    System.Diagnostics.Debug.Assert(entry.Value != null);
                    WriteVersionString(entry, writer);
                }

                System.Diagnostics.Debug.Assert(writer.BaseStream.Position - debugPos == GetStringsSize());
            }
        }
    }
}