]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/AutoGen/AutoGen.py
CryptoPkg: Fix GCC build break for BaseCryptLib.
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / AutoGen.py
index 3b8024c199bd93e2ee4271bc127d3995880ad8d9..8150ea0b69014ca45d2387323f5feb982d715788 100644 (file)
@@ -1,7 +1,7 @@
 ## @file\r
 # Generate AutoGen.h, AutoGen.c and *.depex files\r
 #\r
-# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>\r
+# Copyright (c) 2007 - 2011, 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
@@ -34,6 +34,7 @@ import Common.GlobalData as GlobalData
 from GenFds.FdfParser import *\r
 from CommonDataClass.CommonClass import SkuInfoClass\r
 from Workspace.BuildClassObject import *\r
+import Common.VpdInfoFile as VpdInfoFile\r
 \r
 ## Regular expression for splitting Dependency Expression stirng into tokens\r
 gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)")\r
@@ -52,6 +53,39 @@ gAutoGenStringFileName = "%(module_name)sStrDefs.h"
 gAutoGenStringFormFileName = "%(module_name)sStrDefs.hpk"\r
 gAutoGenDepexFileName = "%(module_name)s.depex"\r
 \r
+#\r
+# Template string to generic AsBuilt INF\r
+#\r
+gAsBuiltInfHeaderString = TemplateString("""## @file\r
+# ${module_name}\r
+#\r
+# DO NOT EDIT\r
+# FILE auto-generated Binary INF\r
+#\r
+##\r
+\r
+[Defines]\r
+  INF_VERSION                = 0x00010016\r
+  BASE_NAME                  = ${module_name}\r
+  FILE_GUID                  = ${module_guid}\r
+  MODULE_TYPE                = ${module_module_type}\r
+  VERSION_STRING             = ${module_version_string}${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
+  ${package_item}${END}\r
+\r
+[Binaries.${module_arch}]${BEGIN}\r
+  ${binary_item}${END}\r
+\r
+[PcdEx]${BEGIN}\r
+  ${pcd_item}${END}\r
+\r
+## @AsBuilt${BEGIN}\r
+##   ${flags_item}${END}\r
+""")\r
+\r
 ## Base class for AutoGen\r
 #\r
 #   This class just implements the cache mechanism of AutoGen objects.\r
@@ -121,7 +155,7 @@ class AutoGen(object):
 class WorkspaceAutoGen(AutoGen):\r
     ## Real constructor of WorkspaceAutoGen\r
     #\r
-    # This method behaves the same as __init__ except that it needs explict invoke\r
+    # This method behaves the same as __init__ except that it needs explicit invoke\r
     # (in super class's __new__ method)\r
     #\r
     #   @param  WorkspaceDir            Root directory of workspace\r
@@ -135,10 +169,17 @@ class WorkspaceAutoGen(AutoGen):
     #   @param  FlashDefinitionFile     File of flash definition\r
     #   @param  Fds                     FD list to be generated\r
     #   @param  Fvs                     FV list to be generated\r
+    #   @param  Caps                    Capsule list to be generated\r
     #   @param  SkuId                   SKU id from command line\r
     #\r
     def _Init(self, WorkspaceDir, ActivePlatform, Target, Toolchain, ArchList, MetaFileDb,\r
-              BuildConfig, ToolDefinition, FlashDefinitionFile='', Fds=[], Fvs=[], SkuId='', UniFlag=None):\r
+              BuildConfig, ToolDefinition, FlashDefinitionFile='', Fds=None, Fvs=None, Caps=None, SkuId='', UniFlag=None):\r
+        if Fds is None:\r
+            Fds = []\r
+        if Fvs is None:\r
+            Fvs = []\r
+        if Caps is None:\r
+            Caps = []\r
         self.MetaFile       = ActivePlatform.MetaFile\r
         self.WorkspaceDir   = WorkspaceDir\r
         self.Platform       = ActivePlatform\r
@@ -154,6 +195,7 @@ class WorkspaceAutoGen(AutoGen):
         self.FdfFile        = FlashDefinitionFile\r
         self.FdTargetList   = Fds\r
         self.FvTargetList   = Fvs\r
+        self.CapTargetList  = Caps\r
         self.AutoGenObjectList = []\r
 \r
         # there's many relative directory operations, so ...\r
@@ -161,8 +203,17 @@ class WorkspaceAutoGen(AutoGen):
 \r
         # parse FDF file to get PCDs in it, if any\r
         if self.FdfFile != None and self.FdfFile != '':\r
+            #\r
+            # Make global macros available when parsing FDF file\r
+            #\r
+            InputMacroDict.update(self.BuildDatabase.WorkspaceDb._GlobalMacros)\r
+            #\r
+            # Mark now build in AutoGen Phase\r
+            #\r
+            GlobalData.gAutoGenPhase = True            \r
             Fdf = FdfParser(self.FdfFile.Path)\r
             Fdf.ParseFile()\r
+            GlobalData.gAutoGenPhase = False  \r
             PcdSet = Fdf.Profile.PcdDict\r
             ModuleList = Fdf.Profile.InfList\r
             self.FdfProfile = Fdf.Profile\r
@@ -184,7 +235,20 @@ class WorkspaceAutoGen(AutoGen):
             #\r
             Pa.CollectPlatformDynamicPcds()\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
+        # Check PCD type and definition between DSC and DEC\r
+        #\r
+        self._CheckPcdDefineAndType()\r
+        \r
+        if self.FdfFile:\r
+            self._CheckDuplicateInFV(Fdf)\r
+        \r
         self._BuildDir = None\r
         self._FvDir = None\r
         self._MakeFileDir = None\r
@@ -192,6 +256,180 @@ class WorkspaceAutoGen(AutoGen):
 \r
         return True\r
 \r
+    ## _CheckDuplicateInFV() method\r
+    #\r
+    # Check whether there is duplicate modules/files exist in FV section. \r
+    # The check base on the file GUID;\r
+    #\r
+    def _CheckDuplicateInFV(self, Fdf):\r
+        for Fv in Fdf.Profile.FvDict:\r
+            _GuidDict = {}\r
+            for FfsFile in Fdf.Profile.FvDict[Fv].FfsList:\r
+                if FfsFile.InfFileName and FfsFile.NameGuid == None:\r
+                    #\r
+                    # Get INF file GUID\r
+                    #\r
+                    InfFoundFlag = False                   \r
+                    for Pa in self.AutoGenObjectList:\r
+                        for Module in Pa.ModuleAutoGenList:\r
+                            if path.normpath(Module.MetaFile.File) == path.normpath(FfsFile.InfFileName):\r
+                                InfFoundFlag = True\r
+                                if not Module.Guid.upper() in _GuidDict.keys():\r
+                                    _GuidDict[Module.Guid.upper()] = FfsFile\r
+                                else:\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
+                                                                                                                                   FfsFile.CurrentLineContent,\r
+                                                                                                                                   _GuidDict[Module.Guid.upper()].CurrentLineNum,\r
+                                                                                                                                   _GuidDict[Module.Guid.upper()].CurrentLineContent,\r
+                                                                                                                                   Module.Guid.upper()),\r
+                                                    ExtraData=self.FdfFile)\r
+                    #\r
+                    # Some INF files not have entity in DSC file. \r
+                    #\r
+                    if not InfFoundFlag:\r
+                        if FfsFile.InfFileName.find('$') == -1:\r
+                            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
+                            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
+                            # BuildObject from one of AutoGenObjectList is enough.\r
+                            #\r
+                            InfObj = self.AutoGenObjectList[0].BuildDatabase.WorkspaceDb.BuildObject[PathClassObj, 'COMMON', self.BuildTarget, self.ToolChain]\r
+                            if not InfObj.Guid.upper() in _GuidDict.keys():\r
+                                _GuidDict[InfObj.Guid.upper()] = FfsFile\r
+                            else:\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
+                                                                                                                               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
+                if FfsFile.NameGuid != None:\r
+                    _CheckPCDAsGuidPattern = re.compile("^PCD\(.+\..+\)$")\r
+                    \r
+                    #\r
+                    # If the NameGuid reference a PCD name. \r
+                    # The style must match: PCD(xxxx.yyy)\r
+                    #\r
+                    if _CheckPCDAsGuidPattern.match(FfsFile.NameGuid):\r
+                        #\r
+                        # Replace the PCD value.\r
+                        #\r
+                        _PcdName = FfsFile.NameGuid.lstrip("PCD(").rstrip(")")\r
+                        PcdFoundFlag = False\r
+                        for Pa in self.AutoGenObjectList:\r
+                            if not PcdFoundFlag:\r
+                                for PcdItem in Pa.AllPcdList:\r
+                                    if (PcdItem.TokenSpaceGuidCName + "." + PcdItem.TokenCName) == _PcdName:\r
+                                        #\r
+                                        # First convert from CFormatGuid to GUID string\r
+                                        #\r
+                                        _PcdGuidString = GuidStructureStringToGuidString(PcdItem.DefaultValue)\r
+                                        \r
+                                        if not _PcdGuidString:\r
+                                            #\r
+                                            # Then try Byte array.\r
+                                            #\r
+                                            _PcdGuidString = GuidStructureByteArrayToGuidString(PcdItem.DefaultValue)\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
+                                                            ExtraData=self.FdfFile)\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
+                                                            FORMAT_INVALID,\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
+                    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
+                                        FORMAT_INVALID,\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
+    def _CheckPcdDefineAndType(self):\r
+        PcdTypeList = [\r
+            "FixedAtBuild", "PatchableInModule", "FeatureFlag",\r
+            "Dynamic", #"DynamicHii", "DynamicVpd",\r
+            "DynamicEx", # "DynamicExHii", "DynamicExVpd"\r
+        ]\r
+\r
+        # This dict store PCDs which are not used by any modules with specified arches\r
+        UnusedPcd = sdict()\r
+        for Pa in self.AutoGenObjectList:\r
+            # 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
+                # If no PCD type, this PCD comes from FDF \r
+                if not PcdType:\r
+                    continue\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
+                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
+                        break\r
+                    for Type in PcdTypeList:\r
+                        if (Pcd[0], Pcd[1], Type) in Package.Pcds:\r
+                            EdkLogger.error(\r
+                                'build',\r
+                                FORMAT_INVALID,\r
+                                "Type [%s] of PCD [%s.%s] in DSC file doesn't match the type [%s] defined in DEC file." \\r
+                                % (Pa.Platform.Pcds[Pcd].Type, Pcd[1], Pcd[0], Type),\r
+                                ExtraData=None\r
+                            )\r
+                            return\r
+                else:\r
+                    UnusedPcd.setdefault(Pcd, []).append(Pa.Arch)\r
+\r
+        for Pcd in UnusedPcd:\r
+            EdkLogger.warn(\r
+                'build',\r
+                "The PCD was not specified by any INF module in the platform for the given architecture.\n"\r
+                "\tPCD: [%s.%s]\n\tPlatform: [%s]\n\tArch: %s"\r
+                % (Pcd[1], Pcd[0], os.path.basename(str(self.MetaFile)), str(UnusedPcd[Pcd])),\r
+                ExtraData=None\r
+            )\r
+\r
     def __repr__(self):\r
         return "%s [%s]" % (self.MetaFile, ", ".join(self.ArchList))\r
 \r
@@ -243,8 +481,77 @@ 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
+    ## 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
+    # \r
+    # @return  None\r
+    #\r
+    def _CheckAllPcdsTokenValueConflict(self):\r
+        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
+                Count = 0\r
+                while (Count < len(PcdList) - 1) :\r
+                    Item = PcdList[Count]\r
+                    ItemNext = PcdList[Count + 1]\r
+                    #\r
+                    # Make sure in the same token space the TokenValue should be unique\r
+                    #\r
+                    if (Item.TokenValue == ItemNext.TokenValue):\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
+                                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
+                        while (SameTokenValuePcdListCount < len(SameTokenValuePcdList) - 1):\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
+                                            FORMAT_INVALID,\r
+                                            "The TokenValue [%s] of PCD [%s.%s] is conflict with: [%s.%s] in %s"\\r
+                                            % (TemListItem.TokenValue, TemListItem.TokenSpaceGuidCName, TemListItem.TokenCName, TemListItemNext.TokenSpaceGuidCName, TemListItemNext.TokenCName, Package),\r
+                                            ExtraData=None\r
+                                            )\r
+                            SameTokenValuePcdListCount += 1\r
+                        Count += SameTokenValuePcdListCount\r
+                    Count += 1\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
+                Count = 0\r
+                while (Count < len(PcdList) - 1) :\r
+                    Item = PcdList[Count]\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
+                        EdkLogger.error(\r
+                                    'build',\r
+                                    FORMAT_INVALID,\r
+                                    "The TokenValue [%s] of PCD [%s.%s] in %s defined in two places should be same as well."\\r
+                                    % (Item.TokenValue, Item.TokenSpaceGuidCName, Item.TokenCName, Package),\r
+                                    ExtraData=None\r
+                                    )\r
+                    Count += 1\r
+                                      \r
 \r
-    ## Create makefile for the platform and mdoules in it\r
+    ## Create makefile for the platform and modules in it\r
     #\r
     #   @param      CreateDepsMakeFile      Flag indicating if the makefile for\r
     #                                       modules will be created as well\r
@@ -277,6 +584,11 @@ class WorkspaceAutoGen(AutoGen):
         for Pa in self.AutoGenObjectList:\r
             Pa.CreateCodeFile(CreateDepsCodeFile)\r
 \r
+    ## Create AsBuilt INF file the platform\r
+    #\r
+    def CreateAsBuiltInf(self):\r
+        return\r
+\r
     Name                = property(_GetName)\r
     Guid                = property(_GetGuid)\r
     Version             = property(_GetVersion)\r
@@ -301,7 +613,27 @@ class PlatformAutoGen(AutoGen):
     # \r
     _DynaPcdList_ = []\r
     _NonDynaPcdList_ = []\r
-\r
+    \r
+    #\r
+    # The priority list while override build option \r
+    #\r
+    PrioList = {"0x11111"  : 16,     #  TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)\r
+                "0x01111"  : 15,     #  ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE\r
+                "0x10111"  : 14,     #  TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE\r
+                "0x00111"  : 13,     #  ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE \r
+                "0x11011"  : 12,     #  TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE\r
+                "0x01011"  : 11,     #  ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE\r
+                "0x10011"  : 10,     #  TARGET_*********_****_COMMANDTYPE_ATTRIBUTE\r
+                "0x00011"  : 9,      #  ******_*********_****_COMMANDTYPE_ATTRIBUTE\r
+                "0x11101"  : 8,      #  TARGET_TOOLCHAIN_ARCH_***********_ATTRIBUTE\r
+                "0x01101"  : 7,      #  ******_TOOLCHAIN_ARCH_***********_ATTRIBUTE\r
+                "0x10101"  : 6,      #  TARGET_*********_ARCH_***********_ATTRIBUTE\r
+                "0x00101"  : 5,      #  ******_*********_ARCH_***********_ATTRIBUTE\r
+                "0x11001"  : 4,      #  TARGET_TOOLCHAIN_****_***********_ATTRIBUTE\r
+                "0x01001"  : 3,      #  ******_TOOLCHAIN_****_***********_ATTRIBUTE\r
+                "0x10001"  : 2,      #  TARGET_*********_****_***********_ATTRIBUTE\r
+                "0x00001"  : 1}      #  ******_*********_****_***********_ATTRIBUTE (Lowest)\r
+    \r
     ## The real constructor of PlatformAutoGen\r
     #\r
     #  This method is not supposed to be called by users of PlatformAutoGen. It's\r
@@ -400,6 +732,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
 \r
         # no need to create makefile for the platform more than once\r
         if self.IsMakeFileCreated:\r
@@ -476,19 +809,160 @@ class PlatformAutoGen(AutoGen):
         UnicodePcdArray = []\r
         HiiPcdArray     = []\r
         OtherPcdArray   = []\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
-            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
-                UnicodePcdArray.append(Pcd)\r
-            elif len(Sku.VariableName) > 0:\r
-                # if found HII type PCD then insert to right of UnicodeIndex\r
-                HiiPcdArray.append(Pcd)\r
-            else:\r
-                OtherPcdArray.append(Pcd)\r
-        del self._DynamicPcdList[:]\r
+        VpdPcdDict      = {}\r
+        VpdFile               = VpdInfoFile.VpdInfoFile()\r
+        NeedProcessVpdMapFile = False                    \r
+        \r
+        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.VpdOffset = Sku.VpdOffset.strip()\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
+                    UnicodePcdArray.append(Pcd)\r
+                elif len(Sku.VariableName) > 0:\r
+                    # if found HII type PCD then insert to right of UnicodeIndex\r
+                    HiiPcdArray.append(Pcd)\r
+                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
+            PlatformPcds = self.Platform.Pcds.keys()\r
+            PlatformPcds.sort()            \r
+            #\r
+            # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.\r
+            #\r
+            for PcdKey in PlatformPcds:\r
+                Pcd           = self.Platform.Pcds[PcdKey]                            \r
+                if Pcd.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD]:\r
+                    Pcd           = VpdPcdDict[PcdKey]\r
+                    Sku           = Pcd.SkuInfoList[Pcd.SkuInfoList.keys()[0]]\r
+                    Sku.VpdOffset = Sku.VpdOffset.strip()                \r
+                    #\r
+                    # Fix the optional data of VPD PCD.\r
+                    #\r
+                    if (Pcd.DatumType.strip() != "VOID*"):\r
+                        if Sku.DefaultValue == '':\r
+                            Pcd.SkuInfoList[Pcd.SkuInfoList.keys()[0]].DefaultValue = Pcd.MaxDatumSize\r
+                            Pcd.MaxDatumSize = None\r
+                        else:\r
+                            EdkLogger.error("build", AUTOGEN_ERROR, "PCD setting error",\r
+                                            File=self.MetaFile,\r
+                                            ExtraData="\n\tPCD: %s.%s format incorrect in DSC: %s\n\t\t\n"\r
+                                                      % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, self.Platform.MetaFile.Path))                                                                            \r
+                    \r
+                    VpdFile.Add(Pcd, Sku.VpdOffset)\r
+                    # if the offset of a VPD is *, then it need to be fixed up by third party tool.\r
+                    if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":\r
+                        NeedProcessVpdMapFile = True\r
+                        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
+            # Fix the PCDs define in VPD PCD section that never referenced by module.\r
+            # An example is PCD for signature usage.\r
+            #            \r
+            for DscPcd in PlatformPcds:\r
+                DscPcdEntry = self.Platform.Pcds[DscPcd]\r
+                if DscPcdEntry.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD]:\r
+                    if not (self.Platform.VpdToolGuid == None or self.Platform.VpdToolGuid == ''):\r
+                        FoundFlag = False\r
+                        for VpdPcd in VpdFile._VpdArray.keys():\r
+                            # This PCD has been referenced by module\r
+                            if (VpdPcd.TokenSpaceGuidCName == DscPcdEntry.TokenSpaceGuidCName) and \\r
+                               (VpdPcd.TokenCName == DscPcdEntry.TokenCName):\r
+                                    FoundFlag = True\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
+                            Sku           = DscPcdEntry.SkuInfoList[DscPcdEntry.SkuInfoList.keys()[0]]\r
+                            Sku.VpdOffset = Sku.VpdOffset.strip() \r
+                            \r
+                            # Need to iterate DEC pcd information to get the value & datumtype\r
+                            for eachDec in self.PackageList:\r
+                                for DecPcd in eachDec.Pcds:\r
+                                    DecPcdEntry = eachDec.Pcds[DecPcd]\r
+                                    if (DecPcdEntry.TokenSpaceGuidCName == DscPcdEntry.TokenSpaceGuidCName) and \\r
+                                       (DecPcdEntry.TokenCName == DscPcdEntry.TokenCName):\r
+                                        # Print warning message to let the developer make a determine.\r
+                                        EdkLogger.warn("build", "Unreferenced vpd pcd used!",\r
+                                                        File=self.MetaFile, \\r
+                                                        ExtraData = "PCD: %s.%s used in the DSC file %s is unreferenced." \\r
+                                                        %(DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, self.Platform.MetaFile.Path))  \r
+                                                                              \r
+                                        DscPcdEntry.DatumType    = DecPcdEntry.DatumType\r
+                                        DscPcdEntry.DefaultValue = DecPcdEntry.DefaultValue\r
+                                        # Only fix the value while no value provided in DSC file.\r
+                                        if (Sku.DefaultValue == "" or Sku.DefaultValue==None):\r
+                                            DscPcdEntry.SkuInfoList[DscPcdEntry.SkuInfoList.keys()[0]].DefaultValue = DecPcdEntry.DefaultValue\r
+                                                                                                                \r
+                                                       \r
+                            VpdFile.Add(DscPcdEntry, Sku.VpdOffset)\r
+                            # if the offset of a VPD is *, then it need to be fixed up by third party tool.\r
+                            if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":\r
+                                NeedProcessVpdMapFile = True                        \r
+                    \r
+                    \r
+            if (self.Platform.FlashDefinition == None or self.Platform.FlashDefinition == '') and \\r
+               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
+            if VpdFile.GetCount() != 0:\r
+                WorkspaceDb = self.BuildDatabase.WorkspaceDb\r
+                DscTimeStamp = WorkspaceDb.GetTimeStamp(WorkspaceDb.GetFileId(str(self.Platform.MetaFile)))\r
+                FvPath = os.path.join(self.BuildDir, "FV")\r
+                if not os.path.exists(FvPath):\r
+                    try:\r
+                        os.makedirs(FvPath)\r
+                    except:\r
+                        EdkLogger.error("build", FILE_WRITE_FAILURE, "Fail to create FV folder under %s" % self.BuildDir)\r
+                        \r
+        \r
+                VpdFilePath = os.path.join(FvPath, "%s.txt" % self.Platform.VpdToolGuid)\r
+\r
+                \r
+                if not os.path.exists(VpdFilePath) or os.path.getmtime(VpdFilePath) < DscTimeStamp:\r
+                    VpdFile.Write(VpdFilePath)\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
+                        if ToolDef.has_key("GUID") and ToolDef["GUID"] == self.Platform.VpdToolGuid:\r
+                            if not ToolDef.has_key("PATH"):\r
+                                EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self.Platform.VpdToolGuid)\r
+                            BPDGToolName = ToolDef["PATH"]\r
+                            break\r
+                    # Call third party GUID BPDG tool.\r
+                    if BPDGToolName != None:\r
+                        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
+                # 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
+                        # Fixup "*" offset\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
+                            if Sku.VpdOffset == "*":\r
+                                Sku.VpdOffset = VpdFile.GetOffset(Pcd)[0]\r
+                    else:\r
+                        EdkLogger.error("build", FILE_READ_FAILURE, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath)\r
+            \r
+            # Delete the DynamicPcdList At the last time enter into this function \r
+            del self._DynamicPcdList[:]                        \r
         self._DynamicPcdList.extend(UnicodePcdArray)\r
         self._DynamicPcdList.extend(HiiPcdArray)\r
         self._DynamicPcdList.extend(OtherPcdArray)\r
@@ -562,7 +1036,7 @@ class PlatformAutoGen(AutoGen):
                 if "FLAGS" in self.ToolDefinition["MAKE"]:\r
                     NewOption = self.ToolDefinition["MAKE"]["FLAGS"].strip()\r
                     if NewOption != '':\r
-                      self._BuildCommand += SplitOption(NewOption)\r
+                        self._BuildCommand += SplitOption(NewOption)\r
         return self._BuildCommand\r
 \r
     ## Get tool chain definition\r
@@ -709,10 +1183,14 @@ class PlatformAutoGen(AutoGen):
 \r
     ## Get list of non-dynamic PCDs\r
     def _GetNonDynamicPcdList(self):\r
+        if self._NonDynamicPcdList == None:\r
+            self.CollectPlatformDynamicPcds()\r
         return self._NonDynamicPcdList\r
 \r
     ## Get list of dynamic PCDs\r
     def _GetDynamicPcdList(self):\r
+        if self._DynamicPcdList == None:\r
+            self.CollectPlatformDynamicPcds()\r
         return self._DynamicPcdList\r
 \r
     ## Generate Token Number for all PCD\r
@@ -792,16 +1270,21 @@ class PlatformAutoGen(AutoGen):
         PlatformModule = self.Platform.Modules[str(Module)]\r
 \r
         # add forced library instances (specified under LibraryClasses sections)\r
-        for LibraryClass in self.Platform.LibraryClasses.GetKeys():\r
-            if LibraryClass.startswith("NULL"):\r
-                Module.LibraryClasses[LibraryClass] = self.Platform.LibraryClasses[LibraryClass]\r
+        #\r
+        # If a module has a MODULE_TYPE of USER_DEFINED,\r
+        # do not link in NULL library class instances from the global [LibraryClasses.*] sections.\r
+        #\r
+        if Module.ModuleType != SUP_MODULE_USER_DEFINED:\r
+            for LibraryClass in self.Platform.LibraryClasses.GetKeys():\r
+                if LibraryClass.startswith("NULL") and self.Platform.LibraryClasses[LibraryClass, Module.ModuleType]:\r
+                    Module.LibraryClasses[LibraryClass] = self.Platform.LibraryClasses[LibraryClass, Module.ModuleType]\r
 \r
         # add forced library instances (specified in module overrides)\r
         for LibraryClass in PlatformModule.LibraryClasses:\r
             if LibraryClass.startswith("NULL"):\r
                 Module.LibraryClasses[LibraryClass] = PlatformModule.LibraryClasses[LibraryClass]\r
 \r
-        # R9 module\r
+        # EdkII module\r
         LibraryConsumerList = [Module]\r
         Constructor         = []\r
         ConsumedByList      = sdict()\r
@@ -952,6 +1435,10 @@ class PlatformAutoGen(AutoGen):
         if FromPcd != None:\r
             if ToPcd.Pending and FromPcd.Type not in [None, '']:\r
                 ToPcd.Type = FromPcd.Type\r
+            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
             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
@@ -1046,7 +1533,7 @@ class PlatformAutoGen(AutoGen):
 \r
     ## Resolve library names to library modules\r
     #\r
-    # (for R8.x modules)\r
+    # (for Edk.x modules)\r
     #\r
     #   @param  Module  The module from which the library names will be resolved\r
     #\r
@@ -1057,7 +1544,7 @@ class PlatformAutoGen(AutoGen):
         EdkLogger.verbose("Library instances of module [%s] [%s]:" % (str(Module), self.Arch))\r
         LibraryConsumerList = [Module]\r
 \r
-        # "CompilerStub" is a must for R8 modules\r
+        # "CompilerStub" is a must for Edk modules\r
         if Module.Libraries:\r
             Module.Libraries.append("CompilerStub")\r
         LibraryList = []\r
@@ -1081,16 +1568,86 @@ class PlatformAutoGen(AutoGen):
                     EdkLogger.verbose("\t" + LibraryName + " : " + str(Library) + ' ' + str(type(Library)))\r
         return LibraryList\r
 \r
+    ## Calculate the priority value of the build option\r
+    #\r
+    # @param    Key    Build option definition contain: TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE\r
+    #\r
+    # @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
+        if Target == "*":\r
+            PriorityValue &= 0x01111\r
+        if ToolChain == "*":\r
+            PriorityValue &= 0x10111\r
+        if Arch == "*":\r
+            PriorityValue &= 0x11011\r
+        if CommandType == "*":\r
+            PriorityValue &= 0x11101\r
+        if Attr == "*":\r
+            PriorityValue &= 0x11110\r
+        \r
+        return self.PrioList["0x%0.5x"%PriorityValue]\r
+                                    \r
+\r
     ## Expand * in build option key\r
     #\r
     #   @param  Options     Options to be expanded\r
     #\r
     #   @retval options     Options expanded\r
-    #\r
+    #      \r
     def _ExpandBuildOption(self, Options, ModuleStyle=None):\r
         BuildOptions = {}\r
         FamilyMatch  = False\r
         FamilyIsNull = True\r
+                \r
+        OverrideList = {}\r
+        #\r
+        # Construct a list contain the build options which need override.\r
+        #\r
+        for Key in Options:\r
+            #\r
+            # Key[0] -- tool family\r
+            # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE\r
+            #\r
+            if Key[0] == self.BuildRuleFamily :\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
+                                    OverrideList.pop(Key[1])\r
+                                OverrideList[Key[1]] = Options[Key]\r
+        \r
+        #\r
+        # Use the highest priority value. \r
+        #\r
+        if (len(OverrideList) >= 2):\r
+            KeyList   = OverrideList.keys()\r
+            for Index in range(len(KeyList)):\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
+                    #\r
+                    # Compare two Key, if one is included by another, choose the higher priority one\r
+                    #                    \r
+                    Target2, ToolChain2, Arch2, CommandType2, Attr2 = NextKey.split("_")\r
+                    if Target1 == Target2 or Target1 == "*" or Target2 == "*":\r
+                        if ToolChain1 == ToolChain2 or ToolChain1 == "*" or ToolChain2 == "*":\r
+                            if Arch1 == Arch2 or Arch1 == "*" or Arch2 == "*":\r
+                                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
+                                                Options.pop((self.BuildRuleFamily, NextKey))\r
+                                        else:\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
@@ -1278,6 +1835,8 @@ class ModuleAutoGen(AutoGen):
 \r
         self.IsMakeFileCreated = False\r
         self.IsCodeFileCreated = False\r
+        self.IsAsBuiltInfCreated = False\r
+        self.DepexGenerated = False\r
 \r
         self.BuildDatabase = self.Workspace.BuildDatabase\r
 \r
@@ -1317,6 +1876,7 @@ class ModuleAutoGen(AutoGen):
         self._DepexList               = None\r
         self._DepexExpressionList     = None\r
         self._BuildOption             = None\r
+        self._BuildOptionIncPathList  = None\r
         self._BuildTargets            = None\r
         self._IntroBuildTargetList    = None\r
         self._FinalBuildTargetList    = None\r
@@ -1367,6 +1927,10 @@ class ModuleAutoGen(AutoGen):
     def _GetBaseName(self):\r
         return self.Module.BaseName\r
 \r
+    ## Return the module DxsFile if exist\r
+    def _GetDxsFile(self):\r
+        return self.Module.DxsFile\r
+\r
     ## Return the module SourceOverridePath\r
     def _GetSourceOverridePath(self):\r
         return self.Module.SourceOverridePath\r
@@ -1383,7 +1947,7 @@ class ModuleAutoGen(AutoGen):
     def _GetModuleType(self):\r
         return self.Module.ModuleType\r
 \r
-    ## Return the component type (for R8.x style of module)\r
+    ## Return the component type (for Edk.x style of module)\r
     def _GetComponentType(self):\r
         return self.Module.ComponentType\r
 \r
@@ -1486,7 +2050,7 @@ class ModuleAutoGen(AutoGen):
     def _GetDepexTokenList(self):\r
         if self._DepexList == None:\r
             self._DepexList = {}\r
-            if self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
+            if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
                 return self._DepexList\r
 \r
             self._DepexList[self.ModuleType] = []\r
@@ -1522,7 +2086,7 @@ class ModuleAutoGen(AutoGen):
     def _GetDepexExpressionTokenList(self):\r
         if self._DepexExpressionList == None:\r
             self._DepexExpressionList = {}\r
-            if self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
+            if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
                 return self._DepexExpressionList\r
 \r
             self._DepexExpressionList[self.ModuleType] = ''\r
@@ -1568,6 +2132,50 @@ class ModuleAutoGen(AutoGen):
             self._BuildOption = self.PlatformInfo.ApplyBuildOption(self.Module)\r
         return self._BuildOption\r
 \r
+    ## Get include path list from tool option for the module build\r
+    #\r
+    #   @retval     list            The include path list\r
+    #\r
+    def _GetBuildOptionIncPathList(self):\r
+        if self._BuildOptionIncPathList == None:\r
+            #\r
+            # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC\r
+            # 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
+            elif self.PlatformInfo.ToolChainFamily in ('INTEL', 'GCC'):\r
+                gBuildOptIncludePattern = re.compile(r"(?:.*?)-I[ \t]*([^ ]*)", re.MULTILINE|re.DOTALL)\r
+            \r
+            BuildOptionIncPathList = []\r
+            for Tool in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):\r
+                Attr = 'FLAGS'\r
+                try:\r
+                    FlagOption = self.BuildOption[Tool][Attr]\r
+                except KeyError:\r
+                    FlagOption = ''\r
+                \r
+                IncPathList = [NormPath(Path, self.Macros) for Path in gBuildOptIncludePattern.findall(FlagOption)]\r
+                #\r
+                # EDK II modules must not reference header files outside of the packages they depend on or \r
+                # within the module's directory tree. Report error if violation.\r
+                #\r
+                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
+                                            PARAMETER_INVALID,\r
+                                            ExtraData = ErrMsg, \r
+                                            File = str(self.MetaFile))\r
+\r
+                \r
+                BuildOptionIncPathList += IncPathList\r
+            \r
+            self._BuildOptionIncPathList = BuildOptionIncPathList\r
+        \r
+        return self._BuildOptionIncPathList\r
+        \r
     ## 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
@@ -1578,12 +2186,12 @@ class ModuleAutoGen(AutoGen):
             self._SourceFileList = []\r
             for F in self.Module.Sources:\r
                 # match tool chain\r
-                if F.TagName != "" and F.TagName != self.ToolChain:\r
+                if F.TagName not in ("", "*", self.ToolChain):\r
                     EdkLogger.debug(EdkLogger.DEBUG_9, "The toolchain [%s] for processing file [%s] is found, "\r
                                     "but [%s] is needed" % (F.TagName, str(F), self.ToolChain))\r
                     continue\r
                 # match tool chain family\r
-                if F.ToolChainFamily != "" and F.ToolChainFamily != self.ToolChainFamily:\r
+                if F.ToolChainFamily not in ("", "*", self.ToolChainFamily):\r
                     EdkLogger.debug(\r
                                 EdkLogger.DEBUG_0,\r
                                 "The file [%s] must be built by tools of [%s], " \\r
@@ -1669,6 +2277,9 @@ class ModuleAutoGen(AutoGen):
                 CreateDirectory(Source.Dir)\r
 \r
             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
                 RuleObject = self.BuildRules[TAB_DEFAULT_BINARY_FILE]\r
             elif FileType in self.BuildRules:\r
                 RuleObject = self.BuildRules[FileType]\r
@@ -1723,7 +2334,7 @@ class ModuleAutoGen(AutoGen):
             self._BuildTargets = {}\r
             self._FileTypes = {}\r
 \r
-        #TRICK: call _GetSourceFileList to apply build rule for binary files\r
+        #TRICK: call _GetSourceFileList to apply build rule for source files\r
         if self.SourceFileList:\r
             pass\r
 \r
@@ -1758,9 +2369,8 @@ class ModuleAutoGen(AutoGen):
     #\r
     def _GetAutoGenFileList(self):\r
         UniStringAutoGenC = True\r
-        UniStringBinBuffer = None\r
+        UniStringBinBuffer = StringIO()\r
         if self.BuildType == 'UEFI_HII':\r
-            UniStringBinBuffer = StringIO()\r
             UniStringAutoGenC = False\r
         if self._AutoGenFileList == None:\r
             self._AutoGenFileList = {}\r
@@ -1818,7 +2428,7 @@ class ModuleAutoGen(AutoGen):
     #\r
     def _GetLibraryPcdList(self):\r
         if self._LibraryPcdList == None:\r
-            Pcds = {}\r
+            Pcds = sdict()\r
             if not self.IsLibrary:\r
                 # get PCDs from dependent libraries\r
                 for Library in self.DependentLibraryList:\r
@@ -1877,11 +2487,11 @@ class ModuleAutoGen(AutoGen):
                 for Inc in self.Module.Includes:\r
                     if Inc not in self._IncludePathList:\r
                         self._IncludePathList.append(Inc)\r
-                    # for r8 modules\r
+                    # for Edk modules\r
                     Inc = path.join(Inc, self.Arch.capitalize())\r
                     if os.path.exists(Inc) and Inc not in self._IncludePathList:\r
                         self._IncludePathList.append(Inc)\r
-                # r8 module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time\r
+                # Edk module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time\r
                 self._IncludePathList.append(self.DebugDir)\r
             else:\r
                 self._IncludePathList.append(self.MetaFile.Dir)\r
@@ -1896,6 +2506,107 @@ class ModuleAutoGen(AutoGen):
                         self._IncludePathList.append(str(Inc))\r
         return self._IncludePathList\r
 \r
+    ## Create AsBuilt INF file the module\r
+    #\r
+    def CreateAsBuiltInf(self):\r
+        if self.IsAsBuiltInfCreated:\r
+            return\r
+            \r
+        # Skip the following code for EDK I inf\r
+        if self.AutoGenVersion < 0x00010005:\r
+            return\r
+            \r
+        # Skip the following code for libraries\r
+        if self.IsLibrary:\r
+            return\r
+            \r
+        # Skip the following code for modules with no source files\r
+        if self.SourceFileList == None or self.SourceFileList == []:\r
+            return\r
+\r
+        # Skip the following code for modules without any binary files\r
+        if self.BinaryFileList <> None and self.BinaryFileList <> []:\r
+            return\r
+            \r
+        ### TODO: How to handles mixed source and binary modules\r
+\r
+        # Find all DynamicEx PCDs used by this module and dependent libraries\r
+        # Also find all packages that the DynamicEx PCDs depend on\r
+        Pcds = []\r
+        Packages = []        \r
+        for Pcd in self.ModulePcdList + self.LibraryPcdList:\r
+          if Pcd.Type in GenC.gDynamicExPcd:\r
+            if Pcd not in Pcds:\r
+              Pcds += [Pcd]\r
+            for Package in self.DerivedPackageList:\r
+              if Package not in Packages:\r
+                if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, 'DynamicEx') in Package.Pcds:\r
+                  Packages += [Package]\r
+                elif (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, 'Dynamic') in Package.Pcds:\r
+                  Packages += [Package]\r
+\r
+        ModuleType = self.ModuleType\r
+        if ModuleType == 'UEFI_DRIVER' and self.DepexGenerated:\r
+          ModuleType = 'DXE_DRIVER'\r
+\r
+        AsBuiltInfDict = {\r
+          'module_name'                       : self.Name,\r
+          'module_guid'                       : self.Guid,\r
+          'module_module_type'                : ModuleType,\r
+          'module_version_string'             : self.Version,\r
+          'module_uefi_specification_version' : [],\r
+          'module_pi_specification_version'   : [],\r
+          'module_arch'                       : self.Arch,\r
+          'package_item'                      : ['%s' % (Package.MetaFile.File.replace('\\','/')) for Package in Packages],\r
+          'binary_item'                       : [],\r
+          'pcd_item'                          : [],\r
+          'flags_item'                        : []\r
+        }\r
+\r
+        if 'UEFI_SPECIFICATION_VERSION' in self.Specification:\r
+          AsBuiltInfDict['module_uefi_specification_version'] += [self.Specification['UEFI_SPECIFICATION_VERSION']]\r
+        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
+        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
+              AsBuiltInfDict['binary_item'] += ['ASL|' + File]\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
+              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
+              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
+        for Pcd in Pcds:\r
+          AsBuiltInfDict['pcd_item'] += [Pcd.TokenSpaceGuidCName + '.' + Pcd.TokenCName]\r
+         \r
+        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
+        AsBuiltInf = TemplateString()\r
+        AsBuiltInf.Append(gAsBuiltInfHeaderString.Replace(AsBuiltInfDict))\r
+        \r
+        SaveFileOnChange(os.path.join(self.OutputDir, self.Name + '.inf'), str(AsBuiltInf), False)\r
+        \r
+        self.IsAsBuiltInfCreated = True\r
+        \r
     ## Create makefile for the module and its dependent libraries\r
     #\r
     #   @param      CreateLibraryMakeFile   Flag indicating if or not the makefiles of\r
@@ -1940,7 +2651,7 @@ class ModuleAutoGen(AutoGen):
 \r
         for File in self.AutoGenFileList:\r
             if GenC.Generate(File.Path, self.AutoGenFileList[File], File.IsBinary):\r
-                #Ignore R8 AutoGen.c\r
+                #Ignore Edk AutoGen.c\r
                 if self.AutoGenVersion < 0x00010005 and File.Name == 'AutoGen.c':\r
                         continue\r
 \r
@@ -1960,6 +2671,9 @@ class ModuleAutoGen(AutoGen):
             Dpx = GenDepex.DependencyExpression(self.DepexList[ModuleType], ModuleType, True)\r
             DpxFile = gAutoGenDepexFileName % {"module_name" : self.Name}\r
 \r
+            if len(Dpx.PostfixNotation) <> 0:\r
+              self.DepexGenerated = True\r
+\r
             if Dpx.Generate(path.join(self.OutputDir, DpxFile)):\r
                 AutoGenList.append(str(DpxFile))\r
             else:\r
@@ -1997,14 +2711,6 @@ class ModuleAutoGen(AutoGen):
                         self._ApplyBuildRule(Lib.Target, TAB_UNKNOWN_FILE)\r
         return self._LibraryAutoGenList\r
 \r
-    ## Return build command string\r
-    #\r
-    #   @retval     string  Build command string\r
-    #\r
-    def _GetBuildCommand(self):\r
-        return self.PlatformInfo.BuildCommand\r
-\r
-\r
     Module          = property(_GetModule)\r
     Name            = property(_GetBaseName)\r
     Guid            = property(_GetGuid)\r
@@ -2047,8 +2753,10 @@ class ModuleAutoGen(AutoGen):
     ProtocolList            = property(_GetProtocolList)\r
     PpiList                 = property(_GetPpiList)\r
     DepexList               = property(_GetDepexTokenList)\r
+    DxsFile                 = property(_GetDxsFile)\r
     DepexExpressionList     = property(_GetDepexExpressionTokenList)\r
     BuildOption             = property(_GetModuleBuildOption)\r
+    BuildOptionIncPathList  = property(_GetBuildOptionIncPathList)\r
     BuildCommand            = property(_GetBuildCommand)\r
 \r
 # This acts like the main() function for the script, unless it is 'import'ed into another script.\r