]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/AutoGen/AutoGen.py
BaseTools: Clean some coding style issues
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / AutoGen.py
index 2b4ba52e0965b1269a1db41f8f97304fa0547bcf..4c627dfb555a1c5d2287b8d2f0063441a5950e03 100644 (file)
@@ -1,7 +1,7 @@
 ## @file\r
 # Generate AutoGen.h, AutoGen.c and *.depex files\r
 #\r
-# Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR>\r
+# Copyright (c) 2007 - 2015, Intel Corporation. All rights reserved.<BR>\r
 # This program and the accompanying materials\r
 # are licensed and made available under the terms and conditions of the BSD License\r
 # which accompanies this distribution.  The full text of the license may be found at\r
@@ -17,6 +17,7 @@ import Common.LongFilePathOs as os
 import re\r
 import os.path as path\r
 import copy\r
+import uuid\r
 \r
 import GenC\r
 import GenMake\r
@@ -39,16 +40,28 @@ from GenPatchPcdTable.GenPatchPcdTable import parsePcdInfoFromMapFile
 import Common.VpdInfoFile as VpdInfoFile\r
 from GenPcdDb import CreatePcdDatabaseCode\r
 from Workspace.MetaFileCommentParser import UsageList\r
+from Common.MultipleWorkspace import MultipleWorkspace as mws\r
+import InfSectionParser\r
 \r
 ## Regular expression for splitting Dependency Expression string into tokens\r
 gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)")\r
 \r
+#\r
+# Match name = variable\r
+#\r
+gEfiVarStoreNamePattern = re.compile("\s*name\s*=\s*(\w+)")\r
+#\r
+# The format of guid in efivarstore statement likes following and must be correct:\r
+# guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}\r
+#\r
+gEfiVarStoreGuidPattern = re.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")\r
+\r
 ## Mapping Makefile type\r
 gMakeTypeMap = {"MSFT":"nmake", "GCC":"gmake"}\r
 \r
 \r
 ## Build rule configuration file\r
-gBuildRuleFile = 'Conf/build_rule.txt'\r
+gDefaultBuildRuleFile = 'Conf/build_rule.txt'\r
 \r
 ## Build rule default version\r
 AutoGenReqBuildRuleVerNum = "0.1"\r
@@ -60,22 +73,40 @@ gAutoGenStringFileName = "%(module_name)sStrDefs.h"
 gAutoGenStringFormFileName = "%(module_name)sStrDefs.hpk"\r
 gAutoGenDepexFileName = "%(module_name)s.depex"\r
 \r
+gInfSpecVersion = "0x00010017"\r
+\r
 #\r
 # Template string to generic AsBuilt INF\r
 #\r
 gAsBuiltInfHeaderString = TemplateString("""${header_comments}\r
 \r
+# DO NOT EDIT\r
+# FILE auto-generated\r
+\r
 [Defines]\r
-  INF_VERSION                = 0x00010016\r
+  INF_VERSION                = ${module_inf_version}\r
   BASE_NAME                  = ${module_name}\r
   FILE_GUID                  = ${module_guid}\r
-  MODULE_TYPE                = ${module_module_type}\r
-  VERSION_STRING             = ${module_version_string}${BEGIN}\r
+  MODULE_TYPE                = ${module_module_type}${BEGIN}\r
+  VERSION_STRING             = ${module_version_string}${END}${BEGIN}\r
   PCD_IS_DRIVER              = ${pcd_is_driver_string}${END}${BEGIN}\r
   UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}\r
-  PI_SPECIFICATION_VERSION   = ${module_pi_specification_version}${END}\r
-\r
-[Packages]${BEGIN}\r
+  PI_SPECIFICATION_VERSION   = ${module_pi_specification_version}${END}${BEGIN}\r
+  ENTRY_POINT                = ${module_entry_point}${END}${BEGIN}\r
+  UNLOAD_IMAGE               = ${module_unload_image}${END}${BEGIN}\r
+  CONSTRUCTOR                = ${module_constructor}${END}${BEGIN}\r
+  DESTRUCTOR                 = ${module_destructor}${END}${BEGIN}\r
+  SHADOW                     = ${module_shadow}${END}${BEGIN}\r
+  PCI_VENDOR_ID              = ${module_pci_vendor_id}${END}${BEGIN}\r
+  PCI_DEVICE_ID              = ${module_pci_device_id}${END}${BEGIN}\r
+  PCI_CLASS_CODE             = ${module_pci_class_code}${END}${BEGIN}\r
+  PCI_REVISION               = ${module_pci_revision}${END}${BEGIN}\r
+  BUILD_NUMBER               = ${module_build_number}${END}${BEGIN}\r
+  SPEC                       = ${module_spec}${END}${BEGIN}\r
+  UEFI_HII_RESOURCE_SECTION  = ${module_uefi_hii_resource_section}${END}${BEGIN}\r
+  MODULE_UNI_FILE            = ${module_uni_file}${END}\r
+\r
+[Packages.${module_arch}]${BEGIN}\r
   ${package_item}${END}\r
 \r
 [Binaries.${module_arch}]${BEGIN}\r
@@ -84,19 +115,32 @@ gAsBuiltInfHeaderString = TemplateString("""${header_comments}
 [PatchPcd.${module_arch}]${BEGIN}\r
   ${patchablepcd_item}\r
 ${END}\r
+\r
 [Protocols.${module_arch}]${BEGIN}\r
   ${protocol_item}\r
 ${END}\r
+\r
 [Ppis.${module_arch}]${BEGIN}\r
   ${ppi_item}\r
 ${END}\r
+\r
 [Guids.${module_arch}]${BEGIN}\r
   ${guid_item}\r
 ${END}\r
+\r
 [PcdEx.${module_arch}]${BEGIN}\r
   ${pcd_item}\r
 ${END}\r
 \r
+[LibraryClasses.${module_arch}]\r
+## @LIB_INSTANCES${BEGIN}\r
+#  ${libraryclasses_item}${END}\r
+\r
+${depexsection_item}\r
+\r
+${tail_comments}\r
+\r
+[BuildOptions.${module_arch}]\r
 ## @AsBuilt${BEGIN}\r
 ##   ${flags_item}${END}\r
 """)\r
@@ -188,7 +232,7 @@ class WorkspaceAutoGen(AutoGen):
     #   @param  SkuId                   SKU id from command line\r
     #\r
     def _Init(self, WorkspaceDir, ActivePlatform, Target, Toolchain, ArchList, MetaFileDb,\r
-              BuildConfig, ToolDefinition, FlashDefinitionFile='', Fds=None, Fvs=None, Caps=None, SkuId='', UniFlag=None, \r
+              BuildConfig, ToolDefinition, FlashDefinitionFile='', Fds=None, Fvs=None, Caps=None, SkuId='', UniFlag=None,\r
               Progress=None, BuildModule=None):\r
         if Fds is None:\r
             Fds = []\r
@@ -236,37 +280,38 @@ class WorkspaceAutoGen(AutoGen):
 \r
         # Validate build target\r
         if self.BuildTarget not in self.Platform.BuildTargets:\r
-            EdkLogger.error("build", PARAMETER_INVALID, \r
+            EdkLogger.error("build", PARAMETER_INVALID,\r
                             ExtraData="Build target [%s] is not supported by the platform. [Valid target: %s]"\r
                                       % (self.BuildTarget, " ".join(self.Platform.BuildTargets)))\r
 \r
+        \r
         # parse FDF file to get PCDs in it, if any\r
         if not self.FdfFile:\r
             self.FdfFile = self.Platform.FlashDefinition\r
-        \r
+\r
         EdkLogger.info("")\r
         if self.ArchList:\r
             EdkLogger.info('%-16s = %s' % ("Architecture(s)", ' '.join(self.ArchList)))\r
         EdkLogger.info('%-16s = %s' % ("Build target", self.BuildTarget))\r
-        EdkLogger.info('%-16s = %s' % ("Toolchain",self.ToolChain))        \r
-        \r
+        EdkLogger.info('%-16s = %s' % ("Toolchain", self.ToolChain))\r
+\r
         EdkLogger.info('\n%-24s = %s' % ("Active Platform", self.Platform))\r
         if BuildModule:\r
             EdkLogger.info('%-24s = %s' % ("Active Module", BuildModule))\r
-        \r
+\r
         if self.FdfFile:\r
             EdkLogger.info('%-24s = %s' % ("Flash Image Definition", self.FdfFile))\r
 \r
         EdkLogger.verbose("\nFLASH_DEFINITION = %s" % self.FdfFile)\r
-        \r
+\r
         if Progress:\r
             Progress.Start("\nProcessing meta-data")\r
-        \r
+\r
         if self.FdfFile:\r
             #\r
             # Mark now build in AutoGen Phase\r
             #\r
-            GlobalData.gAutoGenPhase = True    \r
+            GlobalData.gAutoGenPhase = True\r
             Fdf = FdfParser(self.FdfFile.Path)\r
             Fdf.ParseFile()\r
             GlobalData.gFdfParser = Fdf\r
@@ -291,7 +336,7 @@ class WorkspaceAutoGen(AutoGen):
             if self.CapTargetList:\r
                 EdkLogger.info("No flash definition file found. Capsule [%s] will be ignored." % " ".join(self.CapTargetList))\r
                 self.CapTargetList = []\r
-        \r
+\r
         # apply SKU and inject PCDs from Flash Definition file\r
         for Arch in self.ArchList:\r
             Platform = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]\r
@@ -299,6 +344,7 @@ class WorkspaceAutoGen(AutoGen):
             DecPcds = {}\r
             DecPcdsKey = set()\r
             PGen = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)\r
+            #Collect package set information from INF of FDF\r
             PkgSet = set()\r
             for Inf in ModuleList:\r
                 ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch)\r
@@ -345,20 +391,20 @@ class WorkspaceAutoGen(AutoGen):
             Pa.CollectPlatformDynamicPcds()\r
             Pa.CollectFixedAtBuildPcds()\r
             self.AutoGenObjectList.append(Pa)\r
-        \r
+\r
         #\r
         # Check PCDs token value conflict in each DEC file.\r
         #\r
         self._CheckAllPcdsTokenValueConflict()\r
-        \r
+\r
         #\r
         # Check PCD type and definition between DSC and DEC\r
         #\r
         self._CheckPcdDefineAndType()\r
-        \r
-        if self.FdfFile:\r
-            self._CheckDuplicateInFV(Fdf)\r
-        \r
+\r
+        if self.FdfFile:\r
+            self._CheckDuplicateInFV(Fdf)\r
+\r
         self._BuildDir = None\r
         self._FvDir = None\r
         self._MakeFileDir = None\r
@@ -379,7 +425,7 @@ class WorkspaceAutoGen(AutoGen):
                     #\r
                     # Get INF file GUID\r
                     #\r
-                    InfFoundFlag = False                   \r
+                    InfFoundFlag = False\r
                     for Pa in self.AutoGenObjectList:\r
                         if InfFoundFlag:\r
                             break\r
@@ -390,9 +436,9 @@ class WorkspaceAutoGen(AutoGen):
                                     _GuidDict[Module.Guid.upper()] = FfsFile\r
                                     break\r
                                 else:\r
-                                    EdkLogger.error("build", \r
+                                    EdkLogger.error("build",\r
                                                     FORMAT_INVALID,\r
-                                                    "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s"%(FfsFile.CurrentLineNum,\r
+                                                    "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,\r
                                                                                                                                    FfsFile.CurrentLineContent,\r
                                                                                                                                    _GuidDict[Module.Guid.upper()].CurrentLineNum,\r
                                                                                                                                    _GuidDict[Module.Guid.upper()].CurrentLineContent,\r
@@ -406,7 +452,7 @@ class WorkspaceAutoGen(AutoGen):
                             InfPath = NormPath(FfsFile.InfFileName)\r
                             if not os.path.exists(InfPath):\r
                                 EdkLogger.error('build', GENFDS_ERROR, "Non-existant Module %s !" % (FfsFile.InfFileName))\r
-                                \r
+\r
                             PathClassObj = PathClass(FfsFile.InfFileName, self.WorkspaceDir)\r
                             #\r
                             # Here we just need to get FILE_GUID from INF file, use 'COMMON' as ARCH attribute. and use \r
@@ -416,19 +462,19 @@ class WorkspaceAutoGen(AutoGen):
                             if not InfObj.Guid.upper() in _GuidDict.keys():\r
                                 _GuidDict[InfObj.Guid.upper()] = FfsFile\r
                             else:\r
-                                EdkLogger.error("build", \r
+                                EdkLogger.error("build",\r
                                                 FORMAT_INVALID,\r
-                                                "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s"%(FfsFile.CurrentLineNum,\r
+                                                "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,\r
                                                                                                                                FfsFile.CurrentLineContent,\r
                                                                                                                                _GuidDict[InfObj.Guid.upper()].CurrentLineNum,\r
                                                                                                                                _GuidDict[InfObj.Guid.upper()].CurrentLineContent,\r
                                                                                                                                InfObj.Guid.upper()),\r
                                                 ExtraData=self.FdfFile)\r
                         InfFoundFlag = False\r
-                                                                   \r
+\r
                 if FfsFile.NameGuid != None:\r
                     _CheckPCDAsGuidPattern = re.compile("^PCD\(.+\..+\)$")\r
-                    \r
+\r
                     #\r
                     # If the NameGuid reference a PCD name. \r
                     # The style must match: PCD(xxxx.yyy)\r
@@ -447,51 +493,51 @@ class WorkspaceAutoGen(AutoGen):
                                         # First convert from CFormatGuid to GUID string\r
                                         #\r
                                         _PcdGuidString = GuidStructureStringToGuidString(PcdItem.DefaultValue)\r
-                                        \r
+\r
                                         if not _PcdGuidString:\r
                                             #\r
                                             # Then try Byte array.\r
                                             #\r
                                             _PcdGuidString = GuidStructureByteArrayToGuidString(PcdItem.DefaultValue)\r
-                                            \r
+\r
                                         if not _PcdGuidString:\r
                                             #\r
                                             # Not Byte array or CFormat GUID, raise error.\r
                                             #\r
                                             EdkLogger.error("build",\r
                                                             FORMAT_INVALID,\r
-                                                            "The format of PCD value is incorrect. PCD: %s , Value: %s\n"%(_PcdName, PcdItem.DefaultValue),\r
+                                                            "The format of PCD value is incorrect. PCD: %s , Value: %s\n" % (_PcdName, PcdItem.DefaultValue),\r
                                                             ExtraData=self.FdfFile)\r
-                                        \r
-                                        if not _PcdGuidString.upper() in _GuidDict.keys():    \r
+\r
+                                        if not _PcdGuidString.upper() in _GuidDict.keys():\r
                                             _GuidDict[_PcdGuidString.upper()] = FfsFile\r
                                             PcdFoundFlag = True\r
                                             break\r
                                         else:\r
-                                            EdkLogger.error("build", \r
+                                            EdkLogger.error("build",\r
                                                             FORMAT_INVALID,\r
-                                                            "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s"%(FfsFile.CurrentLineNum,\r
+                                                            "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,\r
                                                                                                                                            FfsFile.CurrentLineContent,\r
                                                                                                                                            _GuidDict[_PcdGuidString.upper()].CurrentLineNum,\r
                                                                                                                                            _GuidDict[_PcdGuidString.upper()].CurrentLineContent,\r
                                                                                                                                            FfsFile.NameGuid.upper()),\r
-                                                            ExtraData=self.FdfFile)                                                                       \r
-                \r
+                                                            ExtraData=self.FdfFile)\r
+\r
                     if not FfsFile.NameGuid.upper() in _GuidDict.keys():\r
                         _GuidDict[FfsFile.NameGuid.upper()] = FfsFile\r
                     else:\r
                         #\r
                         # Two raw file GUID conflict.\r
                         #\r
-                        EdkLogger.error("build", \r
+                        EdkLogger.error("build",\r
                                         FORMAT_INVALID,\r
-                                        "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s"%(FfsFile.CurrentLineNum,\r
+                                        "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,\r
                                                                                                                        FfsFile.CurrentLineContent,\r
                                                                                                                        _GuidDict[FfsFile.NameGuid.upper()].CurrentLineNum,\r
                                                                                                                        _GuidDict[FfsFile.NameGuid.upper()].CurrentLineContent,\r
                                                                                                                        FfsFile.NameGuid.upper()),\r
                                         ExtraData=self.FdfFile)\r
-                \r
+\r
 \r
     def _CheckPcdDefineAndType(self):\r
         PcdTypeList = [\r
@@ -506,17 +552,17 @@ class WorkspaceAutoGen(AutoGen):
             # Key of DSC's Pcds dictionary is PcdCName, TokenSpaceGuid\r
             for Pcd in Pa.Platform.Pcds:\r
                 PcdType = Pa.Platform.Pcds[Pcd].Type\r
-                \r
+\r
                 # If no PCD type, this PCD comes from FDF \r
                 if not PcdType:\r
                     continue\r
-                \r
+\r
                 # Try to remove Hii and Vpd suffix\r
                 if PcdType.startswith("DynamicEx"):\r
                     PcdType = "DynamicEx"\r
                 elif PcdType.startswith("Dynamic"):\r
                     PcdType = "Dynamic"\r
-    \r
+\r
                 for Package in Pa.PackageList:\r
                     # Key of DEC's Pcds dictionary is PcdCName, TokenSpaceGuid, PcdType\r
                     if (Pcd[0], Pcd[1], PcdType) in Package.Pcds:\r
@@ -594,7 +640,7 @@ class WorkspaceAutoGen(AutoGen):
             # BuildCommand should be all the same. So just get one from platform AutoGen\r
             self._BuildCommand = self.AutoGenObjectList[0].BuildCommand\r
         return self._BuildCommand\r
-    \r
+\r
     ## Check the PCDs token value conflict in each DEC file.\r
     #\r
     # Will cause build break and raise error message while two PCDs conflict.\r
@@ -605,7 +651,7 @@ class WorkspaceAutoGen(AutoGen):
         for Pa in self.AutoGenObjectList:\r
             for Package in Pa.PackageList:\r
                 PcdList = Package.Pcds.values()\r
-                PcdList.sort(lambda x, y: cmp(x.TokenValue, y.TokenValue)) \r
+                PcdList.sort(lambda x, y: cmp(int(x.TokenValue, 0), int(y.TokenValue, 0))) \r
                 Count = 0\r
                 while (Count < len(PcdList) - 1) :\r
                     Item = PcdList[Count]\r
@@ -613,25 +659,25 @@ class WorkspaceAutoGen(AutoGen):
                     #\r
                     # Make sure in the same token space the TokenValue should be unique\r
                     #\r
-                    if (Item.TokenValue == ItemNext.TokenValue):\r
+                    if (int(Item.TokenValue, 0) == int(ItemNext.TokenValue, 0)):\r
                         SameTokenValuePcdList = []\r
                         SameTokenValuePcdList.append(Item)\r
                         SameTokenValuePcdList.append(ItemNext)\r
                         RemainPcdListLength = len(PcdList) - Count - 2\r
                         for ValueSameCount in range(RemainPcdListLength):\r
-                            if PcdList[len(PcdList) - RemainPcdListLength + ValueSameCount].TokenValue == Item.TokenValue:\r
+                            if int(PcdList[len(PcdList) - RemainPcdListLength + ValueSameCount].TokenValue, 0) == int(Item.TokenValue, 0):\r
                                 SameTokenValuePcdList.append(PcdList[len(PcdList) - RemainPcdListLength + ValueSameCount])\r
                             else:\r
                                 break;\r
                         #\r
                         # Sort same token value PCD list with TokenGuid and TokenCName\r
                         #\r
-                        SameTokenValuePcdList.sort(lambda x, y: cmp("%s.%s"%(x.TokenSpaceGuidCName, x.TokenCName), "%s.%s"%(y.TokenSpaceGuidCName, y.TokenCName))) \r
-                        SameTokenValuePcdListCount = 0     \r
+                        SameTokenValuePcdList.sort(lambda x, y: cmp("%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName), "%s.%s" % (y.TokenSpaceGuidCName, y.TokenCName)))\r
+                        SameTokenValuePcdListCount = 0\r
                         while (SameTokenValuePcdListCount < len(SameTokenValuePcdList) - 1):\r
-                            TemListItem     = SameTokenValuePcdList[SameTokenValuePcdListCount]\r
-                            TemListItemNext = SameTokenValuePcdList[SameTokenValuePcdListCount + 1] \r
-                                                                                                      \r
+                            TemListItem = SameTokenValuePcdList[SameTokenValuePcdListCount]\r
+                            TemListItemNext = SameTokenValuePcdList[SameTokenValuePcdListCount + 1]\r
+\r
                             if (TemListItem.TokenSpaceGuidCName == TemListItemNext.TokenSpaceGuidCName) and (TemListItem.TokenCName != TemListItemNext.TokenCName):\r
                                 EdkLogger.error(\r
                                             'build',\r
@@ -643,17 +689,17 @@ class WorkspaceAutoGen(AutoGen):
                             SameTokenValuePcdListCount += 1\r
                         Count += SameTokenValuePcdListCount\r
                     Count += 1\r
-                \r
+\r
                 PcdList = Package.Pcds.values()\r
-                PcdList.sort(lambda x, y: cmp("%s.%s"%(x.TokenSpaceGuidCName, x.TokenCName), "%s.%s"%(y.TokenSpaceGuidCName, y.TokenCName)))\r
+                PcdList.sort(lambda x, y: cmp("%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName), "%s.%s" % (y.TokenSpaceGuidCName, y.TokenCName)))\r
                 Count = 0\r
                 while (Count < len(PcdList) - 1) :\r
                     Item = PcdList[Count]\r
-                    ItemNext = PcdList[Count + 1]                \r
+                    ItemNext = PcdList[Count + 1]\r
                     #\r
                     # Check PCDs with same TokenSpaceGuidCName.TokenCName have same token value as well.\r
                     #\r
-                    if (Item.TokenSpaceGuidCName == ItemNext.TokenSpaceGuidCName) and (Item.TokenCName == ItemNext.TokenCName) and (Item.TokenValue != ItemNext.TokenValue):\r
+                    if (Item.TokenSpaceGuidCName == ItemNext.TokenSpaceGuidCName) and (Item.TokenCName == ItemNext.TokenCName) and (int(Item.TokenValue, 0) != int(ItemNext.TokenValue, 0)):\r
                         EdkLogger.error(\r
                                     'build',\r
                                     FORMAT_INVALID,\r
@@ -662,7 +708,7 @@ class WorkspaceAutoGen(AutoGen):
                                     ExtraData=None\r
                                     )\r
                     Count += 1\r
-                                      \r
+    ## Generate fds command\r
     def _GenFdsCommand(self):\r
         return (GenMake.TopLevelMakefile(self)._TEMPLATE_.Replace(GenMake.TopLevelMakefile(self)._TemplateDict)).strip()\r
 \r
@@ -740,7 +786,7 @@ class PlatformAutoGen(AutoGen):
                 "0x01001"  : 3,      #  ******_TOOLCHAIN_****_***********_ATTRIBUTE\r
                 "0x10001"  : 2,      #  TARGET_*********_****_***********_ATTRIBUTE\r
                 "0x00001"  : 1}      #  ******_*********_****_***********_ATTRIBUTE (Lowest)\r
-    \r
+\r
     ## The real constructor of PlatformAutoGen\r
     #\r
     #  This method is not supposed to be called by users of PlatformAutoGen. It's\r
@@ -817,9 +863,6 @@ class PlatformAutoGen(AutoGen):
         # get library/modules for build\r
         self.LibraryBuildDirectoryList = []\r
         self.ModuleBuildDirectoryList = []\r
-        # get the original module/package/platform objects\r
-        self.LibraryBuildDirectoryList = []\r
-        self.ModuleBuildDirectoryList = []\r
         return True\r
 \r
     def __repr__(self):\r
@@ -859,7 +902,7 @@ class PlatformAutoGen(AutoGen):
                 Ma = ModuleAutoGen(self.Workspace, ModuleFile, self.BuildTarget,\r
                                    self.ToolChain, self.Arch, self.MetaFile)\r
                 Ma.CreateMakeFile(True)\r
-                Ma.CreateAsBuiltInf()\r
+                #Ma.CreateAsBuiltInf()\r
 \r
         # no need to create makefile for the platform more than once\r
         if self.IsMakeFileCreated:\r
@@ -910,21 +953,24 @@ class PlatformAutoGen(AutoGen):
         self._GuidValue = {}\r
         FdfModuleList = []\r
         for InfName in self._AsBuildInfList:\r
-            InfName = os.path.join(self.WorkspaceDir, InfName)\r
+            InfName = mws.join(self.WorkspaceDir, InfName)\r
             FdfModuleList.append(os.path.normpath(InfName))\r
         for F in self.Platform.Modules.keys():\r
             M = ModuleAutoGen(self.Workspace, F, self.BuildTarget, self.ToolChain, self.Arch, self.MetaFile)\r
             #GuidValue.update(M.Guids)\r
             \r
             self.Platform.Modules[F].M = M\r
-            \r
-            for PcdFromModule in M.ModulePcdList+M.LibraryPcdList:\r
+\r
+            for PcdFromModule in M.ModulePcdList + M.LibraryPcdList:\r
                 # make sure that the "VOID*" kind of datum has MaxDatumSize set\r
                 if PcdFromModule.DatumType == "VOID*" and PcdFromModule.MaxDatumSize in [None, '']:\r
                     NoDatumTypePcdList.add("%s.%s [%s]" % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, F))\r
 \r
+                # Check the PCD from Binary INF or Source INF\r
                 if M.IsBinaryModule == True:\r
                     PcdFromModule.IsFromBinaryInf = True\r
+\r
+                # Check the PCD from DSC or not \r
                 if (PcdFromModule.TokenCName, PcdFromModule.TokenSpaceGuidCName) in self.Platform.Pcds.keys():\r
                     PcdFromModule.IsFromDsc = True\r
                 else:\r
@@ -943,11 +989,6 @@ class PlatformAutoGen(AutoGen):
                             PcdFromModule.IsFromBinaryInf == False:\r
                             # Print warning message to let the developer make a determine.\r
                             if PcdFromModule not in PcdNotInDb:\r
-                                EdkLogger.warn("build",\r
-                                               "A PCD listed in the DSC (%s.%s, %s) is used by a module not in the FDF. If the PCD is not used by any module listed in the FDF this PCD will be ignored. " \\r
-                                               % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, self.Platform.MetaFile.Path),\r
-                                               File=self.MetaFile, \\r
-                                               ExtraData=None)\r
                                 PcdNotInDb.append(PcdFromModule)\r
                             continue\r
                         # If one of the Source built modules listed in the DSC is not listed in \r
@@ -1017,6 +1058,11 @@ class PlatformAutoGen(AutoGen):
                     elif PcdFromModule not in self._NonDynaPcdList_ and PcdFromModule.Type in TAB_PCDS_PATCHABLE_IN_MODULE:\r
                         self._NonDynaPcdList_.append(PcdFromModule)\r
                     if PcdFromModule in self._DynaPcdList_ and PcdFromModule.Phase == 'PEI' and PcdFromModule.Type in GenC.gDynamicExPcd:\r
+                        # Overwrite the phase of any the same PCD existing, if Phase is PEI.\r
+                        # It is to solve the case that a dynamic PCD used by a PEM module/PEI \r
+                        # module & DXE module at a same time.\r
+                        # Overwrite the type of the PCDs in source INF by the type of AsBuild\r
+                        # INF file as DynamicEx. \r
                         Index = self._DynaPcdList_.index(PcdFromModule)\r
                         self._DynaPcdList_[Index].Phase = PcdFromModule.Phase\r
                         self._DynaPcdList_[Index].Type = PcdFromModule.Type\r
@@ -1047,19 +1093,6 @@ class PlatformAutoGen(AutoGen):
                                       % NoDatumTypePcdListString)\r
         self._NonDynamicPcdList = self._NonDynaPcdList_\r
         self._DynamicPcdList = self._DynaPcdList_\r
-        # If PCD is listed in a PcdsDynamicHii, PcdsDynamicExHii, PcdsDynamicHii or PcdsDynamicExHii\r
-        # section, and the PCD is not used by any module that is listed in the DSC file, the build \r
-        # provide a warning message.\r
-        for PcdKey in self.Platform.Pcds.keys():\r
-            Pcd = self.Platform.Pcds[PcdKey]\r
-            if Pcd not in self._DynamicPcdList + PcdNotInDb and \\r
-                Pcd.Type in [TAB_PCDS_DYNAMIC, TAB_PCDS_DYNAMIC_DEFAULT, TAB_PCDS_DYNAMIC_HII, TAB_PCDS_DYNAMIC_EX, TAB_PCDS_DYNAMIC_EX_DEFAULT, TAB_PCDS_DYNAMIC_EX_HII]:\r
-                # Print warning message to let the developer make a determine.\r
-                EdkLogger.warn("build",\r
-                               "A %s PCD listed in the DSC (%s.%s, %s) is not used by any module." \\r
-                               % (Pcd.Type, Pcd.TokenSpaceGuidCName, Pcd.TokenCName, self.Platform.MetaFile.Path),\r
-                               File=self.MetaFile, \\r
-                               ExtraData=None)\r
         #\r
         # Sort dynamic PCD list to:\r
         # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should \r
@@ -1078,9 +1111,9 @@ class PlatformAutoGen(AutoGen):
         if (self.Workspace.ArchList[-1] == self.Arch): \r
             for Pcd in self._DynamicPcdList:\r
                 # just pick the a value to determine whether is unicode string type\r
-                Sku      = Pcd.SkuInfoList[Pcd.SkuInfoList.keys()[0]]\r
+                Sku = Pcd.SkuInfoList[Pcd.SkuInfoList.keys()[0]]\r
                 Sku.VpdOffset = Sku.VpdOffset.strip()\r
-                \r
+\r
                 PcdValue = Sku.DefaultValue\r
                 if Pcd.DatumType == 'VOID*' and PcdValue.startswith("L"):\r
                     # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex\r
@@ -1091,10 +1124,10 @@ class PlatformAutoGen(AutoGen):
                 else:\r
                     OtherPcdArray.append(Pcd)\r
                 if Pcd.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD]:\r
-                    VpdPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = Pcd                   \r
-            \r
+                    VpdPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = Pcd\r
+\r
             PlatformPcds = self.Platform.Pcds.keys()\r
-            PlatformPcds.sort()            \r
+            PlatformPcds.sort()\r
             #\r
             # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.\r
             #\r
@@ -1112,8 +1145,8 @@ class PlatformAutoGen(AutoGen):
                             if self.Platform.VpdToolGuid == None or self.Platform.VpdToolGuid == '':\r
                                 EdkLogger.error("Build", FILE_NOT_FOUND, \\r
                                                 "Fail to find third-party BPDG tool to process VPD PCDs. BPDG Guid tool need to be defined in tools_def.txt and VPD_TOOL_GUID need to be provided in DSC file.")\r
-                            \r
-                                   \r
+\r
+\r
             #\r
             # Fix the PCDs define in VPD PCD section that never referenced by module.\r
             # An example is PCD for signature usage.\r
@@ -1128,7 +1161,7 @@ class PlatformAutoGen(AutoGen):
                             if (VpdPcd.TokenSpaceGuidCName == DscPcdEntry.TokenSpaceGuidCName) and \\r
                                (VpdPcd.TokenCName == DscPcdEntry.TokenCName):\r
                                     FoundFlag = True\r
-                        \r
+\r
                         # Not found, it should be signature\r
                         if not FoundFlag :\r
                             # just pick the a value to determine whether is unicode string type\r
@@ -1178,7 +1211,7 @@ class PlatformAutoGen(AutoGen):
                VpdFile.GetCount() != 0:\r
                 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, \r
                                 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self.Platform.MetaFile))\r
-            \r
+\r
             if VpdFile.GetCount() != 0:\r
                 DscTimeStamp = self.Platform.MetaFile.TimeStamp\r
                 FvPath = os.path.join(self.BuildDir, "FV")\r
@@ -1187,14 +1220,14 @@ class PlatformAutoGen(AutoGen):
                         os.makedirs(FvPath)\r
                     except:\r
                         EdkLogger.error("build", FILE_WRITE_FAILURE, "Fail to create FV folder under %s" % self.BuildDir)\r
-                        \r
-        \r
+\r
+\r
                 VpdFilePath = os.path.join(FvPath, "%s.txt" % self.Platform.VpdToolGuid)\r
 \r
-                \r
+\r
                 if not os.path.exists(VpdFilePath) or os.path.getmtime(VpdFilePath) < DscTimeStamp:\r
                     VpdFile.Write(VpdFilePath)\r
-        \r
+\r
                     # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.\r
                     BPDGToolName = None\r
                     for ToolDef in self.ToolDefinition.values():\r
@@ -1208,13 +1241,13 @@ class PlatformAutoGen(AutoGen):
                         VpdInfoFile.CallExtenalBPDGTool(BPDGToolName, VpdFilePath)\r
                     else:\r
                         EdkLogger.error("Build", FILE_NOT_FOUND, "Fail to find third-party BPDG tool to process VPD PCDs. BPDG Guid tool need to be defined in tools_def.txt and VPD_TOOL_GUID need to be provided in DSC file.")\r
-                        \r
+\r
                 # Process VPD map file generated by third party BPDG tool\r
                 if NeedProcessVpdMapFile:\r
                     VpdMapFilePath = os.path.join(self.BuildDir, "FV", "%s.map" % self.Platform.VpdToolGuid)\r
                     if os.path.exists(VpdMapFilePath):\r
                         VpdFile.Read(VpdMapFilePath)\r
-                \r
+\r
                         # Fixup "*" offset\r
                         for Pcd in self._DynamicPcdList:\r
                             # just pick the a value to determine whether is unicode string type\r
@@ -1225,9 +1258,9 @@ class PlatformAutoGen(AutoGen):
                                 i += 1\r
                     else:\r
                         EdkLogger.error("build", FILE_READ_FAILURE, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath)\r
-            \r
+\r
             # Delete the DynamicPcdList At the last time enter into this function \r
-            del self._DynamicPcdList[:]                        \r
+            del self._DynamicPcdList[:]\r
         self._DynamicPcdList.extend(UnicodePcdArray)\r
         self._DynamicPcdList.extend(HiiPcdArray)\r
         self._DynamicPcdList.extend(OtherPcdArray)\r
@@ -1255,7 +1288,7 @@ class PlatformAutoGen(AutoGen):
     def _GetFdfFile(self):\r
         if self._FdfFile == None:\r
             if self.Workspace.FdfFile != "":\r
-                self._FdfFile= path.join(self.WorkspaceDir, self.Workspace.FdfFile)\r
+                self._FdfFile= mws.join(self.WorkspaceDir, self.Workspace.FdfFile)\r
             else:\r
                 self._FdfFile = ''\r
         return self._FdfFile\r
@@ -1421,7 +1454,7 @@ class PlatformAutoGen(AutoGen):
             self._EdkIIBuildOption = self._ExpandBuildOption(self.Platform.BuildOptions, EDKII_NAME)\r
         return self._EdkIIBuildOption\r
 \r
-    ## Parse build_rule.txt in $(WORKSPACE)/Conf/build_rule.txt\r
+    ## Parse build_rule.txt in Conf Directory.\r
     #\r
     #   @retval     BuildRule object\r
     #\r
@@ -1431,17 +1464,17 @@ class PlatformAutoGen(AutoGen):
             if TAB_TAT_DEFINES_BUILD_RULE_CONF in self.Workspace.TargetTxt.TargetTxtDictionary:\r
                 BuildRuleFile = self.Workspace.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_BUILD_RULE_CONF]\r
             if BuildRuleFile in [None, '']:\r
-                BuildRuleFile = gBuildRuleFile\r
+                BuildRuleFile = gDefaultBuildRuleFile\r
             self._BuildRule = BuildRule(BuildRuleFile)\r
             if self._BuildRule._FileVersion == "":\r
                 self._BuildRule._FileVersion = AutoGenReqBuildRuleVerNum\r
             else:\r
                 if self._BuildRule._FileVersion < AutoGenReqBuildRuleVerNum :\r
                     # If Build Rule's version is less than the version number required by the tools, halting the build.\r
-                    EdkLogger.error("build", AUTOGEN_ERROR, \r
+                    EdkLogger.error("build", AUTOGEN_ERROR,\r
                                     ExtraData="The version number [%s] of build_rule.txt is less than the version number required by the AutoGen.(the minimum required version number is [%s])"\\r
                                      % (self._BuildRule._FileVersion, AutoGenReqBuildRuleVerNum))\r
-              \r
+\r
         return self._BuildRule\r
 \r
     ## Summarize the packages used by modules in this platform\r
@@ -1501,28 +1534,28 @@ class PlatformAutoGen(AutoGen):
                         EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
                         self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
                         TokenNumber += 1\r
-                        \r
+\r
             for Pcd in self.DynamicPcdList:\r
                 if Pcd.Phase == "PEI":\r
                     if Pcd.Type in ["DynamicEx", "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:\r
                         EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
                         self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
                         TokenNumber += 1\r
-                        \r
+\r
             for Pcd in self.DynamicPcdList:\r
                 if Pcd.Phase == "DXE":\r
                     if Pcd.Type in ["Dynamic", "DynamicDefault", "DynamicVpd", "DynamicHii"]:\r
                         EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
                         self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
                         TokenNumber += 1\r
-                        \r
+\r
             for Pcd in self.DynamicPcdList:\r
                 if Pcd.Phase == "DXE":\r
                     if Pcd.Type in ["DynamicEx", "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:\r
                         EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
                         self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
                         TokenNumber += 1\r
-                        \r
+\r
             for Pcd in self.NonDynamicPcdList:\r
                 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
                 TokenNumber += 1\r
@@ -1754,7 +1787,7 @@ class PlatformAutoGen(AutoGen):
             elif (ToPcd.Type not in [None, '']) and (FromPcd.Type not in [None, ''])\\r
                 and (ToPcd.Type != FromPcd.Type) and (ToPcd.Type in FromPcd.Type):\r
                 if ToPcd.Type.strip() == "DynamicEx":\r
-                    ToPcd.Type = FromPcd.Type             \r
+                    ToPcd.Type = FromPcd.Type\r
             elif ToPcd.Type not in [None, ''] and FromPcd.Type not in [None, ''] \\r
                 and ToPcd.Type != FromPcd.Type:\r
                 EdkLogger.error("build", OPTION_CONFLICT, "Mismatched PCD type",\r
@@ -1781,6 +1814,9 @@ class PlatformAutoGen(AutoGen):
             if not IsValid:\r
                 EdkLogger.error('build', FORMAT_INVALID, Cause, File=self.MetaFile,\r
                                 ExtraData="%s.%s" % (ToPcd.TokenSpaceGuidCName, ToPcd.TokenCName))\r
+            ToPcd.validateranges = FromPcd.validateranges\r
+            ToPcd.validlists = FromPcd.validlists\r
+            ToPcd.expressions = FromPcd.expressions\r
 \r
         if ToPcd.DatumType == "VOID*" and ToPcd.MaxDatumSize in ['', None]:\r
             EdkLogger.debug(EdkLogger.DEBUG_9, "No MaxDatumSize specified for PCD %s.%s" \\r
@@ -1814,11 +1850,11 @@ class PlatformAutoGen(AutoGen):
     #\r
     def ApplyPcdSetting(self, Module, Pcds):\r
         # for each PCD in module\r
-        for Name,Guid in Pcds:\r
-            PcdInModule = Pcds[Name,Guid]\r
+        for Name, Guid in Pcds:\r
+            PcdInModule = Pcds[Name, Guid]\r
             # find out the PCD setting in platform\r
-            if (Name,Guid) in self.Platform.Pcds:\r
-                PcdInPlatform = self.Platform.Pcds[Name,Guid]\r
+            if (Name, Guid) in self.Platform.Pcds:\r
+                PcdInPlatform = self.Platform.Pcds[Name, Guid]\r
             else:\r
                 PcdInPlatform = None\r
             # then override the settings if any\r
@@ -1891,8 +1927,8 @@ class PlatformAutoGen(AutoGen):
     # @retval   Value  Priority value based on the priority list.\r
     #\r
     def CalculatePriorityValue(self, Key):\r
-        Target, ToolChain, Arch, CommandType, Attr = Key.split('_')       \r
-        PriorityValue = 0x11111          \r
+        Target, ToolChain, Arch, CommandType, Attr = Key.split('_')\r
+        PriorityValue = 0x11111\r
         if Target == "*":\r
             PriorityValue &= 0x01111\r
         if ToolChain == "*":\r
@@ -1903,9 +1939,9 @@ class PlatformAutoGen(AutoGen):
             PriorityValue &= 0x11101\r
         if Attr == "*":\r
             PriorityValue &= 0x11110\r
-        \r
-        return self.PrioList["0x%0.5x"%PriorityValue]\r
-                                    \r
+\r
+        return self.PrioList["0x%0.5x" % PriorityValue]\r
+\r
 \r
     ## Expand * in build option key\r
     #\r
@@ -1917,7 +1953,7 @@ class PlatformAutoGen(AutoGen):
         BuildOptions = {}\r
         FamilyMatch  = False\r
         FamilyIsNull = True\r
-                \r
+\r
         OverrideList = {}\r
         #\r
         # Construct a list contain the build options which need override.\r
@@ -1927,13 +1963,14 @@ class PlatformAutoGen(AutoGen):
             # Key[0] -- tool family\r
             # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE\r
             #\r
-            if Key[0] == self.BuildRuleFamily :\r
+            if (Key[0] == self.BuildRuleFamily and\r
+                (ModuleStyle == None or len(Key) < 3 or (len(Key) > 2 and Key[2] == ModuleStyle))):\r
                 Target, ToolChain, Arch, CommandType, Attr = Key[1].split('_')\r
                 if Target == self.BuildTarget or Target == "*":\r
                     if ToolChain == self.ToolChain or ToolChain == "*":\r
                         if Arch == self.Arch or Arch == "*":\r
                             if Options[Key].startswith("="):\r
-                                if OverrideList.get(Key[1]) != None:                                                \r
+                                if OverrideList.get(Key[1]) != None:\r
                                     OverrideList.pop(Key[1])\r
                                 OverrideList[Key[1]] = Options[Key]\r
         \r
@@ -1941,9 +1978,9 @@ class PlatformAutoGen(AutoGen):
         # Use the highest priority value. \r
         #\r
         if (len(OverrideList) >= 2):\r
-            KeyList   = OverrideList.keys()\r
+            KeyList = OverrideList.keys()\r
             for Index in range(len(KeyList)):\r
-                NowKey      = KeyList[Index]\r
+                NowKey = KeyList[Index]\r
                 Target1, ToolChain1, Arch1, CommandType1, Attr1 = NowKey.split("_")\r
                 for Index1 in range(len(KeyList) - Index - 1):\r
                     NextKey = KeyList[Index1 + Index + 1]\r
@@ -1957,13 +1994,12 @@ class PlatformAutoGen(AutoGen):
                                 if CommandType1 == CommandType2 or CommandType1 == "*" or CommandType2 == "*":\r
                                     if Attr1 == Attr2 or Attr1 == "*" or Attr2 == "*":\r
                                         if self.CalculatePriorityValue(NowKey) > self.CalculatePriorityValue(NextKey):\r
-                                            if Options.get((self.BuildRuleFamily, NextKey)) != None:  \r
+                                            if Options.get((self.BuildRuleFamily, NextKey)) != None:\r
                                                 Options.pop((self.BuildRuleFamily, NextKey))\r
                                         else:\r
-                                            if Options.get((self.BuildRuleFamily, NowKey)) != None: \r
+                                            if Options.get((self.BuildRuleFamily, NowKey)) != None:\r
                                                 Options.pop((self.BuildRuleFamily, NowKey))\r
                                                            \r
-        \r
         for Key in Options:\r
             if ModuleStyle != None and len (Key) > 2:\r
                 # Check Module style is EDK or EDKII.\r
@@ -1989,7 +2025,7 @@ class PlatformAutoGen(AutoGen):
                     if Arch == "*" or Arch == self.Arch:\r
                         if Tool not in BuildOptions:\r
                             BuildOptions[Tool] = {}\r
-                        if Attr != "FLAGS" or Attr not in BuildOptions[Tool]:\r
+                        if Attr != "FLAGS" or Attr not in BuildOptions[Tool] or Options[Key].startswith('='):\r
                             BuildOptions[Tool][Attr] = Options[Key]\r
                         else:\r
                             # append options for the same tool\r
@@ -1997,7 +2033,7 @@ class PlatformAutoGen(AutoGen):
         # Build Option Family has been checked, which need't to be checked again for family.\r
         if FamilyMatch or FamilyIsNull:\r
             return BuildOptions\r
-        \r
+\r
         for Key in Options:\r
             if ModuleStyle != None and len (Key) > 2:\r
                 # Check Module style is EDK or EDKII.\r
@@ -2009,7 +2045,7 @@ class PlatformAutoGen(AutoGen):
             Family = Key[0]\r
             Target, Tag, Arch, Tool, Attr = Key[1].split("_")\r
             # if tool chain family doesn't match, skip it\r
-            if Tool not in self.ToolDefinition or Family =="":\r
+            if Tool not in self.ToolDefinition or Family == "":\r
                 continue\r
             # option has been added before\r
             if Family != self.ToolDefinition[Tool][TAB_TOD_DEFINES_FAMILY]:\r
@@ -2021,7 +2057,7 @@ class PlatformAutoGen(AutoGen):
                     if Arch == "*" or Arch == self.Arch:\r
                         if Tool not in BuildOptions:\r
                             BuildOptions[Tool] = {}\r
-                        if Attr != "FLAGS" or Attr not in BuildOptions[Tool]:\r
+                        if Attr != "FLAGS" or Attr not in BuildOptions[Tool] or Options[Key].startswith('='):\r
                             BuildOptions[Tool][Attr] = Options[Key]\r
                         else:\r
                             # append options for the same tool\r
@@ -2038,8 +2074,11 @@ class PlatformAutoGen(AutoGen):
         # Get the different options for the different style module\r
         if Module.AutoGenVersion < 0x00010005:\r
             PlatformOptions = self.EdkBuildOption\r
+            ModuleTypeOptions = self.Platform.GetBuildOptionsByModuleType(EDK_NAME, Module.ModuleType)\r
         else:\r
             PlatformOptions = self.EdkIIBuildOption\r
+            ModuleTypeOptions = self.Platform.GetBuildOptionsByModuleType(EDKII_NAME, Module.ModuleType)\r
+        ModuleTypeOptions = self._ExpandBuildOption(ModuleTypeOptions)\r
         ModuleOptions = self._ExpandBuildOption(Module.BuildOptions)\r
         if Module in self.Platform.Modules:\r
             PlatformModule = self.Platform.Modules[str(Module)]\r
@@ -2047,23 +2086,40 @@ class PlatformAutoGen(AutoGen):
         else:\r
             PlatformModuleOptions = {}\r
 \r
-        AllTools = set(ModuleOptions.keys() + PlatformOptions.keys() + PlatformModuleOptions.keys() + self.ToolDefinition.keys())\r
+        BuildRuleOrder = None\r
+        for Options in [self.ToolDefinition, ModuleOptions, PlatformOptions, ModuleTypeOptions, PlatformModuleOptions]:\r
+            for Tool in Options:\r
+                for Attr in Options[Tool]:\r
+                    if Attr == TAB_TOD_DEFINES_BUILDRULEORDER:\r
+                        BuildRuleOrder = Options[Tool][Attr]\r
+\r
+        AllTools = set(ModuleOptions.keys() + PlatformOptions.keys() +\r
+                       PlatformModuleOptions.keys() + ModuleTypeOptions.keys() +\r
+                       self.ToolDefinition.keys())\r
         BuildOptions = {}\r
         for Tool in AllTools:\r
             if Tool not in BuildOptions:\r
                 BuildOptions[Tool] = {}\r
 \r
-            for Options in [self.ToolDefinition, ModuleOptions, PlatformOptions, PlatformModuleOptions]:\r
+            for Options in [self.ToolDefinition, ModuleOptions, PlatformOptions, ModuleTypeOptions, PlatformModuleOptions]:\r
                 if Tool not in Options:\r
                     continue\r
                 for Attr in Options[Tool]:\r
                     Value = Options[Tool][Attr]\r
+                    #\r
+                    # Do not generate it in Makefile\r
+                    #\r
+                    if Attr == TAB_TOD_DEFINES_BUILDRULEORDER:\r
+                        continue\r
                     if Attr not in BuildOptions[Tool]:\r
                         BuildOptions[Tool][Attr] = ""\r
                     # check if override is indicated\r
                     if Value.startswith('='):\r
-                        BuildOptions[Tool][Attr] = Value[1:]\r
+                        ToolPath = Value[1:]\r
+                        ToolPath = mws.handleWsMacro(ToolPath)\r
+                        BuildOptions[Tool][Attr] = ToolPath\r
                     else:\r
+                        Value = mws.handleWsMacro(Value)\r
                         BuildOptions[Tool][Attr] += " " + Value\r
         if Module.AutoGenVersion < 0x00010005 and self.Workspace.UniFlag != None:\r
             #\r
@@ -2072,7 +2128,7 @@ class PlatformAutoGen(AutoGen):
             if 'BUILD' not in BuildOptions:\r
                 BuildOptions['BUILD'] = {}\r
             BuildOptions['BUILD']['FLAGS'] = self.Workspace.UniFlag\r
-        return BuildOptions\r
+        return BuildOptions, BuildRuleOrder\r
 \r
     Platform            = property(_GetPlatform)\r
     Name                = property(_GetName)\r
@@ -2140,6 +2196,8 @@ class ModuleAutoGen(AutoGen):
             return False\r
 \r
         self.SourceDir = self.MetaFile.SubDir\r
+        self.SourceDir = mws.relpath(self.SourceDir, self.WorkspaceDir)\r
+\r
         self.SourceOverrideDir = None\r
         # use overrided path defined in DSC file\r
         if self.MetaFile.Key in GlobalData.gOverrideDir:\r
@@ -2157,6 +2215,7 @@ class ModuleAutoGen(AutoGen):
         self.DepexGenerated = False\r
 \r
         self.BuildDatabase = self.Workspace.BuildDatabase\r
+        self.BuildRuleOrder = None\r
 \r
         self._Module          = None\r
         self._Name            = None\r
@@ -2234,12 +2293,25 @@ class ModuleAutoGen(AutoGen):
                 \r
         return self._FixedAtBuildPcds        \r
 \r
+    def _GetUniqueBaseName(self):\r
+        BaseName = self.Name\r
+        for Module in self.PlatformInfo.ModuleAutoGenList:\r
+            if Module.MetaFile == self.MetaFile:\r
+                continue\r
+            if Module.Name == self.Name:\r
+                if uuid.UUID(Module.Guid) == uuid.UUID(self.Guid):\r
+                    EdkLogger.error("build", FILE_DUPLICATED, 'Modules have same BaseName and FILE_GUID:\n'\r
+                                    '  %s\n  %s' % (Module.MetaFile, self.MetaFile))\r
+                BaseName = '%s_%s' % (self.Name, self.Guid)\r
+        return BaseName\r
+\r
     # Macros could be used in build_rule.txt (also Makefile)\r
     def _GetMacros(self):\r
         if self._Macro == None:\r
             self._Macro = sdict()\r
             self._Macro["WORKSPACE"             ] = self.WorkspaceDir\r
             self._Macro["MODULE_NAME"           ] = self.Name\r
+            self._Macro["MODULE_NAME_GUID"      ] = self._GetUniqueBaseName()\r
             self._Macro["MODULE_GUID"           ] = self.Guid\r
             self._Macro["MODULE_VERSION"        ] = self.Version\r
             self._Macro["MODULE_TYPE"           ] = self.ModuleType\r
@@ -2284,6 +2356,16 @@ class ModuleAutoGen(AutoGen):
 \r
     ## Return the module meta-file GUID\r
     def _GetGuid(self):\r
+        #\r
+        # To build same module more than once, the module path with FILE_GUID overridden has\r
+        # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path\r
+        # in DSC. The overridden GUID can be retrieved from file name\r
+        #\r
+        if os.path.basename(self.MetaFile.File) != os.path.basename(self.MetaFile.Path):\r
+            #\r
+            # Length of GUID is 36\r
+            #\r
+            return os.path.basename(self.MetaFile.Path)[:36]\r
         return self.Module.Guid\r
 \r
     ## Return the module version\r
@@ -2393,7 +2475,66 @@ class ModuleAutoGen(AutoGen):
                     continue\r
                 PackageList.append(Package)\r
         return PackageList\r
-\r
+    \r
+    ## Get the depex string\r
+    #\r
+    # @return : a string contain all depex expresion.\r
+    def _GetDepexExpresionString(self):\r
+        DepexStr = ''\r
+        DepexList = []\r
+        ## DPX_SOURCE IN Define section.\r
+        if self.Module.DxsFile:\r
+            return DepexStr\r
+        for M in [self.Module] + self.DependentLibraryList:\r
+            Filename = M.MetaFile.Path\r
+            InfObj = InfSectionParser.InfSectionParser(Filename)\r
+            DepexExpresionList = InfObj.GetDepexExpresionList()\r
+            for DepexExpresion in DepexExpresionList:\r
+                for key in DepexExpresion.keys():\r
+                    Arch, ModuleType = key\r
+                    # the type of build module is USER_DEFINED.\r
+                    # All different DEPEX section tags would be copied into the As Built INF file\r
+                    # and there would be separate DEPEX section tags\r
+                    if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:\r
+                        if (Arch.upper() == self.Arch.upper()) and (ModuleType.upper() != TAB_ARCH_COMMON):\r
+                            DepexList.append({(Arch, ModuleType): DepexExpresion[key][:]})\r
+                    else:\r
+                        if Arch.upper() == TAB_ARCH_COMMON or \\r
+                          (Arch.upper() == self.Arch.upper() and \\r
+                          ModuleType.upper() in [TAB_ARCH_COMMON, self.ModuleType.upper()]):\r
+                            DepexList.append({(Arch, ModuleType): DepexExpresion[key][:]})\r
+        \r
+        #the type of build module is USER_DEFINED.\r
+        if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:\r
+            for Depex in DepexList:\r
+                for key in Depex.keys():\r
+                    DepexStr += '[Depex.%s.%s]\n' % key\r
+                    DepexStr += '\n'.join(['# '+ val for val in Depex[key]])\r
+                    DepexStr += '\n\n'\r
+            if not DepexStr:\r
+                return '[Depex.%s]\n' % self.Arch\r
+            return DepexStr\r
+        \r
+        #the type of build module not is USER_DEFINED.\r
+        Count = 0\r
+        for Depex in DepexList:\r
+            Count += 1\r
+            if DepexStr != '':\r
+                DepexStr += ' AND '\r
+            DepexStr += '('\r
+            for D in Depex.values():\r
+                DepexStr += ' '.join([val for val in D])\r
+            Index = DepexStr.find('END')\r
+            if Index > -1 and Index == len(DepexStr) - 3:\r
+                DepexStr = DepexStr[:-3]\r
+            DepexStr = DepexStr.strip()\r
+            DepexStr += ')'\r
+        if Count == 1:\r
+            DepexStr = DepexStr.lstrip('(').rstrip(')').strip()\r
+        if not DepexStr:\r
+            return '[Depex.%s]\n' % self.Arch\r
+        return '[Depex.%s]\n#  ' % self.Arch + DepexStr\r
+    \r
     ## Merge dependency expression\r
     #\r
     #   @retval     list    The token list of the dependency expression after parsed\r
@@ -2480,7 +2621,9 @@ class ModuleAutoGen(AutoGen):
     #\r
     def _GetModuleBuildOption(self):\r
         if self._BuildOption == None:\r
-            self._BuildOption = self.PlatformInfo.ApplyBuildOption(self.Module)\r
+            self._BuildOption, self.BuildRuleOrder = self.PlatformInfo.ApplyBuildOption(self.Module)\r
+            if self.BuildRuleOrder:\r
+                self.BuildRuleOrder = ['.%s' % Ext for Ext in self.BuildRuleOrder.split()]\r
         return self._BuildOption\r
 \r
     ## Get include path list from tool option for the module build\r
@@ -2494,9 +2637,9 @@ class ModuleAutoGen(AutoGen):
             # is the former use /I , the Latter used -I to specify include directories\r
             #\r
             if self.PlatformInfo.ToolChainFamily in ('MSFT'):\r
-                gBuildOptIncludePattern = re.compile(r"(?:.*?)/I[ \t]*([^ ]*)", re.MULTILINE|re.DOTALL)\r
+                gBuildOptIncludePattern = re.compile(r"(?:.*?)/I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)\r
             elif self.PlatformInfo.ToolChainFamily in ('INTEL', 'GCC', 'RVCT'):\r
-                gBuildOptIncludePattern = re.compile(r"(?:.*?)-I[ \t]*([^ ]*)", re.MULTILINE|re.DOTALL)\r
+                gBuildOptIncludePattern = re.compile(r"(?:.*?)-I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)\r
             else:\r
                 #\r
                 # New ToolChainFamily, don't known whether there is option to specify include directories\r
@@ -2530,11 +2673,11 @@ class ModuleAutoGen(AutoGen):
                 if self.AutoGenVersion >= 0x00010005 and len(IncPathList) > 0:\r
                     for Path in IncPathList:\r
                         if (Path not in self.IncludePathList) and (CommonPath([Path, self.MetaFile.Dir]) != self.MetaFile.Dir):\r
-                            ErrMsg = "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path, Tool, FlagOption) \r
-                            EdkLogger.error("build", \r
+                            ErrMsg = "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path, Tool, FlagOption)\r
+                            EdkLogger.error("build",\r
                                             PARAMETER_INVALID,\r
-                                            ExtraData = ErrMsg, \r
-                                            File = str(self.MetaFile))\r
+                                            ExtraData=ErrMsg,\r
+                                            File=str(self.MetaFile))\r
 \r
                 \r
                 BuildOptionIncPathList += IncPathList\r
@@ -2546,7 +2689,7 @@ class ModuleAutoGen(AutoGen):
     ## Return a list of files which can be built from source\r
     #\r
     #  What kind of files can be built is determined by build rules in\r
-    #  $(WORKSPACE)/Conf/build_rule.txt and toolchain family.\r
+    #  $(CONF_DIRECTORY)/build_rule.txt and toolchain family.\r
     #\r
     def _GetSourceFileList(self):\r
         if self._SourceFileList == None:\r
@@ -2639,6 +2782,11 @@ class ModuleAutoGen(AutoGen):
         RuleChain = []\r
         SourceList = [File]\r
         Index = 0\r
+        #\r
+        # Make sure to get build rule order value\r
+        #\r
+        self._GetModuleBuildOption()\r
+\r
         while Index < len(SourceList):\r
             Source = SourceList[Index]\r
             Index = Index + 1\r
@@ -2649,7 +2797,7 @@ class ModuleAutoGen(AutoGen):
             if File.IsBinary and File == Source and self._BinaryFileList != None and File in self._BinaryFileList:\r
                 # Skip all files that are not binary libraries\r
                 if not self.IsLibrary:\r
-                    continue            \r
+                    continue\r
                 RuleObject = self.BuildRules[TAB_DEFAULT_BINARY_FILE]\r
             elif FileType in self.BuildRules:\r
                 RuleObject = self.BuildRules[FileType]\r
@@ -2672,7 +2820,7 @@ class ModuleAutoGen(AutoGen):
                     self._FinalBuildTargetList.add(LastTarget)\r
                 break\r
 \r
-            Target = RuleObject.Apply(Source)\r
+            Target = RuleObject.Apply(Source, self.BuildRuleOrder)\r
             if not Target:\r
                 if LastTarget:\r
                     self._FinalBuildTargetList.add(LastTarget)\r
@@ -2831,7 +2979,8 @@ class ModuleAutoGen(AutoGen):
     #\r
     def _GetGuidList(self):\r
         if self._GuidList == None:\r
-            self._GuidList = self.Module.Guids\r
+            self._GuidList = sdict()\r
+            self._GuidList.update(self.Module.Guids)\r
             for Library in self.DependentLibraryList:\r
                 self._GuidList.update(Library.Guids)\r
                 self.UpdateComments(self._GuidComments, Library.GuidComments)\r
@@ -2851,7 +3000,8 @@ class ModuleAutoGen(AutoGen):
     #\r
     def _GetProtocolList(self):\r
         if self._ProtocolList == None:\r
-            self._ProtocolList = self.Module.Protocols\r
+            self._ProtocolList = sdict()\r
+            self._ProtocolList.update(self.Module.Protocols)\r
             for Library in self.DependentLibraryList:\r
                 self._ProtocolList.update(Library.Protocols)\r
                 self.UpdateComments(self._ProtocolComments, Library.ProtocolComments)\r
@@ -2864,7 +3014,8 @@ class ModuleAutoGen(AutoGen):
     #\r
     def _GetPpiList(self):\r
         if self._PpiList == None:\r
-            self._PpiList = self.Module.Ppis\r
+            self._PpiList = sdict()\r
+            self._PpiList.update(self.Module.Ppis)\r
             for Library in self.DependentLibraryList:\r
                 self._PpiList.update(Library.Ppis)\r
                 self.UpdateComments(self._PpiComments, Library.PpiComments)\r
@@ -2893,7 +3044,7 @@ class ModuleAutoGen(AutoGen):
                 self._IncludePathList.append(self.DebugDir)\r
 \r
             for Package in self.Module.Packages:\r
-                PackageDir = path.join(self.WorkspaceDir, Package.MetaFile.Dir)\r
+                PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir)\r
                 if PackageDir not in self._IncludePathList:\r
                     self._IncludePathList.append(PackageDir)\r
                 for Inc in Package.Includes:\r
@@ -2901,6 +3052,141 @@ class ModuleAutoGen(AutoGen):
                         self._IncludePathList.append(str(Inc))\r
         return self._IncludePathList\r
 \r
+    ## Get HII EX PCDs which maybe used by VFR\r
+    #\r
+    #  efivarstore used by VFR may relate with HII EX PCDs\r
+    #  Get the variable name and GUID from efivarstore and HII EX PCD\r
+    #  List the HII EX PCDs in As Built INF if both name and GUID match.\r
+    #\r
+    #  @retval    list    HII EX PCDs\r
+    #\r
+    def _GetPcdsMaybeUsedByVfr(self):\r
+        if not self.SourceFileList:\r
+            return []\r
+\r
+        NameGuids = []\r
+        for SrcFile in self.SourceFileList:\r
+            if SrcFile.Ext.lower() != '.vfr':\r
+                continue\r
+            Vfri = os.path.join(self.OutputDir, SrcFile.BaseName + '.i')\r
+            if not os.path.exists(Vfri):\r
+                continue\r
+            VfriFile = open(Vfri, 'r')\r
+            Content = VfriFile.read()\r
+            VfriFile.close()\r
+            Pos = Content.find('efivarstore')\r
+            while Pos != -1:\r
+                #\r
+                # Make sure 'efivarstore' is the start of efivarstore statement\r
+                # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'\r
+                #\r
+                Index = Pos - 1\r
+                while Index >= 0 and Content[Index] in ' \t\r\n':\r
+                    Index -= 1\r
+                if Index >= 0 and Content[Index] != ';':\r
+                    Pos = Content.find('efivarstore', Pos + len('efivarstore'))\r
+                    continue\r
+                #\r
+                # 'efivarstore' must be followed by name and guid\r
+                #\r
+                Name = gEfiVarStoreNamePattern.search(Content, Pos)\r
+                if not Name:\r
+                    break\r
+                Guid = gEfiVarStoreGuidPattern.search(Content, Pos)\r
+                if not Guid:\r
+                    break\r
+                NameArray = ConvertStringToByteArray('L"' + Name.group(1) + '"')\r
+                NameGuids.append((NameArray, GuidStructureStringToGuidString(Guid.group(1))))\r
+                Pos = Content.find('efivarstore', Name.end())\r
+        if not NameGuids:\r
+            return []\r
+        HiiExPcds = []\r
+        for Pcd in self.PlatformInfo.Platform.Pcds.values():\r
+            if Pcd.Type != TAB_PCDS_DYNAMIC_EX_HII:\r
+                continue\r
+            for SkuName in Pcd.SkuInfoList:\r
+                SkuInfo = Pcd.SkuInfoList[SkuName]\r
+                Name = ConvertStringToByteArray(SkuInfo.VariableName)\r
+                Value = GuidValue(SkuInfo.VariableGuid, self.PlatformInfo.PackageList)\r
+                if not Value:\r
+                    continue\r
+                Guid = GuidStructureStringToGuidString(Value)\r
+                if (Name, Guid) in NameGuids and Pcd not in HiiExPcds:\r
+                    HiiExPcds.append(Pcd)\r
+                    break\r
+\r
+        return HiiExPcds\r
+\r
+    def _GenOffsetBin(self):\r
+        VfrUniBaseName = {}\r
+        for SourceFile in self.Module.Sources:\r
+            if SourceFile.Type.upper() == ".VFR" :\r
+                #\r
+                # search the .map file to find the offset of vfr binary in the PE32+/TE file. \r
+                #\r
+                VfrUniBaseName[SourceFile.BaseName] = (SourceFile.BaseName + "Bin")\r
+            if SourceFile.Type.upper() == ".UNI" :\r
+                #\r
+                # search the .map file to find the offset of Uni strings binary in the PE32+/TE file. \r
+                #\r
+                VfrUniBaseName["UniOffsetName"] = (self.Name + "Strings")\r
+\r
+        if len(VfrUniBaseName) == 0:\r
+            return None\r
+        MapFileName = os.path.join(self.OutputDir, self.Name + ".map")\r
+        EfiFileName = os.path.join(self.OutputDir, self.Name + ".efi")\r
+        VfrUniOffsetList = GetVariableOffset(MapFileName, EfiFileName, VfrUniBaseName.values())\r
+        if not VfrUniOffsetList:\r
+            return None\r
+\r
+        OutputName = '%sOffset.bin' % self.Name\r
+        UniVfrOffsetFileName    =  os.path.join( self.OutputDir, OutputName)\r
+\r
+        try:\r
+            fInputfile = open(UniVfrOffsetFileName, "wb+", 0)\r
+        except:\r
+            EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName,None)\r
+\r
+        # Use a instance of StringIO to cache data\r
+        fStringIO = StringIO('')  \r
+\r
+        for Item in VfrUniOffsetList:\r
+            if (Item[0].find("Strings") != -1):\r
+                #\r
+                # UNI offset in image.\r
+                # GUID + Offset\r
+                # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }\r
+                #\r
+                UniGuid = [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]\r
+                UniGuid = [chr(ItemGuid) for ItemGuid in UniGuid]\r
+                fStringIO.write(''.join(UniGuid))            \r
+                UniValue = pack ('Q', int (Item[1], 16))\r
+                fStringIO.write (UniValue)\r
+            else:\r
+                #\r
+                # VFR binary offset in image.\r
+                # GUID + Offset\r
+                # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };\r
+                #\r
+                VfrGuid = [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]\r
+                VfrGuid = [chr(ItemGuid) for ItemGuid in VfrGuid]\r
+                fStringIO.write(''.join(VfrGuid))                   \r
+                type (Item[1]) \r
+                VfrValue = pack ('Q', int (Item[1], 16))\r
+                fStringIO.write (VfrValue)\r
+        #\r
+        # write data into file.\r
+        #\r
+        try :  \r
+            fInputfile.write (fStringIO.getvalue())\r
+        except:\r
+            EdkLogger.error("build", FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the "\r
+                            "file been locked or using by other applications." %UniVfrOffsetFileName,None)\r
+\r
+        fStringIO.close ()\r
+        fInputfile.close ()\r
+        return OutputName\r
+\r
     ## Create AsBuilt INF file the module\r
     #\r
     def CreateAsBuiltInf(self):\r
@@ -2929,7 +3215,7 @@ class ModuleAutoGen(AutoGen):
         # Also find all packages that the DynamicEx PCDs depend on\r
         Pcds = []\r
         PatchablePcds = {}\r
-        Packages = []        \r
+        Packages = []\r
         PcdCheckList = []\r
         PcdTokenSpaceList = []\r
         for Pcd in self.ModulePcdList + self.LibraryPcdList:\r
@@ -2963,6 +3249,16 @@ class ModuleAutoGen(AutoGen):
                         break\r
                 if Found: break\r
 \r
+        VfrPcds = self._GetPcdsMaybeUsedByVfr()\r
+        for Pkg in self.PlatformInfo.PackageList:\r
+            if Pkg in Packages:\r
+                continue\r
+            for VfrPcd in VfrPcds:\r
+                if ((VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, 'DynamicEx') in Pkg.Pcds or\r
+                    (VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, 'Dynamic') in Pkg.Pcds):\r
+                    Packages += [Pkg]\r
+                    break\r
+\r
         ModuleType = self.ModuleType\r
         if ModuleType == 'UEFI_DRIVER' and self.DepexGenerated:\r
             ModuleType = 'DXE_DRIVER'\r
@@ -2971,16 +3267,32 @@ class ModuleAutoGen(AutoGen):
         if self.PcdIsDriver != '':\r
             DriverType = self.PcdIsDriver\r
 \r
+        Guid = self.Guid\r
+        MDefs = self.Module.Defines\r
+\r
         AsBuiltInfDict = {\r
           'module_name'                       : self.Name,\r
-          'module_guid'                       : self.Guid,\r
+          'module_guid'                       : Guid,\r
           'module_module_type'                : ModuleType,\r
-          'module_version_string'             : self.Version,\r
+          'module_version_string'             : [MDefs['VERSION_STRING']] if 'VERSION_STRING' in MDefs else [],\r
           'pcd_is_driver_string'              : [],\r
           'module_uefi_specification_version' : [],\r
           'module_pi_specification_version'   : [],\r
+          'module_entry_point'                : self.Module.ModuleEntryPointList,\r
+          'module_unload_image'               : self.Module.ModuleUnloadImageList,\r
+          'module_constructor'                : self.Module.ConstructorList,\r
+          'module_destructor'                 : self.Module.DestructorList,\r
+          'module_shadow'                     : [MDefs['SHADOW']] if 'SHADOW' in MDefs else [],\r
+          'module_pci_vendor_id'              : [MDefs['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs else [],\r
+          'module_pci_device_id'              : [MDefs['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs else [],\r
+          'module_pci_class_code'             : [MDefs['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs else [],\r
+          'module_pci_revision'               : [MDefs['PCI_REVISION']] if 'PCI_REVISION' in MDefs else [],\r
+          'module_build_number'               : [MDefs['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs else [],\r
+          'module_spec'                       : [MDefs['SPEC']] if 'SPEC' in MDefs else [],\r
+          'module_uefi_hii_resource_section'  : [MDefs['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs else [],\r
+          'module_uni_file'                   : [MDefs['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs else [],\r
           'module_arch'                       : self.Arch,\r
-          'package_item'                      : ['%s' % (Package.MetaFile.File.replace('\\','/')) for Package in Packages],\r
+          'package_item'                      : ['%s' % (Package.MetaFile.File.replace('\\', '/')) for Package in Packages],\r
           'binary_item'                       : [],\r
           'patchablepcd_item'                 : [],\r
           'pcd_item'                          : [],\r
@@ -2990,7 +3302,12 @@ class ModuleAutoGen(AutoGen):
           'flags_item'                        : [],\r
           'libraryclasses_item'               : []\r
         }\r
-        AsBuiltInfDict['module_inf_version'] = '0x%08x' % self.AutoGenVersion\r
+\r
+        if self.AutoGenVersion > int(gInfSpecVersion, 0):\r
+            AsBuiltInfDict['module_inf_version'] = '0x%08x' % self.AutoGenVersion\r
+        else:\r
+            AsBuiltInfDict['module_inf_version'] = gInfSpecVersion\r
+\r
         if DriverType:\r
             AsBuiltInfDict['pcd_is_driver_string'] += [DriverType]\r
 \r
@@ -2999,31 +3316,35 @@ class ModuleAutoGen(AutoGen):
         if 'PI_SPECIFICATION_VERSION' in self.Specification:\r
           AsBuiltInfDict['module_pi_specification_version'] += [self.Specification['PI_SPECIFICATION_VERSION']]\r
 \r
-        OutputDir = self.OutputDir.replace('\\','/').strip('/')\r
+        OutputDir = self.OutputDir.replace('\\', '/').strip('/')\r
         if self.ModuleType in ['BASE', 'USER_DEFINED']:\r
           for Item in self.CodaTargetList:\r
-            File = Item.Target.Path.replace('\\','/').strip('/').replace(OutputDir,'').strip('/')\r
-            if Item.Target.Ext.lower() == '.aml': \r
+            File = Item.Target.Path.replace('\\', '/').strip('/').replace(OutputDir, '').strip('/')\r
+            if Item.Target.Ext.lower() == '.aml':\r
               AsBuiltInfDict['binary_item'] += ['ASL|' + File]\r
-            elif Item.Target.Ext.lower() == '.acpi': \r
+            elif Item.Target.Ext.lower() == '.acpi':\r
               AsBuiltInfDict['binary_item'] += ['ACPI|' + File]\r
             else:\r
               AsBuiltInfDict['binary_item'] += ['BIN|' + File]\r
         else:\r
           for Item in self.CodaTargetList:\r
-            File = Item.Target.Path.replace('\\','/').strip('/').replace(OutputDir,'').strip('/')\r
-            if Item.Target.Ext.lower() == '.efi': \r
+            File = Item.Target.Path.replace('\\', '/').strip('/').replace(OutputDir, '').strip('/')\r
+            if Item.Target.Ext.lower() == '.efi':\r
               AsBuiltInfDict['binary_item'] += ['PE32|' + self.Name + '.efi']\r
             else:\r
               AsBuiltInfDict['binary_item'] += ['BIN|' + File]\r
           if self.DepexGenerated:\r
             if self.ModuleType in ['PEIM']:\r
               AsBuiltInfDict['binary_item'] += ['PEI_DEPEX|' + self.Name + '.depex']\r
-            if self.ModuleType in ['DXE_DRIVER','DXE_RUNTIME_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER']:\r
+            if self.ModuleType in ['DXE_DRIVER', 'DXE_RUNTIME_DRIVER', 'DXE_SAL_DRIVER', 'UEFI_DRIVER']:\r
               AsBuiltInfDict['binary_item'] += ['DXE_DEPEX|' + self.Name + '.depex']\r
             if self.ModuleType in ['DXE_SMM_DRIVER']:\r
               AsBuiltInfDict['binary_item'] += ['SMM_DEPEX|' + self.Name + '.depex']\r
 \r
+        Bin = self._GenOffsetBin()\r
+        if Bin:\r
+            AsBuiltInfDict['binary_item'] += ['BIN|%s' % Bin]\r
+\r
         for Root, Dirs, Files in os.walk(OutputDir):\r
             for File in Files:\r
                 if File.lower().endswith('.pdb'):\r
@@ -3036,6 +3357,8 @@ class ModuleAutoGen(AutoGen):
                 StartPos = Index\r
                 break\r
         AsBuiltInfDict['header_comments'] = '\n'.join(HeaderComments[StartPos:]).replace(':#', '://')\r
+        AsBuiltInfDict['tail_comments'] = '\n'.join(self.Module.TailComments)\r
+\r
         GenList = [\r
             (self.ProtocolList, self._ProtocolComments, 'protocol_item'),\r
             (self.PpiList, self._PpiComments, 'ppi_item'),\r
@@ -3116,28 +3439,42 @@ class ModuleAutoGen(AutoGen):
                 if PcdComments:\r
                     PcdItem = PcdComments + '\n  ' + PcdItem\r
                 AsBuiltInfDict['patchablepcd_item'].append(PcdItem)\r
-        for Pcd in Pcds:\r
+\r
+        HiiPcds = []\r
+        for Pcd in Pcds + VfrPcds:\r
             PcdComments = ''\r
             PcdCommentList = []\r
             HiiInfo = ''\r
+            SkuId = ''\r
             if Pcd.Type == TAB_PCDS_DYNAMIC_EX_HII:\r
                 for SkuName in Pcd.SkuInfoList:\r
                     SkuInfo = Pcd.SkuInfoList[SkuName]\r
+                    SkuId = SkuInfo.SkuId\r
                     HiiInfo = '## %s|%s|%s' % (SkuInfo.VariableName, SkuInfo.VariableGuid, SkuInfo.VariableOffset)\r
                     break\r
+            if SkuId:\r
+                #\r
+                # Don't generate duplicated HII PCD\r
+                #\r
+                if (SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in HiiPcds:\r
+                    continue\r
+                else:\r
+                    HiiPcds.append((SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
             if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
                 PcdCommentList = self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName][:]\r
             if HiiInfo:\r
                 UsageIndex = -1\r
+                UsageStr = ''\r
                 for Index, Comment in enumerate(PcdCommentList):\r
                     for Usage in UsageList:\r
                         if Comment.find(Usage) != -1:\r
+                            UsageStr = Usage\r
                             UsageIndex = Index\r
                             break\r
                 if UsageIndex != -1:\r
-                    PcdCommentList[UsageIndex] = PcdCommentList[UsageIndex] + ' ' + HiiInfo\r
+                    PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, '')) \r
                 else:\r
-                    PcdCommentList.append('## ' + HiiInfo)\r
+                    PcdCommentList.append('## UNDEFINED ' + HiiInfo)\r
             PcdComments = '\n  '.join(PcdCommentList)\r
             PcdEntry = Pcd.TokenSpaceGuidCName + '.' + Pcd.TokenCName\r
             if PcdComments:\r
@@ -3146,6 +3483,16 @@ class ModuleAutoGen(AutoGen):
         for Item in self.BuildOption:\r
           if 'FLAGS' in self.BuildOption[Item]:\r
             AsBuiltInfDict['flags_item'] += ['%s:%s_%s_%s_%s_FLAGS = %s' % (self.ToolChainFamily, self.BuildTarget, self.ToolChain, self.Arch, Item, self.BuildOption[Item]['FLAGS'].strip())]\r
+\r
+        # Generated LibraryClasses section in comments.\r
+        for Library in self.LibraryAutoGenList:\r
+            AsBuiltInfDict['libraryclasses_item'] += [Library.MetaFile.File.replace('\\', '/')]\r
+        \r
+        # Generated depex expression section in comments.\r
+        AsBuiltInfDict['depexsection_item'] = ''\r
+        DepexExpresion = self._GetDepexExpresionString()\r
+        if DepexExpresion:\r
+            AsBuiltInfDict['depexsection_item'] = DepexExpresion\r
         \r
         AsBuiltInf = TemplateString()\r
         AsBuiltInf.Append(gAsBuiltInfHeaderString.Replace(AsBuiltInfDict))\r
@@ -3160,8 +3507,10 @@ class ModuleAutoGen(AutoGen):
     #                                       dependent libraries will be created\r
     #\r
     def CreateMakeFile(self, CreateLibraryMakeFile=True):\r
+        # Ignore generating makefile when it is a binary module\r
         if self.IsBinaryModule:\r
             return\r
+\r
         if self.IsMakeFileCreated:\r
             return\r
 \r
@@ -3201,7 +3550,8 @@ class ModuleAutoGen(AutoGen):
             CreatePcdDatabaseCode(self, TemplateString(), TemplateString())\r
             return\r
         if self.IsBinaryModule:\r
-            self.CopyBinaryFiles()\r
+            if self.IsLibrary:\r
+                self.CopyBinaryFiles()\r
             return\r
 \r
         if not self.IsLibrary and CreateLibraryCodeFile:\r