]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/AutoGen/AutoGen.py
License header updated to match correct format.
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / AutoGen.py
index 11cf8b2f18deb0c6f7b27a3357a42e4fb3d50110..8cd387072e26c8786dc375b5b6f1e906339163ad 100644 (file)
@@ -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
@@ -39,15 +40,27 @@ import Common.VpdInfoFile as VpdInfoFile
 from GenPcdDb import CreatePcdDatabaseCode\r
 from Workspace.MetaFileCommentParser import UsageList\r
 \r
+import InfSectionParser\r
+\r
 ## Regular expression for splitting Dependency Expression string into tokens\r
 gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)")\r
 \r
+#\r
+# Match name = variable\r
+#\r
+gEfiVarStoreNamePattern = re.compile("\s*name\s*=\s*(\w+)")\r
+#\r
+# The format of guid in efivarstore statement likes following and must be correct:\r
+# guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}\r
+#\r
+gEfiVarStoreGuidPattern = re.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")\r
+\r
 ## Mapping Makefile type\r
 gMakeTypeMap = {"MSFT":"nmake", "GCC":"gmake"}\r
 \r
 \r
 ## Build rule configuration file\r
-gBuildRuleFile = 'Conf/build_rule.txt'\r
+gDefaultBuildRuleFile = 'Conf/build_rule.txt'\r
 \r
 ## Build rule default version\r
 AutoGenReqBuildRuleVerNum = "0.1"\r
@@ -59,22 +72,40 @@ gAutoGenStringFileName = "%(module_name)sStrDefs.h"
 gAutoGenStringFormFileName = "%(module_name)sStrDefs.hpk"\r
 gAutoGenDepexFileName = "%(module_name)s.depex"\r
 \r
+gInfSpecVersion = "0x00010017"\r
+\r
 #\r
 # Template string to generic AsBuilt INF\r
 #\r
 gAsBuiltInfHeaderString = TemplateString("""${header_comments}\r
 \r
+# DO NOT EDIT\r
+# FILE auto-generated\r
+\r
 [Defines]\r
-  INF_VERSION                = 0x00010016\r
+  INF_VERSION                = ${module_inf_version}\r
   BASE_NAME                  = ${module_name}\r
   FILE_GUID                  = ${module_guid}\r
-  MODULE_TYPE                = ${module_module_type}\r
-  VERSION_STRING             = ${module_version_string}${BEGIN}\r
+  MODULE_TYPE                = ${module_module_type}${BEGIN}\r
+  VERSION_STRING             = ${module_version_string}${END}${BEGIN}\r
   PCD_IS_DRIVER              = ${pcd_is_driver_string}${END}${BEGIN}\r
   UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}\r
-  PI_SPECIFICATION_VERSION   = ${module_pi_specification_version}${END}\r
-\r
-[Packages]${BEGIN}\r
+  PI_SPECIFICATION_VERSION   = ${module_pi_specification_version}${END}${BEGIN}\r
+  ENTRY_POINT                = ${module_entry_point}${END}${BEGIN}\r
+  UNLOAD_IMAGE               = ${module_unload_image}${END}${BEGIN}\r
+  CONSTRUCTOR                = ${module_constructor}${END}${BEGIN}\r
+  DESTRUCTOR                 = ${module_destructor}${END}${BEGIN}\r
+  SHADOW                     = ${module_shadow}${END}${BEGIN}\r
+  PCI_VENDOR_ID              = ${module_pci_vendor_id}${END}${BEGIN}\r
+  PCI_DEVICE_ID              = ${module_pci_device_id}${END}${BEGIN}\r
+  PCI_CLASS_CODE             = ${module_pci_class_code}${END}${BEGIN}\r
+  PCI_REVISION               = ${module_pci_revision}${END}${BEGIN}\r
+  BUILD_NUMBER               = ${module_build_number}${END}${BEGIN}\r
+  SPEC                       = ${module_spec}${END}${BEGIN}\r
+  UEFI_HII_RESOURCE_SECTION  = ${module_uefi_hii_resource_section}${END}${BEGIN}\r
+  MODULE_UNI_FILE            = ${module_uni_file}${END}\r
+\r
+[Packages.${module_arch}]${BEGIN}\r
   ${package_item}${END}\r
 \r
 [Binaries.${module_arch}]${BEGIN}\r
@@ -83,19 +114,32 @@ gAsBuiltInfHeaderString = TemplateString("""${header_comments}
 [PatchPcd.${module_arch}]${BEGIN}\r
   ${patchablepcd_item}\r
 ${END}\r
+\r
 [Protocols.${module_arch}]${BEGIN}\r
   ${protocol_item}\r
 ${END}\r
+\r
 [Ppis.${module_arch}]${BEGIN}\r
   ${ppi_item}\r
 ${END}\r
+\r
 [Guids.${module_arch}]${BEGIN}\r
   ${guid_item}\r
 ${END}\r
+\r
 [PcdEx.${module_arch}]${BEGIN}\r
   ${pcd_item}\r
 ${END}\r
 \r
+[LibraryClasses.${module_arch}]\r
+## @LIB_INSTANCES${BEGIN}\r
+#  ${libraryclasses_item}${END}\r
+\r
+${depexsection_item}\r
+\r
+${tail_comments}\r
+\r
+[BuildOptions.${module_arch}]\r
 ## @AsBuilt${BEGIN}\r
 ##   ${flags_item}${END}\r
 """)\r
@@ -239,6 +283,15 @@ class WorkspaceAutoGen(AutoGen):
                             ExtraData="Build target [%s] is not supported by the platform. [Valid target: %s]"\r
                                       % (self.BuildTarget, " ".join(self.Platform.BuildTargets)))\r
 \r
+        # Validate SKU ID\r
+        if not self.SkuId:\r
+            self.SkuId = 'DEFAULT'\r
+\r
+        if self.SkuId not in self.Platform.SkuIds:\r
+            EdkLogger.error("build", PARAMETER_INVALID,\r
+                            ExtraData="SKU-ID [%s] is not supported by the platform. [Valid SKU-ID: %s]"\r
+                                      % (self.SkuId, " ".join(self.Platform.SkuIds.keys())))\r
+\r
         # parse FDF file to get PCDs in it, if any\r
         if not self.FdfFile:\r
             self.FdfFile = self.Platform.FlashDefinition\r
@@ -268,6 +321,7 @@ class WorkspaceAutoGen(AutoGen):
             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
@@ -297,7 +351,15 @@ class WorkspaceAutoGen(AutoGen):
             DecPcds = {}\r
             DecPcdsKey = set()\r
             PGen = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)\r
-            Pkgs = PGen.PackageList\r
+            #Collect package set information from INF of FDF\r
+            PkgSet = set()\r
+            for Inf in ModuleList:\r
+                ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch)\r
+                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
@@ -346,10 +408,10 @@ class WorkspaceAutoGen(AutoGen):
         # Check PCD type and definition between DSC and DEC\r
         #\r
         self._CheckPcdDefineAndType()\r
-        \r
-        if self.FdfFile:\r
-            self._CheckDuplicateInFV(Fdf)\r
-        \r
+\r
+        if self.FdfFile:\r
+            self._CheckDuplicateInFV(Fdf)\r
+\r
         self._BuildDir = None\r
         self._FvDir = None\r
         self._MakeFileDir = None\r
@@ -653,7 +715,9 @@ class WorkspaceAutoGen(AutoGen):
                                     ExtraData=None\r
                                     )\r
                     Count += 1\r
-                                      \r
+    ## Generate fds command\r
+    def _GenFdsCommand(self):\r
+        return (GenMake.TopLevelMakefile(self)._TEMPLATE_.Replace(GenMake.TopLevelMakefile(self)._TemplateDict)).strip()\r
 \r
     ## Create makefile for the platform and modules in it\r
     #\r
@@ -661,15 +725,6 @@ class WorkspaceAutoGen(AutoGen):
     #                                       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
@@ -704,6 +759,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
@@ -765,6 +821,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
@@ -799,9 +857,19 @@ class PlatformAutoGen(AutoGen):
         self._ModuleAutoGenList  = None\r
         self._LibraryAutoGenList = None\r
         self._BuildCommand = None\r
-\r
-        # get the original module/package/platform objects\r
-        self.BuildDatabase = Workspace.BuildDatabase\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
         return True\r
 \r
     def __repr__(self):\r
@@ -826,6 +894,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
@@ -837,20 +909,17 @@ class PlatformAutoGen(AutoGen):
                 Ma = ModuleAutoGen(self.Workspace, ModuleFile, self.BuildTarget,\r
                                    self.ToolChain, self.Arch, self.MetaFile)\r
                 Ma.CreateMakeFile(True)\r
-                Ma.CreateAsBuiltInf()\r
+                #Ma.CreateAsBuiltInf()\r
 \r
         # no need to create makefile for the platform more than once\r
         if self.IsMakeFileCreated:\r
             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
@@ -887,8 +956,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
@@ -900,7 +973,45 @@ class PlatformAutoGen(AutoGen):
                 if PcdFromModule.DatumType == "VOID*" and PcdFromModule.MaxDatumSize in [None, '']:\r
                     NoDatumTypePcdList.add("%s.%s [%s]" % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, F))\r
 \r
+                # Check the PCD from Binary INF or Source INF\r
+                if M.IsBinaryModule == True:\r
+                    PcdFromModule.IsFromBinaryInf = True\r
+\r
+                # Check the PCD from DSC or not \r
+                if (PcdFromModule.TokenCName, PcdFromModule.TokenSpaceGuidCName) in self.Platform.Pcds.keys():\r
+                    PcdFromModule.IsFromDsc = True\r
+                else:\r
+                    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
@@ -917,6 +1028,73 @@ 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
+                        # Overwrite the phase of any the same PCD existing, if Phase is PEI.\r
+                        # It is to solve the case that a dynamic PCD used by a PEM module/PEI \r
+                        # module & DXE module at a same time.\r
+                        # Overwrite the type of the PCDs in source INF by the type of AsBuild\r
+                        # INF file as DynamicEx. \r
+                        Index = self._DynaPcdList_.index(PcdFromModule)\r
+                        self._DynaPcdList_[Index].Phase = PcdFromModule.Phase\r
+                        self._DynaPcdList_[Index].Type = PcdFromModule.Type\r
+        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
@@ -927,8 +1105,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
@@ -1100,7 +1289,7 @@ class PlatformAutoGen(AutoGen):
         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
@@ -1290,7 +1479,7 @@ class PlatformAutoGen(AutoGen):
             self._EdkIIBuildOption = self._ExpandBuildOption(self.Platform.BuildOptions, EDKII_NAME)\r
         return self._EdkIIBuildOption\r
 \r
-    ## Parse build_rule.txt in $(WORKSPACE)/Conf/build_rule.txt\r
+    ## Parse build_rule.txt in Conf Directory.\r
     #\r
     #   @retval     BuildRule object\r
     #\r
@@ -1300,7 +1489,7 @@ class PlatformAutoGen(AutoGen):
             if TAB_TAT_DEFINES_BUILD_RULE_CONF in self.Workspace.TargetTxt.TargetTxtDictionary:\r
                 BuildRuleFile = self.Workspace.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_BUILD_RULE_CONF]\r
             if BuildRuleFile in [None, '']:\r
-                BuildRuleFile = gBuildRuleFile\r
+                BuildRuleFile = gDefaultBuildRuleFile\r
             self._BuildRule = BuildRule(BuildRuleFile)\r
             if self._BuildRule._FileVersion == "":\r
                 self._BuildRule._FileVersion = AutoGenReqBuildRuleVerNum\r
@@ -1321,7 +1510,14 @@ 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
@@ -1429,7 +1625,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
@@ -1963,6 +2160,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
@@ -2000,6 +2198,9 @@ class ModuleAutoGen(AutoGen):
             return False\r
 \r
         self.SourceDir = self.MetaFile.SubDir\r
+        if self.SourceDir.upper().find(self.WorkspaceDir.upper()) == 0:\r
+            self.SourceDir = self.SourceDir[len(self.WorkspaceDir) + 1:]\r
+\r
         self.SourceOverrideDir = None\r
         # use overrided path defined in DSC file\r
         if self.MetaFile.Key in GlobalData.gOverrideDir:\r
@@ -2144,6 +2345,16 @@ class ModuleAutoGen(AutoGen):
 \r
     ## Return the module meta-file GUID\r
     def _GetGuid(self):\r
+        #\r
+        # To build same module more than once, the module path with FILE_GUID overridden has\r
+        # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path\r
+        # in DSC. The overridden GUID can be retrieved from file name\r
+        #\r
+        if os.path.basename(self.MetaFile.File) != os.path.basename(self.MetaFile.Path):\r
+            #\r
+            # Length of GUID is 36\r
+            #\r
+            return os.path.basename(self.MetaFile.Path)[:36]\r
         return self.Module.Guid\r
 \r
     ## Return the module version\r
@@ -2253,7 +2464,66 @@ class ModuleAutoGen(AutoGen):
                     continue\r
                 PackageList.append(Package)\r
         return PackageList\r
-\r
+    \r
+    ## Get the depex string\r
+    #\r
+    # @return : a string contain all depex expresion.\r
+    def _GetDepexExpresionString(self):\r
+        DepexStr = ''\r
+        DepexList = []\r
+        ## DPX_SOURCE IN Define section.\r
+        if self.Module.DxsFile:\r
+            return DepexStr\r
+        for M in [self.Module] + self.DependentLibraryList:\r
+            Filename = M.MetaFile.Path\r
+            InfObj = InfSectionParser.InfSectionParser(Filename)\r
+            DepexExpresionList = InfObj.GetDepexExpresionList()\r
+            for DepexExpresion in DepexExpresionList:\r
+                for key in DepexExpresion.keys():\r
+                    Arch, ModuleType = key\r
+                    # the type of build module is USER_DEFINED.\r
+                    # All different DEPEX section tags would be copied into the As Built INF file\r
+                    # and there would be separate DEPEX section tags\r
+                    if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:\r
+                        if (Arch.upper() == self.Arch.upper()) and (ModuleType.upper() != TAB_ARCH_COMMON):\r
+                            DepexList.append({(Arch, ModuleType): DepexExpresion[key][:]})\r
+                    else:\r
+                        if Arch.upper() == TAB_ARCH_COMMON or \\r
+                          (Arch.upper() == self.Arch.upper() and \\r
+                          ModuleType.upper() in [TAB_ARCH_COMMON, self.ModuleType.upper()]):\r
+                            DepexList.append({(Arch, ModuleType): DepexExpresion[key][:]})\r
+        \r
+        #the type of build module is USER_DEFINED.\r
+        if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:\r
+            for Depex in DepexList:\r
+                for key in Depex.keys():\r
+                    DepexStr += '[Depex.%s.%s]\n' % key\r
+                    DepexStr += '\n'.join(['# '+ val for val in Depex[key]])\r
+                    DepexStr += '\n\n'\r
+            if not DepexStr:\r
+                return '[Depex.%s]\n' % self.Arch\r
+            return DepexStr\r
+        \r
+        #the type of build module not is USER_DEFINED.\r
+        Count = 0\r
+        for Depex in DepexList:\r
+            Count += 1\r
+            if DepexStr != '':\r
+                DepexStr += ' AND '\r
+            DepexStr += '('\r
+            for D in Depex.values():\r
+                DepexStr += ' '.join([val for val in D])\r
+            Index = DepexStr.find('END')\r
+            if Index > -1 and Index == len(DepexStr) - 3:\r
+                DepexStr = DepexStr[:-3]\r
+            DepexStr = DepexStr.strip()\r
+            DepexStr += ')'\r
+        if Count == 1:\r
+            DepexStr = DepexStr.lstrip('(').rstrip(')').strip()\r
+        if not DepexStr:\r
+            return '[Depex.%s]\n' % self.Arch\r
+        return '[Depex.%s]\n#  ' % self.Arch + DepexStr\r
+    \r
     ## Merge dependency expression\r
     #\r
     #   @retval     list    The token list of the dependency expression after parsed\r
@@ -2406,7 +2676,7 @@ class ModuleAutoGen(AutoGen):
     ## Return a list of files which can be built from source\r
     #\r
     #  What kind of files can be built is determined by build rules in\r
-    #  $(WORKSPACE)/Conf/build_rule.txt and toolchain family.\r
+    #  $(CONF_DIRECTORY)/build_rule.txt and toolchain family.\r
     #\r
     def _GetSourceFileList(self):\r
         if self._SourceFileList == None:\r
@@ -2492,6 +2762,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
@@ -2605,7 +2878,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
@@ -2754,6 +3031,71 @@ class ModuleAutoGen(AutoGen):
                         self._IncludePathList.append(str(Inc))\r
         return self._IncludePathList\r
 \r
+    ## Get HII EX PCDs which maybe used by VFR\r
+    #\r
+    #  efivarstore used by VFR may relate with HII EX PCDs\r
+    #  Get the variable name and GUID from efivarstore and HII EX PCD\r
+    #  List the HII EX PCDs in As Built INF if both name and GUID match.\r
+    #\r
+    #  @retval    list    HII EX PCDs\r
+    #\r
+    def _GetPcdsMaybeUsedByVfr(self):\r
+        if not self.SourceFileList:\r
+            return []\r
+\r
+        NameGuids = []\r
+        for SrcFile in self.SourceFileList:\r
+            if SrcFile.Ext.lower() != '.vfr':\r
+                continue\r
+            Vfri = os.path.join(self.OutputDir, SrcFile.BaseName + '.i')\r
+            if not os.path.exists(Vfri):\r
+                continue\r
+            VfriFile = open(Vfri, 'r')\r
+            Content = VfriFile.read()\r
+            VfriFile.close()\r
+            Pos = Content.find('efivarstore')\r
+            while Pos != -1:\r
+                #\r
+                # Make sure 'efivarstore' is the start of efivarstore statement\r
+                # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'\r
+                #\r
+                Index = Pos - 1\r
+                while Index >= 0 and Content[Index] in ' \t\r\n':\r
+                    Index -= 1\r
+                if Index >= 0 and Content[Index] != ';':\r
+                    Pos = Content.find('efivarstore', Pos + len('efivarstore'))\r
+                    continue\r
+                #\r
+                # 'efivarstore' must be followed by name and guid\r
+                #\r
+                Name = gEfiVarStoreNamePattern.search(Content, Pos)\r
+                if not Name:\r
+                    break\r
+                Guid = gEfiVarStoreGuidPattern.search(Content, Pos)\r
+                if not Guid:\r
+                    break\r
+                NameArray = ConvertStringToByteArray('L"' + Name.group(1) + '"')\r
+                NameGuids.append((NameArray, GuidStructureStringToGuidString(Guid.group(1))))\r
+                Pos = Content.find('efivarstore', Name.end())\r
+        if not NameGuids:\r
+            return []\r
+        HiiExPcds = []\r
+        for Pcd in self.PlatformInfo.Platform.Pcds.values():\r
+            if Pcd.Type != TAB_PCDS_DYNAMIC_EX_HII:\r
+                continue\r
+            for SkuName in Pcd.SkuInfoList:\r
+                SkuInfo = Pcd.SkuInfoList[SkuName]\r
+                Name = ConvertStringToByteArray(SkuInfo.VariableName)\r
+                Value = GuidValue(SkuInfo.VariableGuid, self.PlatformInfo.PackageList)\r
+                if not Value:\r
+                    continue\r
+                Guid = GuidStructureStringToGuidString(Value)\r
+                if (Name, Guid) in NameGuids and Pcd not in HiiExPcds:\r
+                    HiiExPcds.append(Pcd)\r
+                    break\r
+\r
+        return HiiExPcds\r
+\r
     ## Create AsBuilt INF file the module\r
     #\r
     def CreateAsBuiltInf(self):\r
@@ -2816,6 +3158,16 @@ class ModuleAutoGen(AutoGen):
                         break\r
                 if Found: break\r
 \r
+        VfrPcds = self._GetPcdsMaybeUsedByVfr()\r
+        for Pkg in self.PlatformInfo.PackageList:\r
+            if Pkg in Packages:\r
+                continue\r
+            for VfrPcd in VfrPcds:\r
+                if ((VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, 'DynamicEx') in Pkg.Pcds or\r
+                    (VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, 'Dynamic') in Pkg.Pcds):\r
+                    Packages += [Pkg]\r
+                    break\r
+\r
         ModuleType = self.ModuleType\r
         if ModuleType == 'UEFI_DRIVER' and self.DepexGenerated:\r
             ModuleType = 'DXE_DRIVER'\r
@@ -2824,14 +3176,30 @@ class ModuleAutoGen(AutoGen):
         if self.PcdIsDriver != '':\r
             DriverType = self.PcdIsDriver\r
 \r
+        Guid = self.Guid\r
+        MDefs = self.Module.Defines\r
+\r
         AsBuiltInfDict = {\r
           'module_name'                       : self.Name,\r
-          'module_guid'                       : self.Guid,\r
+          'module_guid'                       : Guid,\r
           'module_module_type'                : ModuleType,\r
-          'module_version_string'             : self.Version,\r
+          'module_version_string'             : [MDefs['VERSION_STRING']] if 'VERSION_STRING' in MDefs else [],\r
           'pcd_is_driver_string'              : [],\r
           'module_uefi_specification_version' : [],\r
           'module_pi_specification_version'   : [],\r
+          'module_entry_point'                : self.Module.ModuleEntryPointList,\r
+          'module_unload_image'               : self.Module.ModuleUnloadImageList,\r
+          'module_constructor'                : self.Module.ConstructorList,\r
+          'module_destructor'                 : self.Module.DestructorList,\r
+          'module_shadow'                     : [MDefs['SHADOW']] if 'SHADOW' in MDefs else [],\r
+          'module_pci_vendor_id'              : [MDefs['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs else [],\r
+          'module_pci_device_id'              : [MDefs['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs else [],\r
+          'module_pci_class_code'             : [MDefs['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs else [],\r
+          'module_pci_revision'               : [MDefs['PCI_REVISION']] if 'PCI_REVISION' in MDefs else [],\r
+          'module_build_number'               : [MDefs['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs else [],\r
+          'module_spec'                       : [MDefs['SPEC']] if 'SPEC' in MDefs else [],\r
+          'module_uefi_hii_resource_section'  : [MDefs['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs else [],\r
+          'module_uni_file'                   : [MDefs['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs else [],\r
           'module_arch'                       : self.Arch,\r
           'package_item'                      : ['%s' % (Package.MetaFile.File.replace('\\','/')) for Package in Packages],\r
           'binary_item'                       : [],\r
@@ -2843,7 +3211,12 @@ class ModuleAutoGen(AutoGen):
           'flags_item'                        : [],\r
           'libraryclasses_item'               : []\r
         }\r
-        AsBuiltInfDict['module_inf_version'] = '0x%08x' % self.AutoGenVersion\r
+\r
+        if self.AutoGenVersion > int(gInfSpecVersion, 0):\r
+            AsBuiltInfDict['module_inf_version'] = '0x%08x' % self.AutoGenVersion\r
+        else:\r
+            AsBuiltInfDict['module_inf_version'] = gInfSpecVersion\r
+\r
         if DriverType:\r
             AsBuiltInfDict['pcd_is_driver_string'] += [DriverType]\r
 \r
@@ -2889,6 +3262,8 @@ class ModuleAutoGen(AutoGen):
                 StartPos = Index\r
                 break\r
         AsBuiltInfDict['header_comments'] = '\n'.join(HeaderComments[StartPos:]).replace(':#', '://')\r
+        AsBuiltInfDict['tail_comments'] = '\n'.join(self.Module.TailComments)\r
+\r
         GenList = [\r
             (self.ProtocolList, self._ProtocolComments, 'protocol_item'),\r
             (self.PpiList, self._PpiComments, 'ppi_item'),\r
@@ -2969,28 +3344,42 @@ class ModuleAutoGen(AutoGen):
                 if PcdComments:\r
                     PcdItem = PcdComments + '\n  ' + PcdItem\r
                 AsBuiltInfDict['patchablepcd_item'].append(PcdItem)\r
-        for Pcd in Pcds:\r
+\r
+        HiiPcds = []\r
+        for Pcd in Pcds + VfrPcds:\r
             PcdComments = ''\r
             PcdCommentList = []\r
             HiiInfo = ''\r
+            SkuId = ''\r
             if Pcd.Type == TAB_PCDS_DYNAMIC_EX_HII:\r
                 for SkuName in Pcd.SkuInfoList:\r
                     SkuInfo = Pcd.SkuInfoList[SkuName]\r
+                    SkuId = SkuInfo.SkuId\r
                     HiiInfo = '## %s|%s|%s' % (SkuInfo.VariableName, SkuInfo.VariableGuid, SkuInfo.VariableOffset)\r
                     break\r
+            if SkuId:\r
+                #\r
+                # Don't generate duplicated HII PCD\r
+                #\r
+                if (SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in HiiPcds:\r
+                    continue\r
+                else:\r
+                    HiiPcds.append((SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
             if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
                 PcdCommentList = self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName][:]\r
             if HiiInfo:\r
                 UsageIndex = -1\r
+                UsageStr = ''\r
                 for Index, Comment in enumerate(PcdCommentList):\r
                     for Usage in UsageList:\r
                         if Comment.find(Usage) != -1:\r
+                            UsageStr = Usage\r
                             UsageIndex = Index\r
                             break\r
                 if UsageIndex != -1:\r
-                    PcdCommentList[UsageIndex] = PcdCommentList[UsageIndex] + ' ' + HiiInfo\r
+                    PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, '')) \r
                 else:\r
-                    PcdCommentList.append('## ' + HiiInfo)\r
+                    PcdCommentList.append('## UNDEFINED ' + HiiInfo)\r
             PcdComments = '\n  '.join(PcdCommentList)\r
             PcdEntry = Pcd.TokenSpaceGuidCName + '.' + Pcd.TokenCName\r
             if PcdComments:\r
@@ -2999,6 +3388,16 @@ class ModuleAutoGen(AutoGen):
         for Item in self.BuildOption:\r
           if 'FLAGS' in self.BuildOption[Item]:\r
             AsBuiltInfDict['flags_item'] += ['%s:%s_%s_%s_%s_FLAGS = %s' % (self.ToolChainFamily, self.BuildTarget, self.ToolChain, self.Arch, Item, self.BuildOption[Item]['FLAGS'].strip())]\r
+\r
+        # Generated LibraryClasses section in comments.\r
+        for Library in self.LibraryAutoGenList:\r
+            AsBuiltInfDict['libraryclasses_item'] += [Library.MetaFile.File.replace('\\', '/')]\r
+        \r
+        # Generated depex expression section in comments.\r
+        AsBuiltInfDict['depexsection_item'] = ''\r
+        DepexExpresion = self._GetDepexExpresionString()\r
+        if DepexExpresion:\r
+            AsBuiltInfDict['depexsection_item'] = DepexExpresion\r
         \r
         AsBuiltInf = TemplateString()\r
         AsBuiltInf.Append(gAsBuiltInfHeaderString.Replace(AsBuiltInfDict))\r
@@ -3013,6 +3412,10 @@ class ModuleAutoGen(AutoGen):
     #                                       dependent libraries will be created\r
     #\r
     def CreateMakeFile(self, CreateLibraryMakeFile=True):\r
+        # Ignore generating makefile when it is a binary module\r
+        if self.IsBinaryModule:\r
+            return\r
+\r
         if self.IsMakeFileCreated:\r
             return\r
 \r
@@ -3033,6 +3436,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
@@ -3046,6 +3454,9 @@ class ModuleAutoGen(AutoGen):
         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