]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/AutoGen/AutoGen.py
Add IMAGE_ATTRIBUTE_UEFI_IMAGE definition from UEFI 2.4 specification.
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / AutoGen.py
index 4755e31e965af1a0f6836cf9e3ba15a7e84d83a3..8c62ac8e72a80e5ba79272a837908b5eabbe7cbf 100644 (file)
@@ -1,8 +1,8 @@
 ## @file\r
 # Generate AutoGen.h, AutoGen.c and *.depex files\r
 #\r
-# Copyright (c) 2007 - 2010, Intel Corporation\r
-# All rights reserved. This program and the accompanying materials\r
+# Copyright (c) 2007 - 2014, 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
 # http://opensource.org/licenses/bsd-license.php\r
@@ -13,7 +13,7 @@
 \r
 ## Import Modules\r
 #\r
-import os\r
+import Common.LongFilePathOs as os\r
 import re\r
 import os.path as path\r
 import copy\r
@@ -26,6 +26,7 @@ from StringIO import StringIO
 from StrGather import *\r
 from BuildEngine import BuildRule\r
 \r
+from Common.LongFilePathSupport import CopyLongFilePath\r
 from Common.BuildToolError import *\r
 from Common.DataType import *\r
 from Common.Misc import *\r
@@ -34,8 +35,12 @@ import Common.GlobalData as GlobalData
 from GenFds.FdfParser import *\r
 from CommonDataClass.CommonClass import SkuInfoClass\r
 from Workspace.BuildClassObject import *\r
+from GenPatchPcdTable.GenPatchPcdTable import parsePcdInfoFromMapFile\r
+import Common.VpdInfoFile as VpdInfoFile\r
+from GenPcdDb import CreatePcdDatabaseCode\r
+from Workspace.MetaFileCommentParser import UsageList\r
 \r
-## Regular expression for splitting Dependency Expression stirng into tokens\r
+## Regular expression for splitting Dependency Expression string into tokens\r
 gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)")\r
 \r
 ## Mapping Makefile type\r
@@ -45,6 +50,9 @@ gMakeTypeMap = {"MSFT":"nmake", "GCC":"gmake"}
 ## Build rule configuration file\r
 gBuildRuleFile = 'Conf/build_rule.txt'\r
 \r
+## Build rule default version\r
+AutoGenReqBuildRuleVerNum = "0.1"\r
+\r
 ## default file name for AutoGen\r
 gAutoGenCodeFileName = "AutoGen.c"\r
 gAutoGenHeaderFileName = "AutoGen.h"\r
@@ -52,6 +60,47 @@ 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("""${header_comments}\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
+  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
+  ${package_item}${END}\r
+\r
+[Binaries.${module_arch}]${BEGIN}\r
+  ${binary_item}${END}\r
+\r
+[PatchPcd.${module_arch}]${BEGIN}\r
+  ${patchablepcd_item}\r
+${END}\r
+[Protocols.${module_arch}]${BEGIN}\r
+  ${protocol_item}\r
+${END}\r
+[Ppis.${module_arch}]${BEGIN}\r
+  ${ppi_item}\r
+${END}\r
+[Guids.${module_arch}]${BEGIN}\r
+  ${guid_item}\r
+${END}\r
+[PcdEx.${module_arch}]${BEGIN}\r
+  ${pcd_item}\r
+${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 +170,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,55 +184,181 @@ 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=''):\r
-        self.MetaFile       = ActivePlatform.MetaFile\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
+        if Fvs is None:\r
+            Fvs = []\r
+        if Caps is None:\r
+            Caps = []\r
+        self.BuildDatabase  = MetaFileDb\r
+        self.MetaFile       = ActivePlatform\r
         self.WorkspaceDir   = WorkspaceDir\r
-        self.Platform       = ActivePlatform\r
+        self.Platform       = self.BuildDatabase[self.MetaFile, 'COMMON', Target, Toolchain]\r
+        GlobalData.gActivePlatform = self.Platform\r
         self.BuildTarget    = Target\r
         self.ToolChain      = Toolchain\r
         self.ArchList       = ArchList\r
         self.SkuId          = SkuId\r
+        self.UniFlag        = UniFlag\r
 \r
-        self.BuildDatabase  = MetaFileDb\r
         self.TargetTxt      = BuildConfig\r
         self.ToolDef        = ToolDefinition\r
         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
         os.chdir(self.WorkspaceDir)\r
 \r
+        #\r
+        # Merge Arch\r
+        #\r
+        if not self.ArchList:\r
+            ArchList = set(self.Platform.SupArchList)\r
+        else:\r
+            ArchList = set(self.ArchList) & set(self.Platform.SupArchList)\r
+        if not ArchList:\r
+            EdkLogger.error("build", PARAMETER_INVALID,\r
+                            ExtraData = "Invalid ARCH specified. [Valid ARCH: %s]" % (" ".join(self.Platform.SupArchList)))\r
+        elif self.ArchList and len(ArchList) != len(self.ArchList):\r
+            SkippedArchList = set(self.ArchList).symmetric_difference(set(self.Platform.SupArchList))\r
+            EdkLogger.verbose("\nArch [%s] is ignored because the platform supports [%s] only!"\r
+                              % (" ".join(SkippedArchList), " ".join(self.Platform.SupArchList)))\r
+        self.ArchList = tuple(ArchList)\r
+\r
+        # Validate build target\r
+        if self.BuildTarget not in self.Platform.BuildTargets:\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
         # parse FDF file to get PCDs in it, if any\r
-        if self.FdfFile != None and self.FdfFile != '':\r
+        if not self.FdfFile:\r
+            self.FdfFile = self.Platform.FlashDefinition\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('\n%-24s = %s' % ("Active Platform", self.Platform))\r
+        if BuildModule:\r
+            EdkLogger.info('%-24s = %s' % ("Active Module", BuildModule))\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
+        if Progress:\r
+            Progress.Start("\nProcessing meta-data")\r
+        \r
+        if self.FdfFile:\r
+            #\r
+            # Mark now build in AutoGen Phase\r
+            #\r
+            GlobalData.gAutoGenPhase = True    \r
             Fdf = FdfParser(self.FdfFile.Path)\r
             Fdf.ParseFile()\r
+            GlobalData.gFdfParser = Fdf\r
+            GlobalData.gAutoGenPhase = False\r
             PcdSet = Fdf.Profile.PcdDict\r
             ModuleList = Fdf.Profile.InfList\r
             self.FdfProfile = Fdf.Profile\r
+            for fvname in self.FvTargetList:\r
+                if fvname.upper() not in self.FdfProfile.FvDict:\r
+                    EdkLogger.error("build", OPTION_VALUE_INVALID,\r
+                                    "No such an FV in FDF file: %s" % fvname)\r
         else:\r
             PcdSet = {}\r
             ModuleList = []\r
             self.FdfProfile = None\r
+            if self.FdTargetList:\r
+                EdkLogger.info("No flash definition file found. FD [%s] will be ignored." % " ".join(self.FdTargetList))\r
+                self.FdTargetList = []\r
+            if self.FvTargetList:\r
+                EdkLogger.info("No flash definition file found. FV [%s] will be ignored." % " ".join(self.FvTargetList))\r
+                self.FvTargetList = []\r
+            if self.CapTargetList:\r
+                EdkLogger.info("No flash definition file found. Capsule [%s] will be ignored." % " ".join(self.CapTargetList))\r
+                self.CapTargetList = []\r
         \r
         # apply SKU and inject PCDs from Flash Definition file\r
         for Arch in self.ArchList:\r
-            Platform = self.BuildDatabase[self.MetaFile, Arch]\r
+            Platform = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]\r
+\r
+            DecPcds = {}\r
+            DecPcdsKey = set()\r
+            PGen = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)\r
+            PkgSet = set()\r
+            for Inf in ModuleList:\r
+                ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch)\r
+                if ModuleFile in Platform.Modules:\r
+                    continue\r
+                ModuleData = self.BuildDatabase[ModuleFile, Arch, Target, Toolchain]\r
+                PkgSet.update(ModuleData.Packages)\r
+            Pkgs = list(PkgSet) + list(PGen.PackageList)\r
+            for Pkg in Pkgs:\r
+                for Pcd in Pkg.Pcds:\r
+                    DecPcds[Pcd[0], Pcd[1]] = Pkg.Pcds[Pcd]\r
+                    DecPcdsKey.add((Pcd[0], Pcd[1], Pcd[2]))\r
+\r
             Platform.SkuName = self.SkuId\r
             for Name, Guid in PcdSet:\r
-                Platform.AddPcd(Name, Guid, PcdSet[Name, Guid])\r
+                if (Name, Guid) not in DecPcds:\r
+                    EdkLogger.error(\r
+                        'build',\r
+                        PARSER_ERROR,\r
+                        "PCD (%s.%s) used in FDF is not declared in DEC files." % (Guid, Name),\r
+                        File = self.FdfProfile.PcdFileLineDict[Name, Guid][0],\r
+                        Line = self.FdfProfile.PcdFileLineDict[Name, Guid][1]\r
+                    )\r
+                else:\r
+                    # Check whether Dynamic or DynamicEx PCD used in FDF file. If used, build break and give a error message.\r
+                    if (Name, Guid, TAB_PCDS_FIXED_AT_BUILD) in DecPcdsKey \\r
+                        or (Name, Guid, TAB_PCDS_PATCHABLE_IN_MODULE) in DecPcdsKey \\r
+                        or (Name, Guid, TAB_PCDS_FEATURE_FLAG) in DecPcdsKey:\r
+                        Platform.AddPcd(Name, Guid, PcdSet[Name, Guid])\r
+                        continue\r
+                    elif (Name, Guid, TAB_PCDS_DYNAMIC) in DecPcdsKey or (Name, Guid, TAB_PCDS_DYNAMIC_EX) in DecPcdsKey:\r
+                        EdkLogger.error(\r
+                                'build',\r
+                                PARSER_ERROR,\r
+                                "Using Dynamic or DynamicEx type of PCD [%s.%s] in FDF file is not allowed." % (Guid, Name),\r
+                                File = self.FdfProfile.PcdFileLineDict[Name, Guid][0],\r
+                                Line = self.FdfProfile.PcdFileLineDict[Name, Guid][1]\r
+                        )\r
 \r
             Pa = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)\r
             #\r
             # Explicitly collect platform's dynamic PCDs\r
             #\r
             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
+        # 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
@@ -191,6 +366,183 @@ 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
+                        if InfFoundFlag:\r
+                            break\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
+                                    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[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
@@ -242,22 +594,84 @@ 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
+    def _GenFdsCommand(self):\r
+        return (GenMake.TopLevelMakefile(self)._TEMPLATE_.Replace(GenMake.TopLevelMakefile(self)._TemplateDict)).strip()\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
     #\r
     def CreateMakeFile(self, CreateDepsMakeFile=False):\r
-        # create makefile for platform\r
-        Makefile = GenMake.TopLevelMakefile(self)\r
-        if Makefile.Generate():\r
-            EdkLogger.debug(EdkLogger.DEBUG_9, "Generated makefile for platform [%s] %s\n" %\r
-                            (self.MetaFile, self.ArchList))\r
-        else:\r
-            EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of makefile for platform [%s] %s\n" %\r
-                            (self.MetaFile, self.ArchList))\r
-\r
         if CreateDepsMakeFile:\r
             for Pa in self.AutoGenObjectList:\r
                 Pa.CreateMakeFile(CreateDepsMakeFile)\r
@@ -276,6 +690,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
@@ -287,6 +706,7 @@ class WorkspaceAutoGen(AutoGen):
     FvDir               = property(_GetFvDir)\r
     MakeFileDir         = property(_GetMakeFileDir)\r
     BuildCommand        = property(_GetBuildCommand)\r
+    GenFdsCommand       = property(_GenFdsCommand)\r
 \r
 ## AutoGen class for platform\r
 #\r
@@ -300,7 +720,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
@@ -328,6 +768,8 @@ class PlatformAutoGen(AutoGen):
         self.FdTargetList = self.Workspace.FdTargetList\r
         self.FvTargetList = self.Workspace.FvTargetList\r
         self.AllPcdList = []\r
+        # get the original module/package/platform objects\r
+        self.BuildDatabase = Workspace.BuildDatabase\r
 \r
         # flag indicating if the makefile/C-code file has been created or not\r
         self.IsMakeFileCreated  = False\r
@@ -349,6 +791,7 @@ class PlatformAutoGen(AutoGen):
         self._PcdTokenNumber = None    # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber\r
         self._DynamicPcdList = None    # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]\r
         self._NonDynamicPcdList = None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]\r
+        self._NonDynamicPcdDict = {}\r
 \r
         self._ToolDefinitions = None\r
         self._ToolDefFile = None          # toolcode : tool path\r
@@ -361,9 +804,22 @@ class PlatformAutoGen(AutoGen):
         self._ModuleAutoGenList  = None\r
         self._LibraryAutoGenList = None\r
         self._BuildCommand = None\r
-\r
+        self._AsBuildInfList = []\r
+        self._AsBuildModuleList = []\r
+        if GlobalData.gFdfParser != None:\r
+            self._AsBuildInfList = GlobalData.gFdfParser.Profile.InfList\r
+            for Inf in self._AsBuildInfList:\r
+                InfClass = PathClass(NormPath(Inf), GlobalData.gWorkspace, self.Arch)\r
+                M = self.BuildDatabase[InfClass, self.Arch, self.BuildTarget, self.ToolChain]\r
+                if not M.IsSupportedArch:\r
+                    continue\r
+                self._AsBuildModuleList.append(InfClass)\r
+        # get library/modules for build\r
+        self.LibraryBuildDirectoryList = []\r
+        self.ModuleBuildDirectoryList = []\r
         # get the original module/package/platform objects\r
-        self.BuildDatabase = Workspace.BuildDatabase\r
+        self.LibraryBuildDirectoryList = []\r
+        self.ModuleBuildDirectoryList = []\r
         return True\r
 \r
     def __repr__(self):\r
@@ -388,6 +844,10 @@ class PlatformAutoGen(AutoGen):
         # don't do this twice\r
         self.IsCodeFileCreated = True\r
 \r
+    ## Generate Fds Command\r
+    def _GenFdsCommand(self):\r
+        return self.Workspace.GenFdsCommand\r
+               \r
     ## Create makefile for the platform and mdoules in it\r
     #\r
     #   @param      CreateModuleMakeFile    Flag indicating if the makefile for\r
@@ -399,21 +859,45 @@ 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
             return\r
 \r
-        # create makefile for platform\r
+        # create library/module build dirs for platform\r
         Makefile = GenMake.PlatformMakefile(self)\r
-        if Makefile.Generate():\r
-            EdkLogger.debug(EdkLogger.DEBUG_9, "Generated makefile for platform [%s] [%s]\n" %\r
-                            (self.MetaFile, self.Arch))\r
-        else:\r
-            EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of makefile for platform [%s] [%s]\n" %\r
-                            (self.MetaFile, self.Arch))\r
+        self.LibraryBuildDirectoryList = Makefile.GetLibraryBuildDirectoryList()\r
+        self.ModuleBuildDirectoryList = Makefile.GetModuleBuildDirectoryList()\r
+\r
         self.IsMakeFileCreated = True\r
 \r
+    ## Deal with Shared FixedAtBuild Pcds\r
+    #\r
+    def CollectFixedAtBuildPcds(self):\r
+        for LibAuto in self.LibraryAutoGenList:\r
+            FixedAtBuildPcds = {}  \r
+            ShareFixedAtBuildPcdsSameValue = {} \r
+            for Module in LibAuto._ReferenceModules:                \r
+                for Pcd in Module.FixedAtBuildPcds + LibAuto.FixedAtBuildPcds:\r
+                    key = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))  \r
+                    if key not in FixedAtBuildPcds:\r
+                        ShareFixedAtBuildPcdsSameValue[key] = True\r
+                        FixedAtBuildPcds[key] = Pcd.DefaultValue\r
+                    else:\r
+                        if FixedAtBuildPcds[key] != Pcd.DefaultValue:\r
+                            ShareFixedAtBuildPcdsSameValue[key] = False      \r
+            for Pcd in LibAuto.FixedAtBuildPcds:\r
+                key = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))\r
+                if (Pcd.TokenCName,Pcd.TokenSpaceGuidCName) not in self.NonDynamicPcdDict:\r
+                    continue\r
+                else:\r
+                    DscPcd = self.NonDynamicPcdDict[(Pcd.TokenCName,Pcd.TokenSpaceGuidCName)]\r
+                    if DscPcd.Type != "FixedAtBuild":\r
+                        continue\r
+                if key in ShareFixedAtBuildPcdsSameValue and ShareFixedAtBuildPcdsSameValue[key]:                    \r
+                    LibAuto.ConstPcd[key] = Pcd.DefaultValue\r
+\r
     ## Collect dynamic PCDs\r
     #\r
     #  Gather dynamic PCDs list from each module and their settings from platform\r
@@ -422,8 +906,12 @@ class PlatformAutoGen(AutoGen):
     def CollectPlatformDynamicPcds(self):\r
         # for gathering error information\r
         NoDatumTypePcdList = set()\r
-\r
+        PcdNotInDb = []\r
         self._GuidValue = {}\r
+        FdfModuleList = []\r
+        for InfName in self._AsBuildInfList:\r
+            InfName = os.path.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
@@ -432,10 +920,45 @@ class PlatformAutoGen(AutoGen):
             \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 == None:\r
+                if PcdFromModule.DatumType == "VOID*" and PcdFromModule.MaxDatumSize in [None, '']:\r
                     NoDatumTypePcdList.add("%s.%s [%s]" % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, F))\r
 \r
+                if M.IsBinaryModule == True:\r
+                    PcdFromModule.IsFromBinaryInf = True\r
+                if (PcdFromModule.TokenCName, PcdFromModule.TokenSpaceGuidCName) in self.Platform.Pcds.keys():\r
+                    PcdFromModule.IsFromDsc = True\r
+                else:\r
+                    PcdFromModule.IsFromDsc = False\r
                 if PcdFromModule.Type in GenC.gDynamicPcd or PcdFromModule.Type in GenC.gDynamicExPcd:\r
+                    if F.Path not in FdfModuleList:\r
+                        # If one of the Source built modules listed in the DSC is not listed \r
+                        # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic \r
+                        # access method (it is only listed in the DEC file that declares the \r
+                        # PCD as PcdsDynamic), then build tool will report warning message\r
+                        # notify the PI that they are attempting to build a module that must \r
+                        # be included in a flash image in order to be functional. These Dynamic \r
+                        # PCD will not be added into the Database unless it is used by other \r
+                        # modules that are included in the FDF file.\r
+                        if PcdFromModule.Type in GenC.gDynamicPcd and \\r
+                            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
+                        # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx \r
+                        # access method (it is only listed in the DEC file that declares the \r
+                        # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the \r
+                        # PCD to the Platform's PCD Database.\r
+                        if PcdFromModule.Type in GenC.gDynamicExPcd:\r
+                            if PcdFromModule not in PcdNotInDb:\r
+                                PcdNotInDb.append(PcdFromModule)\r
+                            continue\r
                     #\r
                     # If a dynamic PCD used by a PEM module/PEI module & DXE module,\r
                     # it should be stored in Pcd PEI database, If a dynamic only\r
@@ -452,6 +975,68 @@ class PlatformAutoGen(AutoGen):
                         self._DynaPcdList_[Index] = PcdFromModule\r
                 elif PcdFromModule not in self._NonDynaPcdList_:\r
                     self._NonDynaPcdList_.append(PcdFromModule)\r
+                elif PcdFromModule in self._NonDynaPcdList_ and PcdFromModule.IsFromBinaryInf == True:\r
+                    Index = self._NonDynaPcdList_.index(PcdFromModule)\r
+                    if self._NonDynaPcdList_[Index].IsFromBinaryInf == False:\r
+                        #The PCD from Binary INF will override the same one from source INF\r
+                        self._NonDynaPcdList_.remove (self._NonDynaPcdList_[Index])\r
+                        PcdFromModule.Pending = False\r
+                        self._NonDynaPcdList_.append (PcdFromModule)\r
+        # Parse the DynamicEx PCD from the AsBuild INF module list of FDF.\r
+        DscModuleList = []\r
+        for ModuleInf in self.Platform.Modules.keys():\r
+            DscModuleList.append (os.path.normpath(ModuleInf.Path))\r
+        # add the PCD from modules that listed in FDF but not in DSC to Database \r
+        for InfName in FdfModuleList:\r
+            if InfName not in DscModuleList:\r
+                InfClass = PathClass(InfName)\r
+                M = self.BuildDatabase[InfClass, self.Arch, self.BuildTarget, self.ToolChain]\r
+                # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source) \r
+                # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here. \r
+                # For binary module, if in current arch, we need to list the PCDs into database.   \r
+                if not M.IsSupportedArch:\r
+                    continue\r
+                # Override the module PCD setting by platform setting\r
+                ModulePcdList = self.ApplyPcdSetting(M, M.Pcds)\r
+                for PcdFromModule in ModulePcdList:\r
+                    PcdFromModule.IsFromBinaryInf = True\r
+                    PcdFromModule.IsFromDsc = False\r
+                    # Only allow the DynamicEx and Patchable PCD in AsBuild INF\r
+                    if PcdFromModule.Type not in GenC.gDynamicExPcd and PcdFromModule.Type not in TAB_PCDS_PATCHABLE_IN_MODULE:\r
+                        EdkLogger.error("build", AUTOGEN_ERROR, "PCD setting error",\r
+                                        File=self.MetaFile,\r
+                                        ExtraData="\n\tExisted %s PCD %s in:\n\t\t%s\n"\r
+                                        % (PcdFromModule.Type, PcdFromModule.TokenCName, InfName))\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, InfName))\r
+                    if M.ModuleType in ["PEIM", "PEI_CORE"]:\r
+                        PcdFromModule.Phase = "PEI"\r
+                    if PcdFromModule not in self._DynaPcdList_ and PcdFromModule.Type in GenC.gDynamicExPcd:\r
+                        self._DynaPcdList_.append(PcdFromModule)\r
+                    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
+                        Index = self._DynaPcdList_.index(PcdFromModule)\r
+                        self._DynaPcdList_[Index].Phase = PcdFromModule.Phase\r
+                        self._DynaPcdList_[Index].Type = PcdFromModule.Type\r
+        for PcdFromModule in self._NonDynaPcdList_:\r
+            # If a PCD is not listed in the DSC file, but binary INF files used by \r
+            # this platform all (that use this PCD) list the PCD in a [PatchPcds] \r
+            # section, AND all source INF files used by this platform the build \r
+            # that use the PCD list the PCD in either a [Pcds] or [PatchPcds] \r
+            # section, then the tools must NOT add the PCD to the Platform's PCD\r
+            # Database; the build must assign the access method for this PCD as \r
+            # PcdsPatchableInModule.\r
+            if PcdFromModule not in self._DynaPcdList_:\r
+                continue\r
+            Index = self._DynaPcdList_.index(PcdFromModule)\r
+            if PcdFromModule.IsFromDsc == False and \\r
+                PcdFromModule.Type in TAB_PCDS_PATCHABLE_IN_MODULE and \\r
+                PcdFromModule.IsFromBinaryInf == True and \\r
+                self._DynaPcdList_[Index].IsFromBinaryInf == False:\r
+                Index = self._DynaPcdList_.index(PcdFromModule)\r
+                self._DynaPcdList_.remove (self._DynaPcdList_[Index])\r
 \r
         # print out error information and break the build, if error found\r
         if len(NoDatumTypePcdList) > 0:\r
@@ -462,8 +1047,19 @@ class PlatformAutoGen(AutoGen):
                                       % NoDatumTypePcdListString)\r
         self._NonDynamicPcdList = self._NonDynaPcdList_\r
         self._DynamicPcdList = self._DynaPcdList_\r
-        self.AllPcdList = self._NonDynamicPcdList + self._DynamicPcdList\r
-        \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
@@ -475,28 +1071,172 @@ 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] and \\r
+                   PcdKey in VpdPcdDict:\r
+                    Pcd = VpdPcdDict[PcdKey]\r
+                    for (SkuName,Sku) in Pcd.SkuInfoList.items():\r
+                        Sku.VpdOffset = Sku.VpdOffset.strip()\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
+                            for (SkuName,Sku) in DscPcdEntry.SkuInfoList.items():\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
+                                            DscPcdEntry.TokenValue = DecPcdEntry.TokenValue\r
+                                            DscPcdEntry.TokenSpaceGuidValue = eachDec.Guids[DecPcdEntry.TokenSpaceGuidCName]\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
+                                if DscPcdEntry not in self._DynamicPcdList:\r
+                                    self._DynamicPcdList.append(DscPcdEntry)\r
+#                                Sku = DscPcdEntry.SkuInfoList[DscPcdEntry.SkuInfoList.keys()[0]]\r
+                                Sku.VpdOffset = Sku.VpdOffset.strip()\r
+                                PcdValue = Sku.DefaultValue\r
+                                VpdFile.Add(DscPcdEntry, Sku.VpdOffset)\r
+                                if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":\r
+                                    NeedProcessVpdMapFile = True \r
+                            if DscPcdEntry.DatumType == 'VOID*' and PcdValue.startswith("L"):\r
+                                UnicodePcdArray.append(DscPcdEntry)\r
+                            elif len(Sku.VariableName) > 0:\r
+                                HiiPcdArray.append(DscPcdEntry)\r
+                            else:\r
+                                OtherPcdArray.append(DscPcdEntry)\r
+                                \r
+                                # if the offset of a VPD is *, then it need to be fixed up by third party tool.\r
+                                                       \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
+                DscTimeStamp = self.Platform.MetaFile.TimeStamp\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
+                            i = 0\r
+                            for (SkuName,Sku) in Pcd.SkuInfoList.items():                        \r
+                                if Sku.VpdOffset == "*":\r
+                                    Sku.VpdOffset = VpdFile.GetOffset(Pcd)[i].strip()\r
+                                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
+            # 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
-            \r
+        self.AllPcdList = self._NonDynamicPcdList + self._DynamicPcdList\r
         \r
     ## Return the platform build data object\r
     def _GetPlatform(self):\r
         if self._Platform == None:\r
-            self._Platform = self.BuildDatabase[self.MetaFile, self.Arch]\r
+            self._Platform = self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]\r
         return self._Platform\r
 \r
     ## Return platform name\r
@@ -561,7 +1301,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
@@ -693,6 +1433,15 @@ class PlatformAutoGen(AutoGen):
             if BuildRuleFile in [None, '']:\r
                 BuildRuleFile = gBuildRuleFile\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
+                                    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
         return self._BuildRule\r
 \r
     ## Summarize the packages used by modules in this platform\r
@@ -703,15 +1452,33 @@ class PlatformAutoGen(AutoGen):
                 self._PackageList.update(La.DependentPackageList)\r
             for Ma in self.ModuleAutoGenList:\r
                 self._PackageList.update(Ma.DependentPackageList)\r
-            self._PackageList = list(self._PackageList)\r
+            #Collect package set information from INF of FDF\r
+            PkgSet = set()\r
+            for ModuleFile in self._AsBuildModuleList:\r
+                if ModuleFile in self.Platform.Modules:\r
+                    continue\r
+                ModuleData = self.BuildDatabase[ModuleFile, self.Arch, self.BuildTarget, self.ToolChain]\r
+                PkgSet.update(ModuleData.Packages)\r
+            self._PackageList = list(self._PackageList) + list (PkgSet)\r
         return self._PackageList\r
 \r
+    def _GetNonDynamicPcdDict(self):\r
+        if self._NonDynamicPcdDict:\r
+            return self._NonDynamicPcdDict\r
+        for Pcd in self.NonDynamicPcdList:\r
+            self._NonDynamicPcdDict[(Pcd.TokenCName,Pcd.TokenSpaceGuidCName)] = Pcd\r
+        return self._NonDynamicPcdDict\r
+\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
@@ -719,18 +1486,43 @@ class PlatformAutoGen(AutoGen):
         if self._PcdTokenNumber == None:\r
             self._PcdTokenNumber = sdict()\r
             TokenNumber = 1\r
+            #\r
+            # Make the Dynamic and DynamicEx PCD use within different TokenNumber area. \r
+            # Such as:\r
+            # \r
+            # Dynamic PCD:\r
+            # TokenNumber 0 ~ 10\r
+            # DynamicEx PCD:\r
+            # TokeNumber 11 ~ 20\r
+            #\r
             for Pcd in self.DynamicPcdList:\r
                 if Pcd.Phase == "PEI":\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
+                    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
+            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
             for Pcd in self.DynamicPcdList:\r
                 if Pcd.Phase == "DXE":\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
+                    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
+            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
             for Pcd in self.NonDynamicPcdList:\r
                 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
                 TokenNumber += 1\r
@@ -754,6 +1546,8 @@ class PlatformAutoGen(AutoGen):
             for La in Ma.LibraryAutoGenList:\r
                 if La not in self._LibraryAutoGenList:\r
                     self._LibraryAutoGenList.append(La)\r
+                if Ma not in La._ReferenceModules:\r
+                    La._ReferenceModules.append(Ma)\r
 \r
     ## Summarize ModuleAutoGen objects of all modules to be built for this platform\r
     def _GetModuleAutoGenList(self):\r
@@ -773,7 +1567,8 @@ class PlatformAutoGen(AutoGen):
     #  by the platform or current configuration\r
     #\r
     def ValidModule(self, Module):\r
-        return Module in self.Platform.Modules or Module in self.Platform.LibraryInstances\r
+        return Module in self.Platform.Modules or Module in self.Platform.LibraryInstances \\r
+            or Module in self._AsBuildModuleList\r
 \r
     ## Resolve the library classes in a module to library instances\r
     #\r
@@ -791,16 +1586,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
@@ -825,7 +1625,7 @@ class PlatformAutoGen(AutoGen):
                                             File=self.MetaFile,\r
                                             ExtraData="in [%s] [%s]\n\tconsumed by module [%s]" % (str(M), self.Arch, str(Module)))\r
 \r
-                    LibraryModule = self.BuildDatabase[LibraryPath, self.Arch]\r
+                    LibraryModule = self.BuildDatabase[LibraryPath, self.Arch, self.BuildTarget, self.ToolChain]\r
                     # for those forced library instance (NULL library), add a fake library class\r
                     if LibraryClassName.startswith("NULL"):\r
                         LibraryModule.LibraryClass.append(LibraryClassObject(LibraryClassName, [ModuleType]))\r
@@ -951,6 +1751,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
@@ -983,13 +1787,13 @@ class PlatformAutoGen(AutoGen):
                             % (ToPcd.TokenSpaceGuidCName, ToPcd.TokenCName))\r
             Value = ToPcd.DefaultValue\r
             if Value in [None, '']:\r
-                ToPcd.MaxDatumSize = 1\r
+                ToPcd.MaxDatumSize = '1'\r
             elif Value[0] == 'L':\r
-                ToPcd.MaxDatumSize = str(len(Value) * 2)\r
+                ToPcd.MaxDatumSize = str((len(Value) - 2) * 2)\r
             elif Value[0] == '{':\r
                 ToPcd.MaxDatumSize = str(len(Value.split(',')))\r
             else:\r
-                ToPcd.MaxDatumSize = str(len(Value))\r
+                ToPcd.MaxDatumSize = str(len(Value) - 1)\r
 \r
         # apply default SKU for dynamic PCDS if specified one is not available\r
         if (ToPcd.Type in PCD_DYNAMIC_TYPE_LIST or ToPcd.Type in PCD_DYNAMIC_EX_TYPE_LIST) \\r
@@ -1045,7 +1849,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
@@ -1056,7 +1860,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
@@ -1080,16 +1884,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
@@ -1191,6 +2065,13 @@ class PlatformAutoGen(AutoGen):
                         BuildOptions[Tool][Attr] = Value[1:]\r
                     else:\r
                         BuildOptions[Tool][Attr] += " " + Value\r
+        if Module.AutoGenVersion < 0x00010005 and self.Workspace.UniFlag != None:\r
+            #\r
+            # Override UNI flag only for EDK module.\r
+            #\r
+            if 'BUILD' not in BuildOptions:\r
+                BuildOptions['BUILD'] = {}\r
+            BuildOptions['BUILD']['FLAGS'] = self.Workspace.UniFlag\r
         return BuildOptions\r
 \r
     Platform            = property(_GetPlatform)\r
@@ -1206,6 +2087,7 @@ class PlatformAutoGen(AutoGen):
     PcdTokenNumber      = property(_GetPcdTokenNumbers)    # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber\r
     DynamicPcdList      = property(_GetDynamicPcdList)    # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]\r
     NonDynamicPcdList   = property(_GetNonDynamicPcdList)    # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]\r
+    NonDynamicPcdDict   = property(_GetNonDynamicPcdDict)\r
     PackageList         = property(_GetPackageList)\r
 \r
     ToolDefinition      = property(_GetToolDefinition)    # toolcode : tool path\r
@@ -1220,6 +2102,7 @@ class PlatformAutoGen(AutoGen):
     BuildRule           = property(_GetBuildRule)\r
     ModuleAutoGenList   = property(_GetModuleAutoGenList)\r
     LibraryAutoGenList  = property(_GetLibraryAutoGenList)\r
+    GenFdsCommand       = property(_GenFdsCommand)\r
 \r
 ## ModuleAutoGen class\r
 #\r
@@ -1270,6 +2153,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
@@ -1303,23 +2188,52 @@ class ModuleAutoGen(AutoGen):
         self._DerivedPackageList      = None\r
         self._ModulePcdList           = None\r
         self._LibraryPcdList          = None\r
+        self._PcdComments = sdict()\r
         self._GuidList                = None\r
+        self._GuidsUsedByPcd = None\r
+        self._GuidComments = sdict()\r
         self._ProtocolList            = None\r
+        self._ProtocolComments = sdict()\r
         self._PpiList                 = None\r
+        self._PpiComments = sdict()\r
         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
         self._FileTypes               = None\r
         self._BuildRules              = None\r
-\r
+        \r
+        ## The Modules referenced to this Library\r
+        #  Only Library has this attribute\r
+        self._ReferenceModules        = []        \r
+        \r
+        ## Store the FixedAtBuild Pcds\r
+        #  \r
+        self._FixedAtBuildPcds         = []\r
+        self.ConstPcd                  = {}\r
         return True\r
 \r
     def __repr__(self):\r
         return "%s [%s]" % (self.MetaFile, self.Arch)\r
 \r
+    # Get FixedAtBuild Pcds of this Module\r
+    def _GetFixedAtBuildPcds(self):\r
+        if self._FixedAtBuildPcds:\r
+            return self._FixedAtBuildPcds\r
+        for Pcd in self.ModulePcdList:\r
+            if self.IsLibrary:\r
+                if not (Pcd.Pending == False and Pcd.Type == "FixedAtBuild"):\r
+                    continue\r
+            elif Pcd.Type != "FixedAtBuild":\r
+                continue\r
+            if Pcd not in self._FixedAtBuildPcds:\r
+                self._FixedAtBuildPcds.append(Pcd)\r
+                \r
+        return self._FixedAtBuildPcds        \r
+\r
     # Macros could be used in build_rule.txt (also Makefile)\r
     def _GetMacros(self):\r
         if self._Macro == None:\r
@@ -1339,6 +2253,7 @@ class ModuleAutoGen(AutoGen):
             self._Macro["ARCH"                  ] = self.Arch\r
             self._Macro["TOOLCHAIN"             ] = self.ToolChain\r
             self._Macro["TOOLCHAIN_TAG"         ] = self.ToolChain\r
+            self._Macro["TOOL_CHAIN_TAG"        ] = self.ToolChain\r
             self._Macro["TARGET"                ] = self.BuildTarget\r
 \r
             self._Macro["BUILD_DIR"             ] = self.PlatformInfo.BuildDir\r
@@ -1352,13 +2267,17 @@ class ModuleAutoGen(AutoGen):
     ## Return the module build data object\r
     def _GetModule(self):\r
         if self._Module == None:\r
-            self._Module = self.Workspace.BuildDatabase[self.MetaFile, self.Arch]\r
+            self._Module = self.Workspace.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]\r
         return self._Module\r
 \r
     ## Return the module name\r
     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
@@ -1375,7 +2294,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
@@ -1400,6 +2319,10 @@ class ModuleAutoGen(AutoGen):
                 self._LibraryFlag = False\r
         return self._LibraryFlag\r
 \r
+    ## Check if the module is binary module or not\r
+    def _IsBinaryModule(self):\r
+        return self.Module.IsBinaryModule\r
+\r
     ## Return the directory to store intermediate files of the module\r
     def _GetBuildDir(self):\r
         if self._BuildDir == None:\r
@@ -1478,7 +2401,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
@@ -1514,7 +2437,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
@@ -1560,6 +2483,66 @@ 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/RVCT\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', 'RVCT'):\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
+                #\r
+                self._BuildOptionIncPathList = []\r
+                return self._BuildOptionIncPathList\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
+                if self.PlatformInfo.ToolChainFamily != 'RVCT':\r
+                    IncPathList = [NormPath(Path, self.Macros) for Path in gBuildOptIncludePattern.findall(FlagOption)]\r
+                else:\r
+                    #\r
+                    # RVCT may specify a list of directory seperated by commas\r
+                    #\r
+                    IncPathList = []\r
+                    for Path in gBuildOptIncludePattern.findall(FlagOption):\r
+                        PathList = GetSplitList(Path, TAB_COMMA_SPLIT)\r
+                        IncPathList += [NormPath(PathEntry, self.Macros) for PathEntry in PathList]\r
+\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
@@ -1570,12 +2553,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
@@ -1649,6 +2632,9 @@ class ModuleAutoGen(AutoGen):
             self._BuildTargets = {}\r
             self._FileTypes = {}\r
 \r
+        SubDirectory = os.path.join(self.OutputDir, File.SubDir)\r
+        if not os.path.exists(SubDirectory):\r
+            CreateDirectory(SubDirectory)\r
         LastTarget = None\r
         RuleChain = []\r
         SourceList = [File]\r
@@ -1661,6 +2647,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
@@ -1715,7 +2704,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
@@ -1750,9 +2739,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
@@ -1760,7 +2748,11 @@ class ModuleAutoGen(AutoGen):
             AutoGenH = TemplateString()\r
             StringH = TemplateString()\r
             GenC.CreateCode(self, AutoGenC, AutoGenH, StringH, UniStringAutoGenC, UniStringBinBuffer)\r
-            if str(AutoGenC) != "" and TAB_C_CODE_FILE in self.FileTypes:\r
+            #\r
+            # AutoGen.c is generated if there are library classes in inf, or there are object files\r
+            #\r
+            if str(AutoGenC) != "" and (len(self.Module.LibraryClasses) > 0\r
+                                        or TAB_OBJECT_FILE in self.FileTypes):\r
                 AutoFile = PathClass(gAutoGenCodeFileName, self.DebugDir)\r
                 self._AutoGenFileList[AutoFile] = str(AutoGenC)\r
                 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
@@ -1794,6 +2786,12 @@ class ModuleAutoGen(AutoGen):
                     self._DependentLibraryList = self.PlatformInfo.ApplyLibraryInstance(self.Module)\r
         return self._DependentLibraryList\r
 \r
+    @staticmethod\r
+    def UpdateComments(Recver, Src):\r
+        for Key in Src:\r
+            if Key not in Recver:\r
+                Recver[Key] = []\r
+            Recver[Key].extend(Src[Key])\r
     ## Get the list of PCDs from current module\r
     #\r
     #   @retval     list                    The list of PCD\r
@@ -1802,6 +2800,7 @@ class ModuleAutoGen(AutoGen):
         if self._ModulePcdList == None:\r
             # apply PCD settings from platform\r
             self._ModulePcdList = self.PlatformInfo.ApplyPcdSetting(self.Module, self.Module.Pcds)\r
+            self.UpdateComments(self._PcdComments, self.Module.PcdComments)\r
         return self._ModulePcdList\r
 \r
     ## Get the list of PCDs from dependent libraries\r
@@ -1810,10 +2809,11 @@ 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
+                    self.UpdateComments(self._PcdComments, Library.PcdComments)\r
                     for Key in Library.Pcds:\r
                         # skip duplicated PCDs\r
                         if Key in self.Module.Pcds or Key in Pcds:\r
@@ -1834,8 +2834,17 @@ class ModuleAutoGen(AutoGen):
             self._GuidList = self.Module.Guids\r
             for Library in self.DependentLibraryList:\r
                 self._GuidList.update(Library.Guids)\r
+                self.UpdateComments(self._GuidComments, Library.GuidComments)\r
+            self.UpdateComments(self._GuidComments, self.Module.GuidComments)\r
         return self._GuidList\r
 \r
+    def GetGuidsUsedByPcd(self):\r
+        if self._GuidsUsedByPcd == None:\r
+            self._GuidsUsedByPcd = sdict()\r
+            self._GuidsUsedByPcd.update(self.Module.GetGuidsUsedByPcd())\r
+            for Library in self.DependentLibraryList:\r
+                self._GuidsUsedByPcd.update(Library.GetGuidsUsedByPcd())\r
+        return self._GuidsUsedByPcd\r
     ## Get the protocol value mapping\r
     #\r
     #   @retval     dict    The mapping between protocol cname and its value\r
@@ -1845,6 +2854,8 @@ class ModuleAutoGen(AutoGen):
             self._ProtocolList = self.Module.Protocols\r
             for Library in self.DependentLibraryList:\r
                 self._ProtocolList.update(Library.Protocols)\r
+                self.UpdateComments(self._ProtocolComments, Library.ProtocolComments)\r
+            self.UpdateComments(self._ProtocolComments, self.Module.ProtocolComments)\r
         return self._ProtocolList\r
 \r
     ## Get the PPI value mapping\r
@@ -1856,6 +2867,8 @@ class ModuleAutoGen(AutoGen):
             self._PpiList = self.Module.Ppis\r
             for Library in self.DependentLibraryList:\r
                 self._PpiList.update(Library.Ppis)\r
+                self.UpdateComments(self._PpiComments, Library.PpiComments)\r
+            self.UpdateComments(self._PpiComments, self.Module.PpiComments)\r
         return self._PpiList\r
 \r
     ## Get the list of include search path\r
@@ -1869,11 +2882,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
@@ -1888,12 +2901,269 @@ 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 and PatchableInModule PCDs used by this module and dependent libraries\r
+        # Also find all packages that the DynamicEx PCDs depend on\r
+        Pcds = []\r
+        PatchablePcds = {}\r
+        Packages = []        \r
+        PcdCheckList = []\r
+        PcdTokenSpaceList = []\r
+        for Pcd in self.ModulePcdList + self.LibraryPcdList:\r
+            if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:\r
+                PatchablePcds[Pcd.TokenCName] = Pcd\r
+                PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, 'PatchableInModule'))\r
+            elif Pcd.Type in GenC.gDynamicExPcd:\r
+                if Pcd not in Pcds:\r
+                    Pcds += [Pcd]\r
+                    PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, 'DynamicEx'))\r
+                    PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, 'Dynamic'))\r
+                    PcdTokenSpaceList.append(Pcd.TokenSpaceGuidCName)\r
+        GuidList = sdict()\r
+        GuidList.update(self.GuidList)\r
+        for TokenSpace in self.GetGuidsUsedByPcd():\r
+            # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list\r
+            # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs\r
+            if TokenSpace not in PcdTokenSpaceList and TokenSpace in GuidList:\r
+                GuidList.pop(TokenSpace)\r
+        CheckList = (GuidList, self.PpiList, self.ProtocolList, PcdCheckList)\r
+        for Package in self.DerivedPackageList:\r
+            if Package in Packages:\r
+                continue\r
+            BeChecked = (Package.Guids, Package.Ppis, Package.Protocols, Package.Pcds)\r
+            Found = False\r
+            for Index in range(len(BeChecked)):\r
+                for Item in CheckList[Index]:\r
+                    if Item in BeChecked[Index]:\r
+                        Packages += [Package]\r
+                        Found = True\r
+                        break\r
+                if Found: break\r
+\r
+        ModuleType = self.ModuleType\r
+        if ModuleType == 'UEFI_DRIVER' and self.DepexGenerated:\r
+            ModuleType = 'DXE_DRIVER'\r
+\r
+        DriverType = ''\r
+        if self.PcdIsDriver != '':\r
+            DriverType = self.PcdIsDriver\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
+          'pcd_is_driver_string'              : [],\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
+          'patchablepcd_item'                 : [],\r
+          'pcd_item'                          : [],\r
+          'protocol_item'                     : [],\r
+          'ppi_item'                          : [],\r
+          'guid_item'                         : [],\r
+          'flags_item'                        : [],\r
+          'libraryclasses_item'               : []\r
+        }\r
+        AsBuiltInfDict['module_inf_version'] = '0x%08x' % self.AutoGenVersion\r
+        if DriverType:\r
+            AsBuiltInfDict['pcd_is_driver_string'] += [DriverType]\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 Root, Dirs, Files in os.walk(OutputDir):\r
+            for File in Files:\r
+                if File.lower().endswith('.pdb'):\r
+                    AsBuiltInfDict['binary_item'] += ['DISPOSABLE|' + File]\r
+        HeaderComments = self.Module.HeaderComments\r
+        StartPos = 0\r
+        for Index in range(len(HeaderComments)):\r
+            if HeaderComments[Index].find('@BinaryHeader') != -1:\r
+                HeaderComments[Index] = HeaderComments[Index].replace('@BinaryHeader', '@file')\r
+                StartPos = Index\r
+                break\r
+        AsBuiltInfDict['header_comments'] = '\n'.join(HeaderComments[StartPos:]).replace(':#', '://')\r
+        GenList = [\r
+            (self.ProtocolList, self._ProtocolComments, 'protocol_item'),\r
+            (self.PpiList, self._PpiComments, 'ppi_item'),\r
+            (GuidList, self._GuidComments, 'guid_item')\r
+        ]\r
+        for Item in GenList:\r
+            for CName in Item[0]:\r
+                Comments = ''\r
+                if CName in Item[1]:\r
+                    Comments = '\n  '.join(Item[1][CName])\r
+                Entry = CName\r
+                if Comments:\r
+                    Entry = Comments + '\n  ' + CName\r
+                AsBuiltInfDict[Item[2]].append(Entry)\r
+        PatchList = parsePcdInfoFromMapFile(\r
+                            os.path.join(self.OutputDir, self.Name + '.map'),\r
+                            os.path.join(self.OutputDir, self.Name + '.efi')\r
+                        )\r
+        if PatchList:\r
+            for PatchPcd in PatchList:\r
+                if PatchPcd[0] not in PatchablePcds:\r
+                    continue\r
+                Pcd = PatchablePcds[PatchPcd[0]]\r
+                PcdValue = ''\r
+                if Pcd.DatumType != 'VOID*':\r
+                    HexFormat = '0x%02x'\r
+                    if Pcd.DatumType == 'UINT16':\r
+                        HexFormat = '0x%04x'\r
+                    elif Pcd.DatumType == 'UINT32':\r
+                        HexFormat = '0x%08x'\r
+                    elif Pcd.DatumType == 'UINT64':\r
+                        HexFormat = '0x%016x'\r
+                    PcdValue = HexFormat % int(Pcd.DefaultValue, 0)\r
+                else:\r
+                    if Pcd.MaxDatumSize == None or Pcd.MaxDatumSize == '':\r
+                        EdkLogger.error("build", AUTOGEN_ERROR,\r
+                                        "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)\r
+                                        )\r
+                    ArraySize = int(Pcd.MaxDatumSize, 0)\r
+                    PcdValue = Pcd.DefaultValue\r
+                    if PcdValue[0] != '{':\r
+                        Unicode = False\r
+                        if PcdValue[0] == 'L':\r
+                            Unicode = True\r
+                        PcdValue = PcdValue.lstrip('L')\r
+                        PcdValue = eval(PcdValue)\r
+                        NewValue = '{'\r
+                        for Index in range(0, len(PcdValue)):\r
+                            if Unicode:\r
+                                CharVal = ord(PcdValue[Index])\r
+                                NewValue = NewValue + '0x%02x' % (CharVal & 0x00FF) + ', ' \\r
+                                        + '0x%02x' % (CharVal >> 8) + ', '\r
+                            else:\r
+                                NewValue = NewValue + '0x%02x' % (ord(PcdValue[Index]) % 0x100) + ', '\r
+                        Padding = '0x00, '\r
+                        if Unicode:\r
+                            Padding = Padding * 2\r
+                            ArraySize = ArraySize / 2\r
+                        if ArraySize < (len(PcdValue) + 1):\r
+                            EdkLogger.error("build", AUTOGEN_ERROR,\r
+                                            "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)\r
+                                            )\r
+                        if ArraySize > len(PcdValue) + 1:\r
+                            NewValue = NewValue + Padding * (ArraySize - len(PcdValue) - 1)\r
+                        PcdValue = NewValue + Padding.strip().rstrip(',') + '}'\r
+                    elif len(PcdValue.split(',')) <= ArraySize:\r
+                        PcdValue = PcdValue.rstrip('}') + ', 0x00' * (ArraySize - len(PcdValue.split(',')))\r
+                        PcdValue += '}'\r
+                    else:\r
+                        EdkLogger.error("build", AUTOGEN_ERROR,\r
+                                        "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)\r
+                                        )\r
+                PcdItem = '%s.%s|%s|0x%X' % \\r
+                    (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, PcdValue, PatchPcd[1])\r
+                PcdComments = ''\r
+                if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
+                    PcdComments = '\n  '.join(self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName])\r
+                if PcdComments:\r
+                    PcdItem = PcdComments + '\n  ' + PcdItem\r
+                AsBuiltInfDict['patchablepcd_item'].append(PcdItem)\r
+        for Pcd in Pcds:\r
+            PcdComments = ''\r
+            PcdCommentList = []\r
+            HiiInfo = ''\r
+            if Pcd.Type == TAB_PCDS_DYNAMIC_EX_HII:\r
+                for SkuName in Pcd.SkuInfoList:\r
+                    SkuInfo = Pcd.SkuInfoList[SkuName]\r
+                    HiiInfo = '## %s|%s|%s' % (SkuInfo.VariableName, SkuInfo.VariableGuid, SkuInfo.VariableOffset)\r
+                    break\r
+            if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
+                PcdCommentList = self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName][:]\r
+            if HiiInfo:\r
+                UsageIndex = -1\r
+                for Index, Comment in enumerate(PcdCommentList):\r
+                    for Usage in UsageList:\r
+                        if Comment.find(Usage) != -1:\r
+                            UsageIndex = Index\r
+                            break\r
+                if UsageIndex != -1:\r
+                    PcdCommentList[UsageIndex] = PcdCommentList[UsageIndex] + ' ' + HiiInfo\r
+                else:\r
+                    PcdCommentList.append('## ' + HiiInfo)\r
+            PcdComments = '\n  '.join(PcdCommentList)\r
+            PcdEntry = Pcd.TokenSpaceGuidCName + '.' + Pcd.TokenCName\r
+            if PcdComments:\r
+                PcdEntry = PcdComments + '\n  ' + PcdEntry\r
+            AsBuiltInfDict['pcd_item'] += [PcdEntry]\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
     #                                       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
@@ -1914,6 +3184,11 @@ class ModuleAutoGen(AutoGen):
 \r
         self.IsMakeFileCreated = True\r
 \r
+    def CopyBinaryFiles(self):\r
+        for File in self.Module.Binaries:\r
+            SrcPath = File.Path\r
+            DstPath = os.path.join(self.OutputDir , os.path.basename(SrcPath))\r
+            CopyLongFilePath(SrcPath, DstPath)\r
     ## Create autogen code for the module and its dependent libraries\r
     #\r
     #   @param      CreateLibraryCodeFile   Flag indicating if or not the code of\r
@@ -1923,6 +3198,14 @@ class ModuleAutoGen(AutoGen):
         if self.IsCodeFileCreated:\r
             return\r
 \r
+        # Need to generate PcdDatabase even PcdDriver is binarymodule\r
+        if self.IsBinaryModule and self.PcdIsDriver != '':\r
+            CreatePcdDatabaseCode(self, TemplateString(), TemplateString())\r
+            return\r
+        if self.IsBinaryModule:\r
+            self.CopyBinaryFiles()\r
+            return\r
+\r
         if not self.IsLibrary and CreateLibraryCodeFile:\r
             for LibraryAutoGen in self.LibraryAutoGenList:\r
                 LibraryAutoGen.CreateCodeFile()\r
@@ -1932,7 +3215,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
@@ -1945,11 +3228,16 @@ class ModuleAutoGen(AutoGen):
             return\r
 \r
         for ModuleType in self.DepexList:\r
-            if len(self.DepexList[ModuleType]) == 0:\r
+            # Ignore empty [depex] section or [depex] section for "USER_DEFINED" module\r
+            if len(self.DepexList[ModuleType]) == 0 or ModuleType == "USER_DEFINED":\r
                 continue\r
+\r
             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
@@ -1987,14 +3275,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
@@ -2008,7 +3288,7 @@ class ModuleAutoGen(AutoGen):
     Specification   = property(_GetSpecification)\r
 \r
     IsLibrary       = property(_IsLibrary)\r
-\r
+    IsBinaryModule  = property(_IsBinaryModule)\r
     BuildDir        = property(_GetBuildDir)\r
     OutputDir       = property(_GetOutputDir)\r
     DebugDir        = property(_GetDebugDir)\r
@@ -2037,9 +3317,13 @@ 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
+    FixedAtBuildPcds         = property(_GetFixedAtBuildPcds)\r
 \r
 # This acts like the main() function for the script, unless it is 'import'ed into another script.\r
 if __name__ == '__main__':\r