Added from python source root
authorjwang36 <jwang36@7335b38e-4728-0410-8992-fb3ffe349368>
Fri, 13 Jul 2007 07:43:08 +0000 (07:43 +0000)
committerjwang36 <jwang36@7335b38e-4728-0410-8992-fb3ffe349368>
Fri, 13 Jul 2007 07:43:08 +0000 (07:43 +0000)
git-svn-id: https://buildtools.tianocore.org/svn/buildtools/trunk/BaseTools@325 7335b38e-4728-0410-8992-fb3ffe349368

74 files changed:
Source/Python/AutoGen/AutoGen.py [new file with mode: 0644]
Source/Python/AutoGen/BuildInfo.py [new file with mode: 0644]
Source/Python/AutoGen/GenC.py [new file with mode: 0644]
Source/Python/AutoGen/GenDepex.py [new file with mode: 0644]
Source/Python/AutoGen/GenMake.py [new file with mode: 0644]
Source/Python/AutoGen/StrGather.py [new file with mode: 0644]
Source/Python/AutoGen/UniClassObject.py [new file with mode: 0644]
Source/Python/AutoGen/__init__.py [new file with mode: 0644]
Source/Python/CalcDeps/__init__.py [new file with mode: 0644]
Source/Python/Common/BuildToolError.py [new file with mode: 0644]
Source/Python/Common/DataType.py [new file with mode: 0644]
Source/Python/Common/DecClassObject.py [new file with mode: 0644]
Source/Python/Common/Dictionary.py [new file with mode: 0644]
Source/Python/Common/DscClassObject.py [new file with mode: 0644]
Source/Python/Common/EdkIIWorkspace.py [new file with mode: 0644]
Source/Python/Common/EdkIIWorkspaceBuild.py [new file with mode: 0644]
Source/Python/Common/EdkLogger.py [new file with mode: 0644]
Source/Python/Common/Identification.py [new file with mode: 0644]
Source/Python/Common/InfClassObject.py [new file with mode: 0644]
Source/Python/Common/SequentialDict.py [new file with mode: 0644]
Source/Python/Common/String.py [new file with mode: 0644]
Source/Python/Common/TargetTxtClassObject.py [new file with mode: 0644]
Source/Python/Common/ToolDefClassObject.py [new file with mode: 0644]
Source/Python/Common/__init__.py [new file with mode: 0644]
Source/Python/CommonDataClass/CommonClass.py [new file with mode: 0644]
Source/Python/CommonDataClass/ModuleClass.py [new file with mode: 0644]
Source/Python/CommonDataClass/PackageClass.py [new file with mode: 0644]
Source/Python/CommonDataClass/PlatformClass.py [new file with mode: 0644]
Source/Python/CommonDataClass/__init__.py [new file with mode: 0644]
Source/Python/Ecc/__init__.py [new file with mode: 0644]
Source/Python/Fdb/__init__.py [new file with mode: 0644]
Source/Python/FixFlash/__init__.py [new file with mode: 0644]
Source/Python/GenFds/AprioriSection.py [new file with mode: 0644]
Source/Python/GenFds/Attribute.py [new file with mode: 0644]
Source/Python/GenFds/Capsule.py [new file with mode: 0644]
Source/Python/GenFds/CapsuleData.py [new file with mode: 0644]
Source/Python/GenFds/ComponentStatement.py [new file with mode: 0644]
Source/Python/GenFds/CompressSection.py [new file with mode: 0644]
Source/Python/GenFds/DataSection.py [new file with mode: 0644]
Source/Python/GenFds/EfiSection.py [new file with mode: 0644]
Source/Python/GenFds/Fd.py [new file with mode: 0644]
Source/Python/GenFds/FdfParser.py [new file with mode: 0644]
Source/Python/GenFds/Ffs.py [new file with mode: 0644]
Source/Python/GenFds/FfsFileStatement.py [new file with mode: 0644]
Source/Python/GenFds/FfsInfStatement.py [new file with mode: 0644]
Source/Python/GenFds/FrameworkToken.py [new file with mode: 0644]
Source/Python/GenFds/Fv.py [new file with mode: 0644]
Source/Python/GenFds/FvImageSection.py [new file with mode: 0644]
Source/Python/GenFds/GenFds.py [new file with mode: 0644]
Source/Python/GenFds/GenFdsGlobalVariable.py [new file with mode: 0644]
Source/Python/GenFds/GuidSection.py [new file with mode: 0644]
Source/Python/GenFds/Region.py [new file with mode: 0644]
Source/Python/GenFds/RegionData.py [new file with mode: 0644]
Source/Python/GenFds/Rule.py [new file with mode: 0644]
Source/Python/GenFds/RuleComplexFile.py [new file with mode: 0644]
Source/Python/GenFds/RuleSimpleFile.py [new file with mode: 0644]
Source/Python/GenFds/Section.py [new file with mode: 0644]
Source/Python/GenFds/UefiToken.py [new file with mode: 0644]
Source/Python/GenFds/UiSection.py [new file with mode: 0644]
Source/Python/GenFds/VerSection.py [new file with mode: 0644]
Source/Python/GenFds/Vtf.py [new file with mode: 0644]
Source/Python/GenFds/__init__.py [new file with mode: 0644]
Source/Python/InstallFar/__init__.py [new file with mode: 0644]
Source/Python/MkBOM/__init__.py [new file with mode: 0644]
Source/Python/MkFar/__init__.py [new file with mode: 0644]
Source/Python/TargetTool/__init__.py [new file with mode: 0644]
Source/Python/Trim/Trim.py [new file with mode: 0644]
Source/Python/UpdateFv/__init__.py [new file with mode: 0644]
Source/Python/WkSpace/__init__.py [new file with mode: 0644]
Source/Python/build/__init__.py [new file with mode: 0644]
Source/Python/build/build.py [new file with mode: 0644]
Source/Python/fpd2dsc/__init__.py [new file with mode: 0644]
Source/Python/msa2inf/__init__.py [new file with mode: 0644]
Source/Python/spd2dec/__init__.py [new file with mode: 0644]

diff --git a/Source/Python/AutoGen/AutoGen.py b/Source/Python/AutoGen/AutoGen.py
new file mode 100644 (file)
index 0000000..e07a45d
--- /dev/null
@@ -0,0 +1,919 @@
+#!/usr/bin/env python
+import sys
+import os
+import re
+import EdkLogger
+import os.path as path
+import imp
+import GenC
+import GenMake
+import GenDepex
+
+from EdkIIWorkspaceBuild import *
+from EdkIIWorkspace import *
+from DataType import *
+from BuildInfo import *
+from StrGather import *
+from BuildToolError import *
+
+#
+# generate AutoGen.c, AutoGen.h
+# parse unicode file and generate XXXXString.h, XXXXString.c
+# generate makefile
+#
+
+gPlatformDatabase = {}      # {arch : {dsc file path : PlatformBuildClassObject}}
+gModuleDatabase = {}        # {arch : {inf file path : ModuleBuildClassObject}}
+gPackageDatabase = {}       # {arch : {dec file path : PackageBuildClassObject}}
+gAutoGenDatabase = {}       # (module/package/platform obj, BuildTarget, ToolChain, Arch) : build info
+gWorkspace = None
+gWorkspaceDir = ""
+gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)")
+gMakeTypeMap = {"MSFT":"nmake", "GCC":"gmake"}
+
+def FindModuleOwnerPackage(module, pkgdb):
+    for pkg in pkgdb:
+        pkgDir = path.dirname(pkg)
+        if module.DescFilePath.find(pkgDir) == 0:
+            return pkgdb[pkg]
+    return None
+
+class AutoGen(object):
+
+    def __init__(self, moduleFile, platformFile, workspace, target, toolchain, arch):
+        global gModuleDatabase, gPackageDatabase, gPlatformDatabase, gAutoGenDatabase, gWorkspace, gWorkspaceDir
+
+        if gWorkspace == None:
+            gWorkspace = workspace
+        if gWorkspaceDir == "":
+            gWorkspaceDir = workspace.Workspace.WorkspaceDir
+
+        if gModuleDatabase == {}:
+            for a in workspace.Build:
+                gModuleDatabase[a] = gWorkspace.Build[a].ModuleDatabase
+        if gPackageDatabase == {}:
+            for a in workspace.Build:
+                gPackageDatabase[a] = gWorkspace.Build[a].PackageDatabase
+        if gPlatformDatabase == {}:
+            for a in workspace.Build:
+                gPlatformDatabase[a] = gWorkspace.Build[a].PlatformDatabase
+
+        self.ToolChain = toolchain
+        self.BuildTarget = target
+        self.IsMakefileCreated = False
+        self.IsAutoGenCodeCreated = False
+
+        key = (self.BuildTarget, self.ToolChain, str(platformFile))
+        if moduleFile == None:
+            #
+            # autogen for platform
+            #
+            self.PlatformBuildInfo = {}     # arch : PlatformBuildInfo Object
+            self.Platform = {}
+            self.IsPlatformAutoGen = True
+            if type(arch) == type([]):
+                self.Arch = arch
+            else:
+                self.Arch = [arch]
+                
+            self.Platform = {}
+            self.BuildInfo = {}
+            for a in self.Arch:
+                if a not in gPlatformDatabase or str(platformFile) not in gPlatformDatabase[a]:
+                    raise AutoGenError(msg="[%s] is not active platform, or %s is not supported!" % (platformFile, a))
+                p = gPlatformDatabase[a][str(platformFile)]
+                self.Platform[a] = p
+                self.BuildInfo[a] = self.GetPlatformBuildInfo(p, self.BuildTarget, self.ToolChain, a)
+            gAutoGenDatabase[key] = self
+            return
+        elif key not in gAutoGenDatabase:
+            gAutoGenDatabase[key] = AutoGen(None, platformFile, workspace, target, toolchain, arch)
+
+        #print "-------------",moduleFile,"----------------"
+        #
+        # autogen for module
+        #
+        self.IsPlatformAutoGen = False
+        if type(arch) == type([]):
+            if len(arch) > 1:
+                raise AutoGenError(msg="Cannot AutoGen a module for more than one platform objects at the same time!")
+            self.Arch = arch[0]
+        else:
+            self.Arch = arch
+
+        if self.Arch not in gPlatformDatabase or str(platformFile) not in gPlatformDatabase[arch]:
+            raise AutoGenError(msg="[%s] is not active platform, or %s is not supported!" % (platformFile, self.Arch))
+        if self.Arch not in gModuleDatabase or str(moduleFile) not in gModuleDatabase[self.Arch]:
+            raise AutoGenError(msg="[%s] for %s is not found in active platform [%s]!" % (moduleFile, self.Arch, platformFile))
+        self.Module = gModuleDatabase[self.Arch][str(moduleFile)]
+        self.Platform = gPlatformDatabase[arch][str(platformFile)]
+
+        self.Package = FindModuleOwnerPackage(self.Module, gPackageDatabase[arch])
+        if self.Package == None:
+            raise AutoGenError(msg="Cannot find owner package for [%s]!" % (moduleFile))
+
+        self.AutoGenC = GenC.AutoGenString()
+        self.AutoGenH = GenC.AutoGenString()
+
+        self.BuildInfo = None
+        self.GetModuleBuildInfo()
+        gAutoGenDatabase[self.BuildTarget, self.ToolChain, self.Arch, self.Module] = self
+
+    def GetModuleBuildInfo(self):
+        key = (self.BuildTarget, self.ToolChain, self.Arch, self.Module)
+        if key in gAutoGenDatabase:
+            self.BuildInfo = gAutoGenDatabase[key].BuildInfo
+            self.IsAutoGenCodeCreated = gAutoGenDatabase[key].IsAutoGenCodeCreated
+            self.IsMakefileCreated = gAutoGenDatabase[key].IsMakefileCreated
+            return gAutoGenDatabase[key].BuildInfo
+        
+        info = ModuleBuildInfo(self.Module)
+        self.BuildInfo = info
+        info.PlatformInfo = self.GetPlatformBuildInfo(self.Platform, self.BuildTarget, self.ToolChain, self.Arch)
+
+        key = (self.Package, self.BuildTarget, self.ToolChain, self.Arch)
+        if key in gAutoGenDatabase:
+            info.PackageInfo = gAutoGenDatabase[key]
+        else:
+            info.PackageInfo = PackageBuildInfo(self.Package)
+            self.InitPackageBuildInfo(info.PackageInfo)
+            gAutoGenDatabase[key] = info.PackageInfo
+
+        # basic information
+        info.WorkspaceDir = gWorkspaceDir
+        info.BuildTarget = self.BuildTarget
+        info.ToolChain = self.ToolChain
+        info.Arch = self.Arch
+        info.IsBinary = False
+        info.BaseName = self.Module.BaseName
+        info.FileBase, info.FileExt = path.splitext(path.basename(self.Module.DescFilePath))
+        info.SourceDir = path.dirname(self.Module.DescFilePath)
+        info.BuildDir = os.path.join(info.PlatformInfo.BuildDir,
+                                     info.Arch,
+                                     info.SourceDir,
+                                     info.FileBase)
+        info.OutputDir = os.path.join(info.BuildDir, "OUTPUT")
+        info.DebugDir = os.path.join(info.BuildDir, "DEBUG")
+        info.MakefileDir = info.BuildDir
+        if os.path.isabs(info.BuildDir):
+            CreateDirectory(info.OutputDir)
+            CreateDirectory(info.DebugDir)
+        else:
+            CreateDirectory(os.path.join(gWorkspaceDir, info.OutputDir))
+            CreateDirectory(os.path.join(gWorkspaceDir, info.DebugDir))
+
+        for type in self.Module.CustomMakefile:
+            makeType = gMakeTypeMap[type]
+            info.CustomMakefile[makeType] = os.path.join(info.SourceDir, self.Module.CustomMakefile[type])
+
+        if self.Module.LibraryClass != None and self.Module.LibraryClass != "":
+            info.IsLibrary = True
+            info.DependentLibraryList = []
+        else:
+            info.IsLibrary = False
+            info.DependentLibraryList = self.GetSortedLibraryList()
+
+        info.DependentPackageList = self.GetDependentPackageList()
+
+        info.BuildOption = self.GetModuleBuildOption(info.PlatformInfo)
+
+        info.PcdIsDriver = self.Module.PcdIsDriver
+        info.PcdList = self.GetPcdList(info.DependentLibraryList)
+        info.GuidList = self.GetGuidList()
+        info.ProtocolList = self.GetProtocolGuidList()
+        info.PpiList = self.GetPpiGuidList()
+        info.MacroList = self.GetMacroList()
+        info.DepexList = self.GetDepexTokenList(info)
+        
+        info.IncludePathList = [info.SourceDir, info.DebugDir]
+        info.IncludePathList.extend(self.GetIncludePathList(info.DependentPackageList))
+
+        info.SourceFileList = self.GetBuildFileList(info.PlatformInfo)
+        info.AutoGenFileList = self.GetAutoGenFileList(info)
+
+        return info
+
+    def InitPackageBuildInfo(self, info):
+        info.SourceDir = path.dirname(info.Package.DescFilePath)
+        info.IncludePathList.append(info.SourceDir)
+        for inc in info.Package.Includes:
+            info.IncludePathList.append(os.path.join(info.SourceDir, inc))
+
+    def GetPlatformBuildInfo(self, platform, target, toolchain, arch):
+        key = target, toolchain, platform
+        platformAutoGen = None
+        if key in gAutoGenDatabase:
+            platformAutoGen = gAutoGenDatabase[key]
+            if arch in platformAutoGen.BuildInfo:
+                return platformAutoGen.BuildInfo[arch]
+
+        info = PlatformBuildInfo(platform)
+
+        ruleFile = gWorkspace.Workspace.WorkspaceFile(r'Conf\build_rule.txt')
+        info.BuildRule = imp.load_source("BuildRule", ruleFile)
+
+        info.Arch = arch
+        info.ToolChain = self.ToolChain
+        info.BuildTarget = self.BuildTarget
+
+        info.WorkspaceDir = gWorkspace.Workspace.WorkspaceDir
+        info.SourceDir = path.dirname(platform.DescFilePath)
+        info.OutputDir = platform.OutputDirectory
+        info.BuildDir = path.join(info.OutputDir, self.BuildTarget + "_" + self.ToolChain)
+        info.MakefileDir = info.BuildDir
+        if platform.FlashDefinition != "":
+            info.FdfFileList.append(path.join(gWorkspaceDir, platform.FlashDefinition))
+
+        info.DynamicPcdList = self.GetDynamicPcdList(platform, arch)
+        info.PcdTokenNumber = self.GeneratePcdTokenNumber(platform, info.DynamicPcdList)
+        info.PackageList = gPackageDatabase[arch].values()
+
+        self.ProcessToolDefinition(info)
+
+        if platformAutoGen != None:
+            platformAutoGen.BuildInfo = info
+        return info
+
+    def GetDepexTokenList(self, info):
+        dxs = self.Module.Depex
+        #
+        # Append depex from dependent libraries
+        #
+        for lib in info.DependentLibraryList:
+            if lib.Depex != "":
+                dxs += " AND " + lib.Depex
+        if dxs == "":
+            return []
+
+        tokenList = gDepexTokenPattern.findall(self.Module.Depex)
+        for i in range(0, len(tokenList)):
+            token = tokenList[i].strip()
+            if token.endswith(".inf"):  # module file name
+                moduleFile = os.path.normpath(token)
+                token = gModuleDatabase[moduleFile].Guid
+            elif token.upper() in GenDepex.DependencyExpression.SupportedOpcode: # Opcode name
+                token = token.upper()
+            else:   # GUID C Name
+                guidCName = token
+                for p in info.DependentPackageList:
+                    if guidCName in p.Protocols:
+                        token = p.Protocols[guidCName]
+                        break
+                    elif guidCName in p.Ppis:
+                        token = p.Ppis[guidCName]
+                        break
+                    elif guidCName in p.Guids:
+                        token = p.Guids[guidCName]
+                        break
+                else:
+                    raise AutoGenError(msg="%s used in module %s cannot be found in any package!" % (guidCName, info.Name))
+            tokenList[i] = token
+        return tokenList
+
+    def GetMacroList(self):
+        return ["%s %s" % (name, self.Module.Specification[name]) for name in self.Module.Specification]
+    
+    def ProcessToolDefinition(self, info):
+        toolDefinition = gWorkspace.ToolDef.ToolsDefTxtDictionary
+        toolCodeList = gWorkspace.ToolDef.ToolsDefTxtDatabase["COMMAND_TYPE"]
+        for tool in toolCodeList:
+            keyBaseString = "%s_%s_%s_%s" % (info.BuildTarget, info.ToolChain, info.Arch, tool)
+            key = "%s_NAME" % keyBaseString
+            if key not in toolDefinition:
+                continue
+            name = toolDefinition[key]
+            
+            key = "%s_PATH" % keyBaseString
+            if key in toolDefinition:
+                path = toolDefinition[key]
+            else:
+                path = ""
+
+            key = "%s_FAMILY" % keyBaseString
+            if key in toolDefinition:
+                family = toolDefinition[key]
+            else:
+                family = ""
+
+            key = "%s_FLAGS" % keyBaseString
+            if key in toolDefinition:
+                option = toolDefinition[key]
+            else:
+                option = ""
+                
+            key = "%s_DPATH" % keyBaseString
+            if key in toolDefinition:
+                dll = toolDefinition[key]
+            else:
+                dll = ""
+                
+            key = "%s_SPATH" % keyBaseString
+            if key in toolDefinition:
+                lib = toolDefinition[key]
+            else:
+                lib = ""
+
+            info.ToolPath[tool] = os.path.join(path, name)
+            info.ToolDynamicLib[tool] = dll
+            info.ToolStaticLib[tool] = lib
+            info.ToolChainFamily[tool] = family
+            info.DefaultToolOption[tool] = option
+
+        if self.IsPlatformAutoGen:
+            buildOptions = self.Platform[info.Arch].BuildOptions
+        else:
+            buildOptions = self.Platform.BuildOptions
+
+        for key in buildOptions:
+            family = key[0]
+            target, tag, arch, tool, attr = key[1].split("_")
+            if tool not in info.ToolPath:
+                continue
+            if family != None and family != "" and family != info.ToolChainFamily[tool]:
+                continue
+            if target == "*" or target == info.BuildTarget:
+                if tag == "*" or tag == info.ToolChain:
+                    if arch == "*" or arch == info.Arch:
+                        info.BuildOption[tool] = buildOptions[key]
+        for tool in info.DefaultToolOption:
+            if tool not in info.BuildOption:
+                info.BuildOption[tool] = ""
+
+    def GetModuleBuildOption(self, platformInfo):
+        buildOption = self.Module.BuildOptions
+        optionList = {}
+        for key in buildOption:
+            family = key[0]
+            target, tag, arch, tool, attr = key[1].split("_")
+            if tool not in platformInfo.ToolPath:
+                continue
+            if family != None and family != "" and family != platformInfo.ToolChainFamily[tool]:
+                continue
+            if target == "*" or target == self.BuildTarget:
+                if tag == "*" or tag == self.ToolChain:
+                    if arch == "*" or arch == self.Arch:
+                        optionList[tool] = buildOption[key]
+        for tool in platformInfo.DefaultToolOption:
+            if tool not in optionList:
+                optionList[tool] = ""
+        return optionList
+    
+    def GetBuildFileList(self, platformInfo):
+        buildRule = platformInfo.BuildRule
+        buildFileList = []
+        fileList = self.Module.Sources
+        for f in fileList:
+            if f.TagName != "" and f.TagName != self.ToolChain:
+                continue
+            if f.ToolCode != "" and f.ToolCode not in platformInfo.ToolPath:
+                continue
+
+            dir = path.dirname(f.SourceFile)
+            if dir != "":
+                dir = path.join(self.BuildInfo.SourceDir, dir)
+                if dir not in self.BuildInfo.IncludePathList:
+                    self.BuildInfo.IncludePathList.insert(0, dir)
+
+            # skip unknown file
+            base, ext = path.splitext(f.SourceFile)
+            if ext not in buildRule.FileTypeMapping:
+                EdkLogger.verbose("Don't know how to process file %s (%s)" % (f.SourceFile, ext))
+                continue
+            
+            # skip file which needs a tool having no matching toolchain family
+            fileType = buildRule.FileTypeMapping[ext]
+            if f.ToolCode != "":
+                toolCode = f.ToolCode
+            else:
+                toolCode = buildRule.ToolCodeMapping[fileType]
+            # get the toolchain family from tools definition
+            if f.ToolChainFamily != "" and f.ToolChainFamily != platformInfo.ToolChainFamily[toolCode]:
+                EdkLogger.verbose("File %s for toolchain family %s is not supported" % (f.SourceFile, f.ToolChainFamily))
+                continue
+            if fileType == "Unicode-Text":
+                self.BuildInfo.UnicodeFileList.append(os.path.join(gWorkspaceDir, self.BuildInfo.SourceDir, f.SourceFile))
+            buildFileList.append(f.SourceFile)
+        return buildFileList
+
+    def GetDependentPackageList(self):
+        if self.Package not in self.Module.Packages:
+            self.Module.Packages.insert(0, str(self.Package))
+
+        if self.Arch not in gPackageDatabase:
+            raise AutoGenError(msg="[%s] is not supported!")
+        packageDatabase = gPackageDatabase[self.Arch]
+
+        packageList = []
+        for pf in self.Module.Packages:
+            if pf in packageList:
+                continue
+            if pf not in packageDatabase:
+                raise AutoGenError(FILE_NOT_FOUND, name=pf)
+            packageList.append(packageDatabase[pf])
+        return packageList
+
+    def GetAutoGenFileList(self, buildInfo):
+        GenC.CreateCode(buildInfo, self.AutoGenC, self.AutoGenH)
+        fileList = []
+        if self.AutoGenC.String != "":
+            fileList.append("AutoGen.c")
+        if self.AutoGenH.String != "":
+            fileList.append("AutoGen.h")
+            #print self.AutoGenH.String
+        return fileList
+    
+    def GetSortedLibraryList(self):
+        moduleType = self.Module.ModuleType
+        libraryConsumerList = [self.Module]
+        
+        libraryList         = []
+        constructor         = []
+        consumedByList      = {}
+        libraryClassList    = []
+
+        EdkLogger.verbose("")
+        EdkLogger.verbose("Library instances of module [%s]:" % str(self.Module))
+        while len(libraryConsumerList) > 0:
+            module = libraryConsumerList.pop()
+            for libc, libf in module.LibraryClasses.iteritems():
+                if moduleType not in libc:
+                    EdkLogger.debug(EdkLogger.DEBUG_5, "\t%s for module type %s is not supported" % libc)
+                    continue
+                if libf == None or libf == "":
+                    EdkLogger.info("\tLibrary instance of library class %s is not found" % libc[0])
+                    continue
+                
+                libm = gModuleDatabase[self.Arch][libf]
+                if libm not in libraryList and libc not in libraryClassList:
+                    libraryConsumerList.append(libm)
+                    libraryList.append(libm)
+                    libraryClassList.append(libc)
+                    EdkLogger.verbose("\t" + libc[0] + " : " + str(libm))
+
+                if libm.ConstructorList != [] and libm not in constructor:
+                    constructor.append(libm)
+                    
+                if libm not in consumedByList:
+                    consumedByList[libm] = []
+                if module != self.Module:
+                    if module in consumedByList[libm]:
+                        continue
+                    consumedByList[libm].append(module)
+        #
+        # Initialize the sorted output list to the empty set
+        #
+        SortedLibraryList = []
+        #
+        # Q <- Set of all nodes with no incoming edges
+        #
+        Q = []
+        for m in libraryList:
+            if consumedByList[m] == []:
+                Q.insert(0, m)
+        #
+        # while Q is not empty do
+        #
+        while Q != []:
+            #
+            # remove node n from Q
+            #
+            n = Q.pop()
+            #
+            # output n
+            #
+            SortedLibraryList.append(n)
+            #
+            # for each node m with an edge e from n to m do
+            #
+            for m in libraryList:
+                if n not in consumedByList[m]:
+                    continue
+                #
+                # remove edge e from the graph
+                #
+                consumedByList[m].remove(n)
+                #
+                # If m has no other incoming edges then
+                #
+                if consumedByList[m] == []:
+                    #
+                    # insert m into Q
+                    #
+                    Q.insert(0,m)
+
+            EdgeRemoved = True
+            while Q == [] and EdgeRemoved:
+                EdgeRemoved = False
+                #
+                # for each node m with a constructor
+                #
+                for m in libraryList:
+                    if m in constructor:
+                        #
+                        # for each node n without a constructor with an edge e from m to n
+                        #
+                        for n in consumedByList[m]:
+                            if n not in constructor:
+                                #
+                                # remove edge e from the graph
+                                #
+                                consumedByList[m].remove(n)
+                                EdgeRemoved = True
+                                if consumedByList[m] == []:
+                                    #
+                                    # insert m into Q
+                                    #
+                                    Q.insert(0,m)
+                                    break
+                    if Q != []:
+                        break
+
+        #
+        # if any remaining node m in the graph has a constructor and an incoming edge, then the graph has a cycle
+        #
+        for m in libraryList:
+            if consumedByList[m] != [] and m in constructor:
+                errorMessage = 'Module library [%s] with constructors have a cycle:\n\t' % str(m)
+                errorMessage += "\n\tconsumed by ".join([str(l) for l in consumedByList[m]])
+                raise AutoGenError(msg=errorMessage)
+            if m not in SortedLibraryList:
+                SortedLibraryList.append(m)
+
+        #
+        # Build the list of constructor and destructir names
+        # The DAG Topo sort produces the destructor order, so the list of constructors must generated in the reverse order
+        #
+        SortedLibraryList.reverse()
+        return SortedLibraryList
+
+    def GetDynamicPcdList(self, platform, arch):
+        pcdList = []
+        for f in gModuleDatabase[arch]:
+            m = gModuleDatabase[arch][f]
+            for key in m.Pcds:
+                if key not in platform.Pcds:
+                    raise AutoGenError(msg="PCD [%s %s] not found in platform" % key)
+                mPcd = m.Pcds[key]
+                pPcd = platform.Pcds[key]
+                if pPcd.Type in GenC.gDynamicPcd + GenC.gDynamicExPcd:
+                    if m.ModuleType in ["PEIM", "PEI_CORE"]:
+                        pPcd.Phase = "PEI"
+                    if pPcd not in pcdList:
+                        pPcd.DatumType = mPcd.DatumType
+                        pcdList.append(pPcd)
+        return pcdList
+
+    def GeneratePcdTokenNumber(self, platform, dynamicPcdList):
+        pcdTokenNumber = {}
+        tokenNumber = 1
+        for pcd in dynamicPcdList:
+            #print "@@@",tokenNumber,"=",pcd.TokenCName, pcd.TokenSpaceGuidCName, pcd.DatumType
+            pcdTokenNumber[pcd.TokenCName, pcd.TokenSpaceGuidCName] = tokenNumber
+            tokenNumber += 1
+
+        platformPcds = platform.Pcds
+        for key in platformPcds:
+            pcd = platformPcds[key]
+            #print "###",key
+            if key not in pcdTokenNumber:
+                pcdTokenNumber[key] = tokenNumber
+                tokenNumber += 1
+        return pcdTokenNumber
+
+    def GetPcdList(self, dependentLibraryList):
+        platformPcds = self.Platform.Pcds
+
+        pcdList = []
+        for m in dependentLibraryList + [self.Module]:
+            for pcdKey in m.Pcds:
+                pcd = m.Pcds[pcdKey]
+                if (pcd.Type in GenC.gDynamicPcd + GenC.gDynamicExPcd) and self.Module.ModuleType in ["PEIM", "PEI_CORE"]:
+                    #platformPcds[pcdKey].Phase = "PEI"
+                    pcd.Phase = "PEI"
+                if pcd not in pcdList:
+                    pcdList.append(pcd)
+        return pcdList
+
+    def GetGuidList(self):
+        packageListString = "\n\t".join([p.PackageName for p in self.BuildInfo.DependentPackageList])
+        guid = {}
+        Key = ""
+        for Key in self.Module.Guids:
+            for p in self.BuildInfo.DependentPackageList:
+                if Key in p.Guids:
+                    guid[Key] = p.Guids[Key]
+                    break
+                if Key in p.Protocols:
+                    guid[Key] = p.Protocols[Key]
+                    break
+                if Key in p.Ppis:
+                    guid[Key] = p.Ppis[Key]
+                    break
+            else:
+                raise AutoGenError(msg='GUID [%s] used by [%s] cannot be found in dependent packages:\n\t%s' % (Key, self.BuildInfo.Name, packageListString))
+
+        for lib in self.BuildInfo.DependentLibraryList:
+            if lib.Guids == []:
+                continue
+
+            for Key in lib.Guids:
+                for p in lib.Packages:
+                    # print gPackageDatabase
+                    p = gPackageDatabase[self.Arch][p]
+                    if Key in p.Guids:
+                        guid[Key] = p.Guids[Key]
+                        break
+                    if Key in p.Protocols:
+                        guid[Key] = p.Protocols[Key]
+                        break
+                    if Key in p.Ppis:
+                        guid[Key] = p.Ppis[Key]
+                        break
+                else:
+                    raise AutoGenError(msg='GUID [%s] used by [%s] cannot be found in dependent packages:\n\t%s' % (Key, lib.BaseName, packageListString))
+        return guid
+
+    def GetProtocolGuidList(self):
+        packageListString = "\n\t".join([p.PackageName for p in self.BuildInfo.DependentPackageList])
+        guid = {}
+        Key = ""
+        for Key in self.Module.Protocols:
+            for p in self.BuildInfo.DependentPackageList:
+                    if Key in p.Guids:
+                        guid[Key] = p.Guids[Key]
+                        break
+                    if Key in p.Protocols:
+                        guid[Key] = p.Protocols[Key]
+                        break
+                    if Key in p.Ppis:
+                        guid[Key] = p.Ppis[Key]
+                        break
+            else:
+                raise AutoGenError(msg='Protocol [%s] used by [%s] cannot be found in dependent packages:\n\t%s' % (Key, self.BuildInfo.Name, packageListString))
+
+        for lib in self.BuildInfo.DependentLibraryList:
+            if lib.Protocols == []:
+                continue
+            for Key in lib.Protocols:
+                for p in lib.Packages:
+                    p = gPackageDatabase[self.Arch][p]
+                    if Key in p.Guids:
+                        guid[Key] = p.Guids[Key]
+                        break
+                    if Key in p.Protocols:
+                        guid[Key] = p.Protocols[Key]
+                        break
+                    if Key in p.Ppis:
+                        guid[Key] = p.Ppis[Key]
+                        break
+                else:
+                    raise AutoGenError(msg='Protocol [%s] used by [%s] cannot be found in dependent packages:\n\t%s' % (Key, lib.BaseName, packageListString))
+
+        return guid
+
+    def GetPpiGuidList(self):
+        packageListString = "\n\t".join([p.PackageName for p in self.BuildInfo.DependentPackageList])
+        guid = {}
+        Key = ""
+        for Key in self.Module.Ppis:
+            for p in self.BuildInfo.DependentPackageList:
+                if Key in p.Guids:
+                    guid[Key] = p.Guids[Key]
+                    break
+                if Key in p.Protocols:
+                    guid[Key] = p.Protocols[Key]
+                    break
+                if Key in p.Ppis:
+                    guid[Key] = p.Ppis[Key]
+                    break
+            else:
+                raise AutoGenError(msg='PPI [%s] used by [%s] cannot be found in dependent packages:\n\t%s' % (Key, self.BuildInfo.Name, packageListString))
+
+        for lib in self.BuildInfo.DependentLibraryList:
+            if lib.Ppis == []:
+                continue
+            for Key in lib.Ppis:
+                for p in lib.Packages:
+                    p = gPackageDatabase[self.Arch][p]
+                    if Key in p.Guids:
+                        guid[Key] = p.Guids[Key]
+                        break
+                    if Key in p.Protocols:
+                        guid[Key] = p.Protocols[Key]
+                        break
+                    if Key in p.Ppis:
+                        guid[Key] = p.Ppis[Key]
+                        break
+                else:
+                    raise AutoGenError(msg='PPI [%s] used by [%s] cannot be found in dependent packages:\n\t%s' % (Key, lib.BaseName, packageListString))
+        return guid
+
+    def GetIncludePathList(self, dependentPackageList):
+        includePathList = []
+        for inc in self.Module.Includes:
+            includePathList.append(inc)
+            
+        for package in dependentPackageList:
+            packageDir = path.dirname(package.DescFilePath)
+            includePathList.append(packageDir)
+            for inc in package.Includes:
+                inc = os.path.join(packageDir, inc)
+                if inc not in includePathList:
+                    includePathList.append(inc)
+        return includePathList
+
+    def CreateMakefile(self, filePath=None):
+        myBuildOption = {
+            "ENABLE_PCH"        :   False,
+            "ENABLE_LOCAL_LIB"  :   True,
+        }
+        if self.IsMakefileCreated:
+            return
+
+        if self.IsPlatformAutoGen:
+            for arch in self.BuildInfo:
+                info = self.BuildInfo[arch]
+                for moduleFile in info.Platform.Modules:
+                    key = (info.BuildTarget, info.ToolChain, arch, moduleFile)
+                    moduleAutoGen = None
+                    if key not in gAutoGenDatabase:
+                        moduleAutoGen = AutoGen(moduleFile, info.Platform, gWorkspace,
+                                                info.BuildTarget, info.ToolChain, info.Arch)
+                    else:
+                        moduleAutoGen = gAutoGenDatabase[key]
+                    moduleAutoGen.CreateMakefile()
+        else:
+            platformInfo = self.BuildInfo.PlatformInfo
+            if not self.BuildInfo.IsLibrary:
+                if self not in platformInfo.ModuleAutoGenList:
+                    platformInfo.ModuleAutoGenList.append(self)
+            elif self not in platformInfo.LibraryAutoGenList:
+                platformInfo.LibraryAutoGenList.append(self)
+
+            for lib in self.BuildInfo.DependentLibraryList:
+                EdkLogger.debug(EdkLogger.DEBUG_2, "###" + str(lib))
+                key = (self.BuildTarget, self.ToolChain, self.Arch, lib)
+                libraryAutoGen = None
+                if key not in gAutoGenDatabase:
+                    libraryAutoGen = AutoGen(lib, self.Platform, gWorkspace,
+                                             self.BuildTarget, self.ToolChain, self.Arch)
+                else:
+                    libraryAutoGen = gAutoGenDatabase[key]
+                if libraryAutoGen not in self.BuildInfo.LibraryAutoGenList:
+                    self.BuildInfo.LibraryAutoGenList.append(libraryAutoGen)
+                libraryAutoGen.CreateMakefile()
+
+            makefile = GenMake.Makefile(self.BuildInfo, myBuildOption)
+            f = makefile.Generate()
+            self.IsMakefileCreated = True
+            EdkLogger.info("Generated [%s] for module %s" % (path.basename(f), self.BuildInfo.Name))
+            return f
+
+        makefile = GenMake.Makefile(self.BuildInfo, myBuildOption)
+        f = makefile.Generate()
+        self.IsMakefileCreated = True
+        EdkLogger.info("Generated [%s] for platform %s" % (path.basename(f), self.BuildInfo[self.Arch[0]].Name))
+
+        return f
+
+    def CreateAutoGenFile(self, filePath=None):
+        if self.IsAutoGenCodeCreated:
+            return
+        
+        if self.IsPlatformAutoGen:
+            for arch in self.BuildInfo:
+                info = self.BuildInfo[arch]
+                for moduleFile in info.Platform.Modules:
+                    key = (info.BuildTarget, info.ToolChain, arch, moduleFile)
+                    moduleAutoGen = None
+                    if key not in gAutoGenDatabase:
+                        moduleAutoGen = AutoGen(moduleFile, info.Platform, gWorkspace,
+                                                info.BuildTarget, info.ToolChain, info.Arch)
+                    else:
+                        moduleAutoGen = gAutoGenDatabase[key]
+                    moduleAutoGen.CreateAutoGenFile()
+            print
+        else:
+            platformInfo = self.BuildInfo.PlatformInfo
+            if not self.BuildInfo.IsLibrary and self not in platformInfo.ModuleAutoGenList:
+                platformInfo.ModuleAutoGenList.append(self)
+            elif self.BuildInfo.IsLibrary and self not in platformInfo.LibraryAutoGenList:
+                platformInfo.LibraryAutoGenList.append(self)
+
+            for lib in self.BuildInfo.DependentLibraryList:
+                key = (self.BuildTarget, self.ToolChain, self.Arch, lib)
+                libraryAutoGen = None
+                if key not in gAutoGenDatabase:
+                    libraryAutoGen = AutoGen(lib, self.Platform, gWorkspace,
+                                             self.BuildTarget, self.ToolChain, self.Arch)
+                else:
+                    libraryAutoGen = gAutoGenDatabase[key]
+                if libraryAutoGen not in self.BuildInfo.LibraryAutoGenList:
+                    self.BuildInfo.LibraryAutoGenList.append(libraryAutoGen)
+                libraryAutoGen.CreateAutoGenFile()
+
+            autoGenList = GenC.Generate(os.path.join(self.BuildInfo.WorkspaceDir, self.BuildInfo.DebugDir),
+                                        self.AutoGenC, self.AutoGenH)
+                          
+            if self.BuildInfo.DepexList != []:
+                dpx = GenDepex.DependencyExpression(self.BuildInfo.DepexList, self.BuildInfo.ModuleType)
+                dpxFile = dpx.Generate(os.path.join(gWorkspaceDir, self.BuildInfo.OutputDir, self.BuildInfo.Name + ".depex"))
+                autoGenList.append(dpxFile)
+
+            self.IsAutoGenCodeCreated = True
+            EdkLogger.info("Generated [%s] files for module %s" % (" ".join([path.basename(f) for f in autoGenList]), self.BuildInfo.Name))
+
+            return autoGenList
+
+# This acts like the main() function for the script, unless it is 'import'ed into another
+# script.
+if __name__ == '__main__':
+    print "Running Operating System =", sys.platform
+    ewb = WorkspaceBuild()
+    #print ewb.Build.keys()
+
+    myArch = ewb.Build["IA32"].Arch
+    print myArch
+
+    myBuild = ewb.Build["IA32"]
+
+    myWorkspace = ewb
+    apf = os.path.normpath(ewb.TargetTxt.TargetTxtDictionary["ACTIVE_PLATFORM"][0])
+    myPlatform = myBuild.PlatformDatabase[os.path.normpath(apf)]
+
+    #LoadBuildRule(myWorkspace.Workspace.WorkspaceFile('Tools/Conf/build.rule'))
+
+    myToolchain = ewb.TargetTxt.TargetTxtDictionary["TOOL_CHAIN_TAG"][0]
+    #print myToolchain
+
+    myBuildTarget = ewb.TargetTxt.TargetTxtDictionary["TARGET"][0]
+    #print myBuildTarget
+
+    myBuildOption = {
+        "ENABLE_PCH"        :   False,
+        "ENABLE_LOCAL_LIB"  :   True,
+    }
+    
+    def PrintAutoGen(ag):
+        bi = ag.ModuleBuildInfo
+
+        print " WorkSpaceDir =",bi.WorkspaceDir
+        print " SourceDir =",bi.SourceDir
+        print " Is Library =",bi.IsLibrary
+        print " BaseName =",bi.BaseName
+        print " FileBase =",bi.FileBase
+        print " FileExt =",bi.FileExt
+        print " BuildDir =",bi.BuildDir
+        print " OutputDir =",bi.OutputDir
+        print " DebugDir =",bi.DebugDir
+        print " MakefileDir =",bi.MakefileDir
+
+        print " Include Path:","\n   ","\n    ".join(bi.InclduePathList)
+        print " SourceFileList:","\n   ","\n    ".join(bi.SourceFileList)
+
+        print " BuildOption:","\n   ","\n    ".join(["%s = %s" % (tool,bi.BuildOption[tool]) for tool in bi.BuildOption])
+        print " PcdList:","\n   ","\n    ".join([pcd.TokenCName for pcd in bi.PcdList])
+        print " GuidList:","\n   ","\n    ".join(bi.GuidList)
+        print " ProtocolList:","\n   ","\n    ".join(bi.ProtocolList)
+        print " PpiList:","\n   ","\n    ".join(bi.PpiList)
+        print " LibraryList:","\n   ","\n    ".join([str(l) for l in bi.DependentLibraryList])
+
+        print
+
+##        for key in gAutoGenDatabase:
+##            if str(myPlatform) == str(key[0]):
+##                pi = gAutoGenDatabase[key]
+##                print " BuildDir =",pi.BuildDir
+##                print " OutputDir =",pi.OutputDir
+##                print " DebugDir =",pi.DebugDir
+##                print " LibraryDir =",pi.LibraryDir
+##                print " FvDir =",pi.FvDir
+##                print " MakefileDir =",pi.MakefileDir
+##                print " PcdTokenNumber:","\n   ","\n    ".join(["%s = %s" % (pcd,pi.PcdTokenNumber[pcd]) for pcd in pi.PcdTokenNumber])
+##                print " DynamicPcdList:","\n   ","\n    ".join([str(pcd) for pcd in pi.DynamicPcdList])
+##
+##                print " ToolPath:","\n   ","\n    ".join(["%s = %s" % (tool,pi.ToolPath[tool]) for tool in pi.ToolPath])
+##                print " ToolDynamicLib:","\n   ","\n    ".join(["%s = %s" % (tool,pi.ToolDynamicLib[tool]) for tool in pi.ToolDynamicLib])
+##                print " ToolStaticLib:","\n   ","\n    ".join(["%s = %s" % (tool,pi.ToolStaticLib[tool]) for tool in pi.ToolStaticLib])
+##                print " ToolChainFamily:","\n   ","\n    ".join(["%s = %s" % (tool,pi.ToolChainFamily[tool]) for tool in pi.ToolChainFamily])
+##                print " BuildOption:","\n   ","\n    ".join(["%s = %s" % (tool,pi.BuildOption[tool]) for tool in pi.BuildOption])
+##                print " DefaultToolOption:","\n   ","\n    ".join(["%s = %s" % (tool,pi.DefaultToolOption[tool]) for tool in pi.DefaultToolOption])
+
+    for mf in myBuild.ModuleDatabase:
+        #mf = "MdePkg\\Library\\BaseLib\\BaseLib.inf"
+        #if mf in myPlatform.Modules and mf in myBuild.ModuleDatabase:
+        #print mf
+        myModule = myBuild.ModuleDatabase[mf]
+        ag = AutoGen(myModule, myPlatform, myWorkspace, myBuildTarget, myToolchain, myArch)
+        ag.CreateAutoGenFile()
+        ag.CreateMakefile()
+
+        #PrintAutoGen(ag)
+##        for lib in ag.ModuleBuildInfo.DependentLibraryList:
+##            ag = AutoGen(lib, myPlatform, myWorkspace, myArch, myToolchain, myBuildTarget)
+##            ag.CreateAutoGenFile()
+##            ag.CreateMakefile()
+##            #PrintAutoGen(ag)
+    platformAutoGen = AutoGen(None, apf, myWorkspace, myBuildTarget, myToolchain, myWorkspace.SupArchList)
+    platformAutoGen.CreateAutoGenFile()
+    platformAutoGen.CreateMakefile()
diff --git a/Source/Python/AutoGen/BuildInfo.py b/Source/Python/AutoGen/BuildInfo.py
new file mode 100644 (file)
index 0000000..92e2437
--- /dev/null
@@ -0,0 +1,113 @@
+class BuildInfo(object):
+    def __init__(self, rawobj):
+        self._Key = rawobj.DescFilePath
+
+    def __str__(self):
+        return self._Key
+
+    def __eq__(self, other):
+        return self._Key == str(other)
+
+    def __hash__(self):
+        return hash(self._Key)
+
+class ModuleBuildInfo(BuildInfo):
+    def __init__(self, module):
+        BuildInfo.__init__(self, module)
+        self.Module     = module
+
+        self.Name       = module.BaseName
+        self.Guid       = module.Guid
+        self.Version    = module.Version
+        self.ModuleType = module.ModuleType
+
+        self.PlatformInfo = None
+        self.PackageInfo = None
+        self.Arch = ""
+        self.ToolChain = ""
+        self.BuildTarget = ""
+        self.PcdIsDriver = ""
+
+        self.IsLibrary = False
+        self.IsBinary = False
+
+        self.BaseName = ""
+        self.FileBase = ""
+        self.FileExt = ""
+        
+        self.WorkspaceDir = ""
+        self.SourceDir = ""
+        self.BuildDir = ""
+        self.OutputDir = ""
+        self.DebugDir = ""
+        self.MakefileDir = ""
+        self.CustomMakefile = {}
+
+        self.IncludePathList = []
+        self.AutoGenFileList = []
+        self.UnicodeFileList = []
+        self.SourceFileList = []
+        self.ObjectFileList = []
+
+        self.DependentPackageList = []
+        self.DependentLibraryList = []
+        self.LibraryAutoGenList = []
+
+        self.FileDependency = {}
+        self.BuildOption = {}
+
+        self.PcdList = []
+        self.GuidList = []
+        self.ProtocolList = []
+        self.PpiList = []
+
+        self.MacroList = []
+        self.DepexList = []
+
+class PackageBuildInfo(BuildInfo):
+    def __init__(self, package):
+        BuildInfo.__init__(self, package)
+        self.Package    = package
+        self.Name       = package.PackageName
+        self.Guid       = package.Guid
+        self.Version    = package.Version
+        
+        self.SourceDir = ""
+        self.IncludePathList = []
+
+class PlatformBuildInfo(BuildInfo):
+    def __init__(self, platform):
+        BuildInfo.__init__(self, platform)
+        self.Platform   = platform
+        self.Name       = platform.PlatformName
+        self.Guid       = platform.Guid
+        self.Version    = platform.Version
+
+        self.ArchList = []
+        self.ToolChain = ""
+        self.BuildTarget = ""
+        self.BuildRule = ""
+
+        self.WorkspaceDir = ""
+        self.SourceDir = ""
+        self.BuildDir = ""
+        self.OutputDir = ""
+        self.DebugDir = ""
+        self.LibraryDir = ""
+        self.FvDir = ""
+        self.MakefileDir = ""
+        self.FdfFileList = []
+
+        self.ModuleAutoGenList = []
+        self.LibraryAutoGenList = []
+        self.PackageList = []
+        
+        self.PcdTokenNumber = {}    # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
+        self.DynamicPcdList = []    # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
+
+        self.ToolPath = {}          # toolcode : tool path
+        self.ToolDynamicLib = {}    # toolcode : lib path
+        self.ToolStaticLib = {}     # toolcode : lib path
+        self.ToolChainFamily = {}   # toolcode : tool chain family
+        self.BuildOption = {}       # toolcode : option
+        self.DefaultToolOption = {}
diff --git a/Source/Python/AutoGen/GenC.py b/Source/Python/AutoGen/GenC.py
new file mode 100644 (file)
index 0000000..a46722f
--- /dev/null
@@ -0,0 +1,1565 @@
+#!/usr/bin/env python
+import string
+import EdkLogger
+
+from BuildToolError import *
+from DataType import *
+from EdkIIWorkspace import *
+from BuildInfo import *
+from StrGather import *
+
+ItemTypeStringDatabase  = {
+    TAB_PCDS_FEATURE_FLAG:'FixedAtBuild',
+    TAB_PCDS_FIXED_AT_BUILD:'FixedAtBuild',
+    TAB_PCDS_PATCHABLE_IN_MODULE:'BinaryPatch',
+    TAB_PCDS_DYNAMIC:'',
+    TAB_PCDS_DYNAMIC+"Default":'',
+    TAB_PCDS_DYNAMIC+"Vpd":'',
+    TAB_PCDS_DYNAMIC+"Hii":'',
+    TAB_PCDS_DYNAMIC_EX:'',
+    TAB_PCDS_DYNAMIC_EX+"Default":'',
+    TAB_PCDS_DYNAMIC_EX+"Vpd":'',
+    TAB_PCDS_DYNAMIC_EX+"Hii":'',
+}
+
+gDynamicPcd = [TAB_PCDS_DYNAMIC, TAB_PCDS_DYNAMIC+"Default", TAB_PCDS_DYNAMIC+"Vpd", TAB_PCDS_DYNAMIC+"Hii"]
+gDynamicExPcd = [TAB_PCDS_DYNAMIC_EX, TAB_PCDS_DYNAMIC_EX+"Default", TAB_PCDS_DYNAMIC_EX+"Vpd", TAB_PCDS_DYNAMIC_EX+"Hii"]
+
+DatumSizeStringDatabase = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOLEAN','VOID*':'8'}
+DatumSizeStringDatabaseH = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOL','VOID*':'PTR'}
+DatumSizeStringDatabaseLib = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'Bool','VOID*':'Ptr'}
+
+PcdPhaseMap = {
+    "PEI_PCD_DRIVER"    :   "PEI",
+    "DXE_PCD_DRIVER"    :   "DXE"
+}
+
+PcdDatabaseCommonAutoGenH = """
+//
+// The following definition will be generated by build tool
+//
+
+//
+// Common definitions
+//
+typedef UINT8 SKU_ID;
+
+#define PCD_TYPE_SHIFT        28
+
+#define PCD_TYPE_DATA         (0x0 << PCD_TYPE_SHIFT)
+#define PCD_TYPE_HII          (0x8 << PCD_TYPE_SHIFT)
+#define PCD_TYPE_VPD          (0x4 << PCD_TYPE_SHIFT)
+#define PCD_TYPE_SKU_ENABLED  (0x2 << PCD_TYPE_SHIFT)
+#define PCD_TYPE_STRING       (0x1 << PCD_TYPE_SHIFT)
+
+#define PCD_TYPE_ALL_SET      (PCD_TYPE_DATA | PCD_TYPE_HII | PCD_TYPE_VPD | PCD_TYPE_SKU_ENABLED | PCD_TYPE_STRING)
+
+#define PCD_DATUM_TYPE_SHIFT  24
+
+#define PCD_DATUM_TYPE_POINTER  (0x0 << PCD_DATUM_TYPE_SHIFT)
+#define PCD_DATUM_TYPE_UINT8    (0x1 << PCD_DATUM_TYPE_SHIFT)
+#define PCD_DATUM_TYPE_UINT16   (0x2 << PCD_DATUM_TYPE_SHIFT)
+#define PCD_DATUM_TYPE_UINT32   (0x4 << PCD_DATUM_TYPE_SHIFT)
+#define PCD_DATUM_TYPE_UINT64   (0x8 << PCD_DATUM_TYPE_SHIFT)
+
+#define PCD_DATUM_TYPE_ALL_SET  (PCD_DATUM_TYPE_POINTER | \\
+                                 PCD_DATUM_TYPE_UINT8   | \\
+                                 PCD_DATUM_TYPE_UINT16  | \\
+                                 PCD_DATUM_TYPE_UINT32  | \\
+                                 PCD_DATUM_TYPE_UINT64)
+
+#define PCD_DATABASE_OFFSET_MASK (~(PCD_TYPE_ALL_SET | PCD_DATUM_TYPE_ALL_SET))
+
+typedef struct  {
+  UINT32  ExTokenNumber;
+  UINT16  LocalTokenNumber;   // PCD Number of this particular platform build
+  UINT16  ExGuidIndex;        // Index of GuidTable
+} DYNAMICEX_MAPPING;
+
+typedef struct {
+  UINT32  SkuDataStartOffset; //We have to use offsetof MACRO as we don't know padding done by compiler
+  UINT32  SkuIdTableOffset;   //Offset from the PCD_DB
+} SKU_HEAD;
+
+typedef struct {
+  UINT16  GuidTableIndex;     // Offset in Guid Table in units of GUID.
+  UINT16  StringIndex;        // Offset in String Table in units of UINT16.
+  UINT16  Offset;             // Offset in Variable
+  UINT16  DefaultValueOffset; // Offset of the Default Value
+} VARIABLE_HEAD;
+
+typedef  struct {
+  UINT32  Offset;
+} VPD_HEAD;
+
+typedef UINT16 STRING_HEAD;
+
+typedef UINT16 SIZE_INFO;
+
+#define offsetof(s,m)  (UINT32) (UINTN) &(((s *)0)->m)
+
+"""
+
+PcdDatabaseEpilogueAutoGenH = """
+typedef struct {
+  PEI_PCD_DATABASE PeiDb;
+  DXE_PCD_DATABASE DxeDb;
+} PCD_DATABASE;
+
+#define PCD_TOTAL_TOKEN_NUMBER (PEI_LOCAL_TOKEN_NUMBER + DXE_LOCAL_TOKEN_NUMBER)
+
+"""
+
+PcdDatabaseAutoGenH = """
+#define ${PHASE}_GUID_TABLE_SIZE                ${GUID_TABLE_SIZE}
+#define ${PHASE}_STRING_TABLE_SIZE              ${STRING_TABLE_SIZE}
+#define ${PHASE}_SKUID_TABLE_SIZE               ${SKUID_TABLE_SIZE}
+#define ${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE  ${LOCAL_TOKEN_NUMBER_TABLE_SIZE}
+#define ${PHASE}_LOCAL_TOKEN_NUMBER             ${LOCAL_TOKEN_NUMBER}
+#define ${PHASE}_EXMAPPING_TABLE_SIZE           ${EXMAPPING_TABLE_SIZE}
+#define ${PHASE}_EX_TOKEN_NUMBER                ${EX_TOKEN_NUMBER}
+#define ${PHASE}_SIZE_TABLE_SIZE                ${SIZE_TABLE_SIZE}
+#define ${PHASE}_GUID_TABLE_EMPTY               ${GUID_TABLE_EMPTY}
+#define ${PHASE}_STRING_TABLE_EMPTY             ${STRING_TABLE_EMPTY}
+#define ${PHASE}_SKUID_TABLE_EMPTY              ${SKUID_TABLE_EMPTY}
+#define ${PHASE}_DATABASE_EMPTY                 ${DATABASE_EMPTY}
+#define ${PHASE}_EXMAP_TABLE_EMPTY              ${EXMAP_TABLE_EMPTY}
+
+typedef struct {
+${BEGIN}  UINT64             ${INIT_CNAME_DECL_UITN64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}];
+${END}
+${BEGIN}  UINT64             ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64};
+${END}
+${BEGIN}  UINT32             ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}];
+${END}
+${BEGIN}  UINT32             ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32};
+${END}
+${BEGIN}  VPD_HEAD           ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}];
+${END}
+  DYNAMICEX_MAPPING  ExMapTable[${PHASE}_EXMAPPING_TABLE_SIZE];
+  UINT32             LocalTokenNumberTable[${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE];
+  GUID               GuidTable[${PHASE}_GUID_TABLE_SIZE];
+${BEGIN}  STRING_HEAD        ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}];
+${END}
+${BEGIN}  VARIABLE_HEAD      ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}[${VARIABLE_HEAD_NUMSKUS_DECL}];
+${END}
+${BEGIN}  UINT16             StringTable${STRING_TABLE_INDEX}[${STRING_TABLE_LENGTH}]; /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
+${END}
+  SIZE_INFO          SizeTable[${PHASE}_SIZE_TABLE_SIZE];
+${BEGIN}  UINT16             ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}];
+${END}
+${BEGIN}  UINT16             ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16};
+${END}
+${BEGIN}  UINT8              ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}];
+${END}
+${BEGIN}  UINT8              ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8};
+${END}
+${BEGIN}  BOOLEAN            ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_BOOLEAN}];
+${END}
+${BEGIN}  BOOLEAN            ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN};
+${END}
+  UINT8              SkuIdTable[${PHASE}_SKUID_TABLE_SIZE];
+${SYSTEM_SKU_ID}
+} ${PHASE}_PCD_DATABASE_INIT;
+
+typedef struct {
+${PCD_DATABASE_UNINIT_EMPTY}
+${BEGIN}  UINT64   ${UNINIT_CNAME_DECL_UINT64}_${UNINIT_GUID_DECL_UINT64}[${UNINIT_NUMSKUS_DECL_UINT64}];
+${END}
+${BEGIN}  UINT32   ${UNINIT_CNAME_DECL_UINT32}_${UNINIT_GUID_DECL_UINT32}[${UNINIT_NUMSKUS_DECL_UINT32}];
+${END}
+${BEGIN}  UINT16   ${UNINIT_CNAME_DECL_UINT16}_${UNINIT_GUID_DECL_UINT16}[${UNINIT_NUMSKUS_DECL_UINT16}];
+${END}
+${BEGIN}  UINT8    ${UNINIT_CNAME_DECL_UINT8}_${UNINIT_GUID_DECL_UINT8}[${UNINIT_NUMSKUS_DECL_UINT8}];
+${END}
+${BEGIN}  BOOLEAN  ${UNINIT_CNAME_DECL_BOOLEAN}_${UNINIT_GUID_DECL_BOOLEAN}[${UNINIT_NUMSKUS_DECL_BOOLEAN}];
+${END}
+} ${PHASE}_PCD_DATABASE_UNINIT;
+
+#define PCD_${PHASE}_SERVICE_DRIVER_VERSION         2
+
+typedef struct {
+  ${PHASE}_PCD_DATABASE_INIT    Init;
+  ${PHASE}_PCD_DATABASE_UNINIT  Uninit;
+} ${PHASE}_PCD_DATABASE;
+
+#define ${PHASE}_NEX_TOKEN_NUMBER (${PHASE}_LOCAL_TOKEN_NUMBER - ${PHASE}_EX_TOKEN_NUMBER)
+"""
+
+EmptyPcdDatabaseAutoGenC = """
+${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
+  /* ExMapTable */
+  {
+    {0, 0, 0}
+  },
+  /* LocalTokenNumberTable */
+  {
+    0
+  },
+  /* GuidTable */
+  {
+    {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}
+  },
+  /* StringTable */
+  { 0 },
+  /* SizeTable */
+  {
+    0, 0
+  },
+  /* SkuIdTable */
+  { 0 },
+  ${SYSTEM_SKU_ID_VALUE}
+};
+"""
+
+PcdDatabaseAutoGenC = """
+${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
+${BEGIN}  { ${INIT_VALUE_UINT64} }, /*  ${INIT_CNAME_DECL_UINT64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}] */
+${END}
+${BEGIN}  ${VARDEF_VALUE_UINT64}, /* ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64} */
+${END}
+${BEGIN}  { ${INIT_VALUE_UINT32} }, /*  ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}] */
+${END}
+${BEGIN}  ${VARDEF_VALUE_UINT32}, /* ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32} */
+${END}
+  /* VPD */
+${BEGIN}  { ${VPD_HEAD_VALUE} }, /* ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}] */
+${END}
+  /* ExMapTable */
+  {
+${BEGIN}    { ${EXMAPPING_TABLE_EXTOKEN}, ${EXMAPPING_TABLE_LOCAL_TOKEN}, ${EXMAPPING_TABLE_GUID_INDEX} },
+${END}
+  },
+  /* LocalTokenNumberTable */
+  {
+${BEGIN}    offsetof(${PHASE}_PCD_DATABASE, ${TOKEN_INIT}.${TOKEN_CNAME}_${TOKEN_GUID}) | ${TOKEN_TYPE},
+${END}
+  },
+  /* GuidTable */
+  {
+${BEGIN}    ${GUID_STRUCTURE},
+${END}
+  },
+${BEGIN}  { ${STRING_HEAD_VALUE} }, /* ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}] */
+${END}
+${BEGIN}  /* ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}[${VARIABLE_HEAD_NUMSKUS_DECL}] */
+  {
+    ${VARIABLE_HEAD_VALUE}
+  },
+${END}
+ /* StringTable */
+${BEGIN}  ${STRING_TABLE_VALUE}, /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
+${END}
+  /* SizeTable */
+  {
+${BEGIN}    ${SIZE_TABLE_CURRENT_LENGTH}, ${SIZE_TABLE_MAXIMUM_LENGTH}, /* ${SIZE_TABLE_CNAME}_${SIZE_TABLE_GUID} */
+${END}
+  },
+${BEGIN}  { ${INIT_VALUE_UINT16} }, /*  ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}] */
+${END}
+${BEGIN}  ${VARDEF_VALUE_UINT16}, /* ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16} */
+${END}
+${BEGIN}  { ${INIT_VALUE_UINT8} }, /*  ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}] */
+${END}
+${BEGIN}  ${VARDEF_VALUE_UINT8}, /* ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8} */
+${END}
+${BEGIN}  { ${INIT_VALUE_BOOLEAN} }, /*  ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_DECL_BOOLEAN}] */
+${END}
+${BEGIN}  ${VARDEF_VALUE_BOOLEAN}, /* ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN} */
+${END}
+  /* SkuIdTable */
+  { ${BEGIN}${SKUID_VALUE}, ${END} },
+  ${SYSTEM_SKU_ID_VALUE}
+};
+"""
+
+#
+# AutoGen File Header Templates
+#
+AutoGenHeaderString = """\
+/**
+  DO NOT EDIT
+  FILE auto-generated
+  Module name:
+    $FileName
+  Abstract:       Auto-generated $FileName for building module or library.
+**/
+"""
+
+AutoGenHPrologueString = """
+#ifndef _AUTOGENH_${Guid}
+#define _AUTOGENH_${Guid}
+
+extern int __make_me_compile_correctly;
+"""
+
+AutoGenHEpilogueString = """
+#endif
+"""
+
+#
+# PEI Core Entry Point Templates
+#
+PeiCoreEntryPointString = """
+EFI_STATUS
+${Function} (
+  IN EFI_PEI_STARTUP_DESCRIPTOR  *PeiStartupDescriptor,
+  IN VOID                        *OldCoreData
+  );
+
+EFI_STATUS
+EFIAPI
+ProcessModuleEntryPointList (
+  IN EFI_PEI_STARTUP_DESCRIPTOR  *PeiStartupDescriptor,
+  IN VOID                        *OldCoreData
+  )
+
+{
+  return ${Function} (PeiStartupDescriptor, OldCoreData);
+}
+"""
+
+#
+# DXE Core Entry Point Templates
+#
+DxeCoreEntryPointString = """
+const UINT32 _gUefiDriverRevision = 0;
+
+VOID
+${Function} (
+  IN VOID  *HobStart
+  );
+
+VOID
+EFIAPI
+ProcessModuleEntryPointList (
+  IN VOID  *HobStart
+  )
+
+{
+  ${Function} (HobStart);
+}
+"""
+
+#
+# PEIM Entry Point Templates
+#
+PeimEntryPointString = [
+"""
+GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = 0;
+
+EFI_STATUS
+EFIAPI
+ProcessModuleEntryPointList (
+  IN EFI_FFS_FILE_HEADER  *FfsHeader,
+  IN EFI_PEI_SERVICES     **PeiServices
+  )
+
+{
+  return EFI_SUCCESS;
+}
+""",
+"""
+GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = 0;
+
+EFI_STATUS
+${Function} (
+  IN EFI_FFS_FILE_HEADER  *FfsHeader,
+  IN EFI_PEI_SERVICES     **PeiServices
+  );
+
+EFI_STATUS
+EFIAPI
+ProcessModuleEntryPointList (
+  IN EFI_FFS_FILE_HEADER  *FfsHeader,
+  IN EFI_PEI_SERVICES     **PeiServices
+  )
+
+{
+  return ${Function} (FfsHeader, PeiServices);
+}
+""",
+"""
+GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = 0;
+
+${BEGIN}
+EFI_STATUS
+${Function} (
+  IN EFI_FFS_FILE_HEADER  *FfsHeader,
+  IN EFI_PEI_SERVICES     **PeiServices
+  );
+${END}
+
+EFI_STATUS
+EFIAPI
+ProcessModuleEntryPointList (
+  IN EFI_FFS_FILE_HEADER  *FfsHeader,
+  IN EFI_PEI_SERVICES     **PeiServices
+  )
+
+{
+  EFI_STATUS  Status;
+  EFI_STATUS  CombinedStatus;
+
+  CombinedStatus = EFI_LOAD_ERROR;
+${BEGIN}
+  Status = ${Function} (FfsHeader, PeiServices);
+  if (!EFI_ERROR (Status) || EFI_ERROR (CombinedStatus)) {
+    CombinedStatus = Status;
+  }
+${END}
+  return CombinedStatus;
+}
+"""
+]
+
+#
+# DXE SMM Entry Point Templates
+#
+DxeSmmEntryPointString = [
+"""
+EFI_STATUS
+EFIAPI
+ProcessModuleEntryPointList (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+
+{
+  return EFI_SUCCESS;
+}
+""",
+"""
+${BEGIN}
+EFI_STATUS
+${Function} (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  );
+${END}
+
+static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
+static EFI_STATUS  mDriverEntryPointStatus = EFI_LOAD_ERROR;
+
+VOID
+EFIAPI
+ExitDriver (
+  IN EFI_STATUS  Status
+  )
+{
+  if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
+    mDriverEntryPointStatus = Status;
+  }
+  LongJump (&mJumpContext, (UINTN)-1);
+  ASSERT (FALSE);
+}
+
+EFI_STATUS
+EFIAPI
+ProcessModuleEntryPointList (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+
+{
+${BEGIN}
+  if (SetJump (&mJumpContext) == 0) {
+    ExitDriver (${Function} (ImageHandle, SystemTable));
+    ASSERT (FALSE);
+  }
+${END}
+
+  return mDriverEntryPointStatus;
+}
+"""
+]
+
+#
+# UEFI Entry Point Templates
+#
+UefiEntryPointString = [
+"""
+const UINT32 _gUefiDriverRevision = 0;
+
+EFI_STATUS
+EFIAPI
+ProcessModuleEntryPointList (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  return EFI_SUCCESS;
+}
+""",
+"""
+const UINT32 _gUefiDriverRevision = 0;
+
+EFI_STATUS
+${Function} (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  );
+
+EFI_STATUS
+EFIAPI
+ProcessModuleEntryPointList (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+
+{
+  return ${Function} (ImageHandle, SystemTable);
+}
+
+VOID
+EFIAPI
+ExitDriver (
+  IN EFI_STATUS  Status
+  )
+{
+  if (EFI_ERROR (Status)) {
+    ProcessLibraryDestructorList (gImageHandle, gST);
+  }
+  gBS->Exit (gImageHandle, Status, 0, NULL);
+}
+""",
+"""
+const UINT32 _gUefiDriverRevision = 0;
+
+${BEGIN}
+EFI_STATUS
+${Function} (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  );
+${END}
+
+EFI_STATUS
+EFIAPI
+ProcessModuleEntryPointList (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+
+{
+  ${BEGIN}
+  if (SetJump (&mJumpContext) == 0) {
+    ExitDriver (${Function} (ImageHandle, SystemTable));
+    ASSERT (FALSE);
+  }
+  ${END}
+  return mDriverEntryPointStatus;
+}
+
+static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
+static EFI_STATUS  mDriverEntryPointStatus = EFI_LOAD_ERROR;
+
+VOID
+EFIAPI
+ExitDriver (
+  IN EFI_STATUS  Status
+  )
+{
+  if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
+    mDriverEntryPointStatus = Status;
+  }
+  LongJump (&mJumpContext, (UINTN)-1);
+  ASSERT (FALSE);
+}
+"""
+]
+
+#
+# UEFI Unload Image Templates
+#
+UefiUnloadImageString = [
+"""
+GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
+
+EFI_STATUS
+EFIAPI
+ProcessModuleUnloadList (
+  IN EFI_HANDLE        ImageHandle
+  )
+{
+  return EFI_SUCCESS;
+}
+""",
+"""
+GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
+
+${BEGIN}
+EFI_STATUS
+${Function} (
+  IN EFI_HANDLE        ImageHandle
+  );
+${END}
+
+EFI_STATUS
+EFIAPI
+ProcessModuleUnloadList (
+  IN EFI_HANDLE        ImageHandle
+  )
+{
+  return ${Function} (ImageHandle);
+}
+""",
+"""
+GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};
+
+${BEGIN}
+EFI_STATUS
+${Function} (
+  IN EFI_HANDLE        ImageHandle
+  );
+${END}
+
+EFI_STATUS
+EFIAPI
+ProcessModuleUnloadList (
+  IN EFI_HANDLE        ImageHandle
+  )
+{
+  EFI_STATUS  Status;
+
+  Status = EFI_SUCCESS;
+${BEGIN}
+  if (EFI_ERROR (Status)) {
+    ${Function} (ImageHandle);
+  } else {
+    Status = ${Function} (ImageHandle);
+  }
+${END}
+  return Status;
+}
+"""
+]
+
+#
+# Library Constructor and Destructor Templates
+#
+LibraryString = [
+"""
+VOID
+EFIAPI
+ProcessLibrary${Type}List (
+  VOID
+  )
+{
+}
+""",
+"""
+VOID
+EFIAPI
+ProcessLibrary${Type}List (
+  IN EFI_FFS_FILE_HEADER       *FfsHeader,
+  IN EFI_PEI_SERVICES          **PeiServices
+  )
+{
+}
+""",
+"""
+VOID
+EFIAPI
+ProcessLibrary${Type}List (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+}
+""",
+"""
+${BEGIN}
+RETURN_STATUS
+EFIAPI
+${Function} (
+  VOID
+  );
+${END}
+
+VOID
+EFIAPI
+ProcessLibrary${Type}List (
+  VOID
+  )
+{
+  EFI_STATUS  Status;
+
+${BEGIN}
+  Status = ${Function} ();
+  ASSERT_EFI_ERROR (Status);
+${END}
+}
+""",
+"""
+${BEGIN}
+EFI_STATUS
+EFIAPI
+${Function} (
+  IN EFI_FFS_FILE_HEADER       *FfsHeader,
+  IN EFI_PEI_SERVICES          **PeiServices
+  );
+${END}
+
+VOID
+EFIAPI
+ProcessLibrary${Type}List (
+  IN EFI_FFS_FILE_HEADER       *FfsHeader,
+  IN EFI_PEI_SERVICES          **PeiServices
+  )
+{
+  EFI_STATUS  Status;
+
+${BEGIN}
+  Status = ${Function} (FfsHeader, PeiServices);
+  ASSERT_EFI_ERROR (Status);
+${END}
+}
+""",
+"""
+${BEGIN}
+EFI_STATUS
+EFIAPI
+${Function} (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  );
+${END}
+
+VOID
+EFIAPI
+ProcessLibrary${Type}List (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  EFI_STATUS  Status;
+
+${BEGIN}
+  Status = ${Function} (ImageHandle, SystemTable);
+  ASSERT_EFI_ERROR (Status);
+${END}
+}
+"""
+]
+
+SpecificationString = """
+${BEGIN}
+#define ${Specification}
+${END}
+"""
+
+BasicHeaderFile = "Base.h"
+
+ModuleTypeHeaderFile = {
+    "BASE"              :   [BasicHeaderFile],
+    "SEC"               :   ["PiPei.h", "Library/DebugLib.h"],
+    "PEI_CORE"          :   ["PiPei.h", "Library/DebugLib.h"],  
+    "PEIM"              :   ["PiPei.h", "Library/DebugLib.h"],  
+    "DXE_CORE"          :   ["PiDxe.h", "Library/DebugLib.h"],  
+    "DXE_DRIVER"        :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"], 
+    "DXE_SMM_DRIVER"    :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"], 
+    "DXE_RUNTIME_DRIVER":   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"], 
+    "DXE_SAL_DRIVER"    :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"], 
+    "UEFI_DRIVER"       :   ["Uefi.h",  "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"],
+    "UEFI_APPLICATION"  :   ["Uefi.h",  "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h"],
+    "USER_DEFINED"      :   [BasicHeaderFile]
+}
+
+##ModuleTypeHeaderFile = {
+##    "BASE"              :   BasicHeaderFile,
+##    "SEC"               :   ["Peim.h", "DebugLib.h", ],         # "PiPei.h",
+##    "PEI_CORE"          :   ["PeiCore.h", "DebugLib.h"],        # "PiPei.h",
+##    "PEIM"              :   ["Peim.h", "DebugLib.h"],           # PiPei.h",
+##    "DXE_CORE"          :   ["DxeCore.h", "DebugLib.h"],        # PiDxe.h",
+##    "DXE_DRIVER"        :   ["Dxe.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],   # "PiDxe.h",
+##    "DXE_SMM_DRIVER"    :   ["Dxe.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],   # "PiDxe.h",
+##    "DXE_RUNTIME_DRIVER":   ["Dxe.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],   # "PiDxe.h",
+##    "DXE_SAL_DRIVER"    :   ["Dxe.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],   # "PiDxe.h",
+##    "UEFI_DRIVER"       :   ["Uefi.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"],
+##    "UEFI_APPLICATION"  :   ["Uefi.h", "BaseLib.h", "DebugLib.h", "UefiBootServicesTableLib.h"]
+##}
+
+def GuidStringToGuidStructureString(Guid):
+  GuidList = Guid.split('-')
+  Result = '{'
+  for Index in range(0,3,1):
+    Result = Result + '0x' + GuidList[Index] + ', '
+  Result = Result + '{0x' + GuidList[3][0:2] + ', 0x' + GuidList[3][2:4]
+  for Index in range(0,12,2):
+    Result = Result + ', 0x' + GuidList[4][Index:Index+2]
+  Result += '}}'
+  return Result
+
+def GuidStructureStringToGuidString(GuidValue):
+    guidValueString = GuidValue.lower().replace("{", "").replace("}", "").replace(" ", "")
+    guidValueList = guidValueString.split(",")
+    if len(guidValueList) != 11:
+        raise AutoGenError(msg="Invalid GUID value string %s" % GuidValue)
+    return "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x" % (
+            int(guidValueList[0], 16),
+            int(guidValueList[1], 16),
+            int(guidValueList[2], 16),
+            int(guidValueList[3], 16),
+            int(guidValueList[4], 16),
+            int(guidValueList[5], 16),
+            int(guidValueList[6], 16),
+            int(guidValueList[7], 16),
+            int(guidValueList[8], 16),
+            int(guidValueList[9], 16),
+            int(guidValueList[10], 16)
+            )
+
+def GuidStructureStringToGuidValueName(GuidValue):
+    guidValueString = GuidValue.lower().replace("{", "").replace("}", "").replace(" ", "")
+    guidValueList = guidValueString.split(",")
+    if len(guidValueList) != 11:
+        raise AutoGenError(msg="Invalid GUID value string %s" % GuidValue)
+    return "%08x_%04x_%04x_%02x%02x_%02x%02x%02x%02x%02x%02x" % (
+            int(guidValueList[0], 16),
+            int(guidValueList[1], 16),
+            int(guidValueList[2], 16),
+            int(guidValueList[3], 16),
+            int(guidValueList[4], 16),
+            int(guidValueList[5], 16),
+            int(guidValueList[6], 16),
+            int(guidValueList[7], 16),
+            int(guidValueList[8], 16),
+            int(guidValueList[9], 16),
+            int(guidValueList[10], 16)
+            )
+
+def GetGuidValue(packages, cname):
+    for p in packages:
+        if cname in p.Guids:
+            return p.Guids[cname]
+        if cname in p.Protocols:
+            return p.Protocols[cname]
+        if cname in p.Ppis:
+            return p.Ppis[cname]
+    else:
+        raise AutoGenError(msg="Cannot find GUID value for %s in any package" % cname)
+
+class AutoGenString(object):
+  def __init__(self):
+    self.String = ''
+
+  def Append(self, AppendString, Dictionary=None):
+    if Dictionary == None:
+      self.String += AppendString
+    else:
+      while AppendString.find('${BEGIN}') >= 0:
+        Start = AppendString.find('${BEGIN}')
+        End   = AppendString.find('${END}')
+        SubString = AppendString[AppendString.find('${BEGIN}'):AppendString.find('${END}')+6]
+        Max = 0
+        MaxLen = {}
+        for Key in Dictionary:
+          if SubString.find('$'+Key) >= 0 or SubString.find('${'+Key+'}') >= 0:
+            Value = Dictionary[Key]
+            if type(Value) == type([]):
+              MaxLen[Key] = len(Value)
+            else:
+              MaxLen[Key] = 1
+            if MaxLen[Key] > Max:
+              Max = MaxLen[Key]
+
+        NewString = ''
+        for Index in range(0,Max):
+          NewDict = {'BEGIN':'','END':''}
+          for Key in MaxLen:
+            NewDict[Key] = Dictionary[Key]
+            if type(Dictionary[Key]) == type([]):
+              NewDict[Key] = Dictionary[Key][Index]
+          NewString += string.Template(SubString).safe_substitute(NewDict)
+        AppendString = AppendString[0:Start] + NewString + AppendString[End+6:]
+      NewDict = {}
+      for Key in Dictionary:
+        NewDict[Key] = Dictionary[Key]
+        if type(Dictionary[Key]) == type([]) and len(Dictionary[Key]) > 0:
+          NewDict[Key] = Dictionary[Key][0]
+      self.String += string.Template(AppendString).safe_substitute(NewDict)
+
+def CreateModulePcdCode(info, autoGenC, autoGenH, pcd):
+    pcdTokenNumber = info.PlatformInfo.PcdTokenNumber
+    #
+    # Write PCDs
+    #
+    pcdTokenName = '_PCD_TOKEN_' + pcd.TokenCName
+    if pcd.Type in gDynamicExPcd:
+        tokenNumber = pcd.TokenValue
+    else:
+        tokenNumber = pcdTokenNumber[pcd.TokenCName, pcd.TokenSpaceGuidCName]
+    autoGenH.Append('#define %s  %d\n' % (pcdTokenName, tokenNumber))
+
+    EdkLogger.debug(EdkLogger.DEBUG_7, "Creating code for " + pcd.TokenCName + "/" + pcd.TokenSpaceGuidCName)
+    if pcd.Type not in ItemTypeStringDatabase:
+        raise AutoGenError(msg="Unknown PCD type [%s] of PCD %s/%s" % (pcd.Type, pcd.TokenCName, pcd.TokenSpaceGuidCName))
+    if pcd.DatumType not in DatumSizeStringDatabase:
+        raise AutoGenError(msg="Unknown datum type [%s] of PCD %s/%s" % (pcd.DatumType, pcd.TokenCName, pcd.TokenSpaceGuidCName))
+
+    datumSize = DatumSizeStringDatabase[pcd.DatumType]
+    datumSizeLib = DatumSizeStringDatabaseLib[pcd.DatumType]
+    getModeName = '_PCD_GET_MODE_' + DatumSizeStringDatabaseH[pcd.DatumType] + '_' + pcd.TokenCName
+    setModeName = '_PCD_SET_MODE_' + DatumSizeStringDatabaseH[pcd.DatumType] + '_' + pcd.TokenCName
+
+    if pcd.Type in gDynamicExPcd:
+        autoGenH.Append('#define %s  LibPcdGetEx%s(&%s, %s)\n' % (getModeName, datumSizeLib, pcd.TokenSpaceGuidCName, pcdTokenName))
+        if DatumType == 'VOID*':
+            autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (setModeName, datumSizeLib, pcd.TokenSpaceGuidCName, pcdTokenName))
+        else:
+            autoGenH.Append('#define %s(Value)  LibPcdSetEx%s(&%s, %s, (Value))\n' % (setModeName, datumSizeLib, pcd.TokenSpaceGuidCName, pcdTokenName))
+    elif pcd.Type in gDynamicPcd:
+        autoGenH.Append('#define %s  LibPcdGet%s(%s)\n' % (getModeName, datumSizeLib, pcdTokenName))
+        if pcd.DatumType == 'VOID*':
+            autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(setModeName, datumSizeLib, pcdTokenName))
+        else:
+            autoGenH.Append('#define %s(Value)  LibPcdSet%s(%s, (Value))\n' % (setModeName, datumSizeLib, pcdTokenName))
+    else:
+        PcdVariableName = '_gPcd_' + ItemTypeStringDatabase[pcd.Type] + '_' + pcd.TokenCName
+        Const = 'const'
+        if pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
+            Const = ''
+        Type = ''
+        Array = ''
+        Value = pcd.DefaultValue
+        if pcd.DatumType == 'UINT64':
+            Value += 'ULL'
+        if pcd.DatumType == 'VOID*':
+            ArraySize = int(pcd.MaxDatumSize)
+            if Value[0] == '{':
+                Type = '(VOID *)'
+            else:
+                Unicode = False
+                if Value[0] == 'L':
+                    Unicode = True
+                Value = Value.lstrip('L').strip('"')
+                NewValue = '{'
+                for Index in range(0,len(Value)):
+                    NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ', '
+                    if Unicode:
+                        NewValue = NewValue + str(ord(Value[Index]) / 0x100) + ', '
+                if Unicode:
+                    if ArraySize < (len(Value)*2 + 2):
+                        ArraySize = len(Value)*2 + 2
+                    NewValue = NewValue + '0, '
+                else:
+                    if ArraySize < (len(Value) + 1):
+                        ArraySize = len(Value) + 1
+                Value = NewValue + '0 }'
+            Array = '[%d]' % ArraySize
+
+        PcdValueName = '_PCD_VALUE_' + pcd.TokenCName
+        if pcd.DatumType == 'VOID*' and Value[0] == '{':
+            autoGenH.Append('#define _PCD_PATCHABLE_%s_SIZE %s\n' % (pcd.TokenCName, pcd.MaxDatumSize))
+            autoGenH.Append('#define %s  %s%s\n' %(PcdValueName, Type, PcdVariableName))
+            autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT8 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
+            autoGenH.Append('extern %s UINT8 %s%s;\n' %(Const, PcdVariableName, Array))
+            autoGenH.Append('#define %s  %s%s\n' %(getModeName, Type, PcdVariableName))
+        else:
+            autoGenH.Append('#define %s  %s\n' %(PcdValueName, Value))
+            autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s %s = %s;\n' %(Const, pcd.DatumType, PcdVariableName, PcdValueName))
+            autoGenH.Append('extern %s  %s  %s%s;\n' % (Const, pcd.DatumType, PcdVariableName, Array))
+            autoGenH.Append('#define %s  %s%s\n' % (getModeName, Type, PcdVariableName))
+
+        if pcd.Type == 'PATCHABLE_IN_MODULE':
+            if pcd.DatumType == 'VOID*':
+                autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPatchPcdSetPtr(_gPcd_BinaryPatch_%s, (UINTN)_PCD_PATCHABLE_%s_SIZE, (SizeOfBuffer), (Buffer))\n' % (setModeName, pcd.TokenCName, pcd.TokenCName))
+            else:
+                autoGenH.Append('#define %s(Value)  (%s = (Value))\n' % (setModeName, PcdVariableName))
+        else:
+            autoGenH.Append('//#define %s  ASSERT(FALSE)  // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % setModeName)
+
+def CreateLibraryPcdCode(info, autoGenC, autoGenH, pcd):
+    pcdTokenNumber = info.PlatformInfo.PcdTokenNumber
+    tokenSpaceGuidCName = pcd.TokenSpaceGuidCName
+    tokenCName  = pcd.TokenCName
+    tokenNumber = pcdTokenNumber[tokenCName, tokenSpaceGuidCName]
+    
+    if pcd.Type not in ItemTypeStringDatabase:
+        raise AutoGenError(msg="Unknown PCD type [%s] of PCD %s/%s" % (pcd.Type, pcd.TokenCName, pcd.TokenSpaceGuidCName))
+    if pcd.DatumType not in DatumSizeStringDatabase:
+        raise AutoGenError(msg="Unknown datum type [%s] of PCD %s/%s" % (pcd.DatumType, pcd.TokenCName, pcd.TokenSpaceGuidCName))
+
+    datumType   = pcd.DatumType
+    datumSize   = DatumSizeStringDatabaseH[datumType]
+    datumSizeLib= DatumSizeStringDatabaseLib[datumType]
+    getModeName = '_PCD_GET_MODE_' + datumSize + '_' + tokenCName
+    setModeName = '_PCD_SET_MODE_' + datumSize + '_' + tokenCName
+
+    type = ''
+    array = ''
+    if pcd.DatumType == 'VOID*':
+        type = '(VOID *)'
+        array = '[]'
+
+    autoGenH.Append('#define _PCD_TOKEN_%s  %d\n' % (tokenCName, tokenNumber))
+
+    pcdItemType = pcd.Type
+    if pcdItemType in gDynamicPcd:
+        pcdItemType = TAB_PCDS_FIXED_AT_BUILD
+        if (tokenCName, tokenSpaceGuidCName) in info.PlatformInfo.Platform.Pcds:
+            pcdItemType  = info.PlatformInfo.Platform.Pcds[tokenCName, tokenSpaceGuidCName].Type
+    if pcdItemType in gDynamicExPcd:
+        pcdTokenName = '_PCD_TOKEN_' + tokenCName
+        autoGenH.Append('#define %s  LibPcdGetEx%s(&%s, %s)\n' % (getModeName, datumSizeLib, tokenSpaceGuidCName, pcdTokenName))
+        if DatumType == 'VOID*':
+            autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (setModeName,datumSizeLib, tokenSpaceGuidCName, pcdTokenName))
+        else:
+            autoGenH.Append('#define %s(Value)  LibPcdSetEx%s(&%s, %s, (Value))\n' % (setModeName, datumSizeLib, tokenSpaceGuidCName, pcdTokenName))
+    if pcdItemType in gDynamicPcd:
+        pcdTokenName = '_PCD_TOKEN_' + tokenCName
+        autoGenH.Append('#define %s  LibPcdGet%s(%s)\n' % (getModeName, datumSizeLib, pcdTokenName))
+        if datumType == 'VOID*':
+            autoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(setModeName, datumSizeLib, pcdTokenName))
+        else:
+            autoGenH.Append('#define %s(Value)  LibPcdSet%s(%s, (Value))\n' % (setModeName, datumSizeLib, pcdTokenName))
+    if pcdItemType == TAB_PCDS_PATCHABLE_IN_MODULE:
+        pcdVariableName = '_gPcd_' + ItemTypeStringDatabase[TAB_PCDS_PATCHABLE_IN_MODULE] + '_' + tokenCName
+        autoGenH.Append('extern %s _gPcd_BinaryPatch_%s%s;\n' %(datumType, tokenCName, array) )
+        autoGenH.Append('#define %s  %s_gPcd_BinaryPatch_%s\n' %(getModeName, type, tokenCName))
+        autoGenH.Append('#define %s(Value)  (%s = (Value))\n' % (setModeName, pcdVariableName))
+    if pcdItemType == TAB_PCDS_FIXED_AT_BUILD or pcdItemType == TAB_PCDS_FEATURE_FLAG:
+        autoGenH.Append('extern const %s _gPcd_FixedAtBuild_%s%s;\n' %(datumType, tokenCName, array))
+        autoGenH.Append('#define %s  %s_gPcd_FixedAtBuild_%s\n' %(getModeName, type, tokenCName))
+        autoGenH.Append('//#define %s  ASSERT(FALSE)  // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % setModeName)
+
+def CreatePcdDatabasePhaseSpecificAutoGen (platform, phase):
+    AutoGenC = AutoGenString()
+    AutoGenH = AutoGenString()
+
+    Dict = {
+        'PHASE'                         : phase,
+        'GUID_TABLE_SIZE'               : '1',
+        'STRING_TABLE_SIZE'             : '1',
+        'SKUID_TABLE_SIZE'              : '1',
+        'LOCAL_TOKEN_NUMBER_TABLE_SIZE' : '1',
+        'LOCAL_TOKEN_NUMBER'            : '0',
+        'EXMAPPING_TABLE_SIZE'          : '1',
+        'EX_TOKEN_NUMBER'               : '0',
+        'SIZE_TABLE_SIZE'               : '2',
+        'GUID_TABLE_EMPTY'              : 'TRUE',
+        'STRING_TABLE_EMPTY'            : 'TRUE',
+        'SKUID_TABLE_EMPTY'             : 'TRUE',
+        'DATABASE_EMPTY'                : 'TRUE',
+        'EXMAP_TABLE_EMPTY'             : 'TRUE',
+        'PCD_DATABASE_UNINIT_EMPTY'     : '  UINT8  dummy; /* PCD_DATABASE_UNINIT is emptry */',
+        'SYSTEM_SKU_ID'                 : '  SKU_ID             SystemSkuId;',
+        'SYSTEM_SKU_ID_VALUE'           : '0'
+    }
+
+    for DatumType in ['UINT64','UINT32','UINT16','UINT8','BOOLEAN']:
+        Dict['VARDEF_CNAME_' + DatumType] = []
+        Dict['VARDEF_GUID_' + DatumType]  = []
+        Dict['VARDEF_SKUID_' + DatumType] = []
+        Dict['VARDEF_VALUE_' + DatumType] = []
+        for Init in ['INIT','UNINIT']:
+            Dict[Init+'_CNAME_DECL_' + DatumType]   = []
+            Dict[Init+'_GUID_DECL_' + DatumType]    = []
+            Dict[Init+'_NUMSKUS_DECL_' + DatumType] = []
+            Dict[Init+'_VALUE_' + DatumType]        = []
+
+    for Type in ['STRING_HEAD','VPD_HEAD','VARIABLE_HEAD']:
+        Dict[Type + '_CNAME_DECL']   = []
+        Dict[Type + '_GUID_DECL']    = []
+        Dict[Type + '_NUMSKUS_DECL'] = []
+        Dict[Type + '_VALUE'] = []
+
+    Dict['STRING_TABLE_INDEX'] = []
+    Dict['STRING_TABLE_LENGTH']  = []
+    Dict['STRING_TABLE_CNAME'] = []
+    Dict['STRING_TABLE_GUID']  = []
+    Dict['STRING_TABLE_VALUE'] = []
+
+    Dict['SIZE_TABLE_CNAME'] = []
+    Dict['SIZE_TABLE_GUID']  = []
+    Dict['SIZE_TABLE_CURRENT_LENGTH']  = []
+    Dict['SIZE_TABLE_MAXIMUM_LENGTH']  = []
+
+    Dict['EXMAPPING_TABLE_EXTOKEN'] = []
+    Dict['EXMAPPING_TABLE_LOCAL_TOKEN'] = []
+    Dict['EXMAPPING_TABLE_GUID_INDEX'] = []
+
+    Dict['GUID_STRUCTURE'] = []
+
+    Dict['SKUID_VALUE'] = []
+
+    if phase == 'DXE':
+        Dict['SYSTEM_SKU_ID'] = ''
+        Dict['SYSTEM_SKU_ID_VALUE'] = ''
+
+    StringTableIndex = 0
+    StringTableSize = 0
+    NumberOfLocalTokens = 0
+    NumberOfPeiLocalTokens = 0
+    NumberOfDxeLocalTokens = 0
+    NumberOfExTokens = 0
+    NumberOfSizeItems = 0
+    GuidList = []
+
+    for Pcd in platform.DynamicPcdList:
+        CName = Pcd.TokenCName
+        TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
+        EdkLogger.debug(EdkLogger.DEBUG_5, "PCD: %s %s (%s : %s)" % (CName, TokenSpaceGuidCName, Pcd.Phase, phase))
+
+        if Pcd.Phase == 'PEI':
+            NumberOfPeiLocalTokens += 1
+        if Pcd.Phase == 'DXE':
+            NumberOfDxeLocalTokens += 1
+        if Pcd.Phase != phase:
+            continue
+
+        #
+        # TODO: need GetGuidValue() definition
+        #
+        TokenSpaceGuid = GuidStructureStringToGuidValueName(GetGuidValue(platform.PackageList, TokenSpaceGuidCName))
+        if Pcd.Type == 'DYNAMIC_EX':
+            if TokenSpaceGuid not in GuidList:
+                GuidList += [TokenSpaceGuid]
+                Dict['GUID_STRUCTURE'].append(TokenSpaceGuid)
+            NumberOfExTokens += 1
+
+        ValueList = []
+        StringHeadOffsetList = []
+        VpdHeadOffsetList = []
+        VariableHeadValueList = []
+        Pcd.InitString = 'UNINIT'
+
+        if Pcd.DatumType == 'VOID*':
+            Pcd.TokenTypeList = ['PCD_DATUM_TYPE_POINTER']
+        elif Pcd.DatumType == 'BOOLEAN':
+            Pcd.TokenTypeList = ['PCD_DATUM_TYPE_UINT8']
+        else:
+            Pcd.TokenTypeList = ['PCD_DATUM_TYPE_' + Pcd.DatumType]
+
+        if len(Pcd.SkuInfoList) > 1:
+            Pcd.TokenTypeList += ['PCD_TYPE_SKU_ENABLED']
+
+        for Sku in Pcd.SkuInfoList:
+            SkuId = Sku.SkuId
+            if SkuId == None or SkuId == '':
+                continue
+
+            if SkuId not in Dict['SKUID_VALUE']:
+                Dict['SKUID_VALUE'].append(SkuId)
+
+            SkuIdIndex =   Dict['SKUID_VALUE'].index(SkuId)
+            if len(Sku.VariableName) > 0:
+                Pcd.TokenTypeList += ['PCD_TYPE_HII']
+                Pcd.InitString = 'INIT'
+                VariableNameStructure = '{' + ', '.join(Sku.VariableName) + ', 0x0000}'
+                if VariableNameStructure not in Dict['STRING_TABLE_VALUE']:
+                    Dict['STRING_TABLE_CNAME'].append(CName)
+                    Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)
+                    if StringTableIndex == 0:
+                        Dict['STRING_TABLE_INDEX'].append('')
+                    else:
+                        Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)
+
+                    Dict['STRING_TABLE_LENGTH'].append(len(Sku.VariableName) + 1)
+                    Dict['STRING_TABLE_VALUE'].append(VariableNameStructure)
+                    StringTableIndex += 1
+                    StringTableSize += len(Sku.VariableName) + 1
+
+                VariableHeadStringIndex = 0
+                for Index in range(Dict['STRING_TABLE_VALUE'].index(VariableNameStructure)):
+                    VariableHeadStringIndex += Dict['STRING_TABLE_LENGTH'][Index]
+
+                VariableGuid = GuidStructureStringToGuidValueName(self.GetGuidValue(Sku.VariableGuid))
+                if VariableGuid not in GuidList:
+                    GuidList += [VariableGuid]
+                    Dict['GUID_STRUCTURE'].append(VariableGuid)
+                VariableHeadGuidIndex = GuidList.index(VariableGuid)
+
+                VariableHeadValueList.append('%d, %d, %s, offsetof(${PHASE}_PCD_DATABASE, Init.%s_%s_VariableDefault_%s)' %
+                                             (VariableHeadGuidIndex, VariableHeadStringIndex, Sku.VariableOffset, CName, TokenSpaceGuid, SkuIdIndex))
+                Dict['VARDEF_CNAME_'+Pcd.DatumType].append(CName)
+                Dict['VARDEF_GUID_'+Pcd.DatumType].append(TokenSpaceGuid)
+                Dict['VARDEF_SKUID_'+Pcd.DatumType].append(SkuIdIndex)
+                Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue)
+            elif Sku.VpdOffset != '':
+                Pcd.TokenTypeList += ['PCD_TYPE_VPD']
+                Pcd.InitString = 'INIT'
+                VpdHeadOffsetList.append(Sku.VpdOffset)
+            else:
+                if Pcd.DatumType == 'VOID*':
+                    Pcd.TokenTypeList += ['PCD_TYPE_STRING']
+                    Pcd.InitString = 'INIT'
+                    if Sku.DefaultValue != '':
+                        NumberOfSizeItems += 1
+                        Dict['STRING_TABLE_CNAME'].append(CName)
+                        Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)
+
+                        if StringTableIndex == 0:
+                            Dict['STRING_TABLE_INDEX'].append('')
+                        else:
+                            Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)
+                        if Sku.DefaultValue[0] == 'L':
+                            Size = len(Sku.DefaultValue) - 3
+                            Dict['STRING_TABLE_VALUE'].append(Sku.DefaultValue)
+                        elif Sku.DefaultValue[0] == '"':
+                            Size = len(Sku.DefaultValue) - 2
+                            Dict['STRING_TABLE_VALUE'].append(Sku.DefaultValue)
+                        elif Sku.DefaultValue[0] == '{':
+                            Size = len(Sku.DefaultValue.replace(',',' ').split())
+                            Dict['STRING_TABLE_VALUE'].append('{' + Sku.DefaultValue + '}')
+
+                        StringHeadOffsetList.append(str(StringTableSize))
+                        Dict['SIZE_TABLE_CNAME'].append(CName)
+                        Dict['SIZE_TABLE_GUID'].append(TokenSpaceGuid)
+                        Dict['SIZE_TABLE_CURRENT_LENGTH'].append(Size)
+                        Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append(Pcd.MaxDatumSize)
+                        if Pcd.MaxDatumSize != '' and Pcd.MaxDatumSize > Size:
+                            Size = int(Pcd.MaxDatumSize)
+                        Dict['STRING_TABLE_LENGTH'].append(Size)
+                        StringTableIndex += 1
+                        StringTableSize += Size
+                else:
+                    Pcd.TokenTypeList += ['PCD_TYPE_DATA']
+                    if Sku.DefaultValue == 'TRUE':
+                        Pcd.InitString = 'INIT'
+                    elif Sku.DefaultValue.find('0x') == 0:
+                        if int(Sku.DefaultValue,16) != 0:
+                            Pcd.InitString = 'INIT'
+                    elif Sku.DefaultValue[0].isdigit():
+                        if int(Sku.DefaultValue) != 0:
+                            Pcd.InitString = 'INIT'
+                    ValueList.append(Sku.DefaultValue)
+
+        Pcd.TokenTypeList = list(set(Pcd.TokenTypeList))
+        if 'PCD_TYPE_HII' in Pcd.TokenTypeList:
+            Dict['VARIABLE_HEAD_CNAME_DECL'].append(CName)
+            Dict['VARIABLE_HEAD_GUID_DECL'].append(TokenSpaceGuid)
+            Dict['VARIABLE_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
+            Dict['VARIABLE_HEAD_VALUE'].append('{ %s }\n' % ' },\n    { '.join(VariableHeadValueList))
+        if 'PCD_TYPE_VPD' in Pcd.TokenTypeList:
+            Dict['VPD_HEAD_CNAME_DECL'].append(CName)
+            Dict['VPD_HEAD_GUID_DECL'].append(TokenSpaceGuid)
+            Dict['VPD_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
+            Dict['VPD_HEAD_VALUE'].append('{ %s }' % ' }, { '.join(VpdHeadOffsetList))
+        if 'PCD_TYPE_STRING' in Pcd.TokenTypeList:
+            Dict['STRING_HEAD_CNAME_DECL'].append(CName)
+            Dict['STRING_HEAD_GUID_DECL'].append(TokenSpaceGuid)
+            Dict['STRING_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
+            Dict['STRING_HEAD_VALUE'].append(', '.join(StringHeadOffsetList))
+        if 'PCD_TYPE_DATA' in Pcd.TokenTypeList:
+            Dict[Pcd.InitString+'_CNAME_DECL_'+Pcd.DatumType].append(CName)
+            Dict[Pcd.InitString+'_GUID_DECL_'+Pcd.DatumType].append(TokenSpaceGuid)
+            Dict[Pcd.InitString+'_NUMSKUS_DECL_'+Pcd.DatumType].append(len(Pcd.SkuInfoList))
+            if Pcd.InitString == 'UNINIT':
+                Dict['PCD_DATABASE_UNINIT_EMPTY'] = ''
+            else:
+                Dict[Pcd.InitString+'_VALUE_'+Pcd.DatumType].append(', '.join(ValueList))
+
+    if phase == 'PEI':
+        NumberOfLocalTokens = NumberOfPeiLocalTokens
+    if phase == 'DXE':
+        NumberOfLocalTokens = NumberOfDxeLocalTokens
+
+    Dict['TOKEN_INIT']       = ['' for x in range(NumberOfLocalTokens)]
+    Dict['TOKEN_CNAME']      = ['' for x in range(NumberOfLocalTokens)]
+    Dict['TOKEN_GUID']       = ['' for x in range(NumberOfLocalTokens)]
+    Dict['TOKEN_TYPE']       = ['' for x in range(NumberOfLocalTokens)]
+
+    for Pcd in platform.DynamicPcdList:
+        CName = Pcd.TokenCName
+        TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
+        if Pcd.Phase != phase:
+            continue
+
+        TokenSpaceGuid = GuidStructureStringToGuidValueName(GetGuidValue(platform.PackageList, TokenSpaceGuidCName))
+        GeneratedTokenNumber = platform.PcdTokenNumber[CName, TokenSpaceGuidCName] - 1
+        if phase == 'DXE':
+            GeneratedTokenNumber -= NumberOfPeiLocalTokens
+        Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Init'
+        if Pcd.InitString == 'UNINIT':
+            Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Uninit'
+        Dict['TOKEN_CNAME'][GeneratedTokenNumber] = CName
+        Dict['TOKEN_GUID'][GeneratedTokenNumber] = TokenSpaceGuid
+        Dict['TOKEN_TYPE'][GeneratedTokenNumber] = ' | '.join(Pcd.TokenTypeList)
+        if Pcd.Type == 'DYNAMIC_EX':
+            Dict['EXMAPPING_TABLE_EXTOKEN'].append(Pcd.Token)
+            Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append(GeneratedTokenNumber)
+            Dict['EXMAPPING_TABLE_GUID_INDEX'].append(GuidList.index(TokenSpaceGuid))
+
+    if GuidList != []:
+        Dict['GUID_TABLE_EMPTY'] = 'FALSE'
+        Dict['GUID_TABLE_SIZE'] = len(GuidList)
+    else:
+        Dict['GUID_STRUCTURE'] = [GuidStringToGuidStructureString('00000000-0000-0000-0000-000000000000')]
+
+    if StringTableIndex == 0:
+        Dict['STRING_TABLE_INDEX'].append('')
+        Dict['STRING_TABLE_LENGTH'].append(1)
+        Dict['STRING_TABLE_CNAME'].append('')
+        Dict['STRING_TABLE_GUID'].append('')
+        Dict['STRING_TABLE_VALUE'].append('{ 0 }')
+    else:
+        Dict['STRING_TABLE_EMPTY'] = 'FALSE'
+        Dict['STRING_TABLE_SIZE'] = StringTableSize
+
+    if Dict['SIZE_TABLE_CNAME'] == []:
+        Dict['SIZE_TABLE_CNAME'].append('')
+        Dict['SIZE_TABLE_GUID'].append('')
+        Dict['SIZE_TABLE_CURRENT_LENGTH'].append(0)
+        Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append(0)
+
+    if NumberOfLocalTokens != 0:
+        Dict['DATABASE_EMPTY']                = 'FALSE'
+        Dict['LOCAL_TOKEN_NUMBER_TABLE_SIZE'] = NumberOfLocalTokens
+        Dict['LOCAL_TOKEN_NUMBER']            = NumberOfLocalTokens
+
+    if NumberOfExTokens != 0:
+        Dict['EXMAP_TABLE_EMPTY']    = 'FALSE'
+        Dict['EXMAPPING_TABLE_SIZE'] = NumberOfExTokens
+        Dict['EX_TOKEN_NUMBER']      = NumberOfExTokens
+    else:
+        Dict['EXMAPPING_TABLE_EXTOKEN'].append(0)
+        Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append(0)
+        Dict['EXMAPPING_TABLE_GUID_INDEX'].append(0)
+
+    if NumberOfSizeItems != 0:
+        Dict['SIZE_TABLE_SIZE'] = NumberOfSizeItems * 2
+
+    AutoGenH.Append(PcdDatabaseAutoGenH, Dict)
+    if NumberOfLocalTokens == 0:
+        AutoGenC.Append(EmptyPcdDatabaseAutoGenC, Dict)
+    else:
+        AutoGenC.Append(PcdDatabaseAutoGenC, Dict)
+
+    return AutoGenH, AutoGenC
+
+def CreatePcdDatabaseCode (info, autoGenC, autoGenH):
+    if info.PcdIsDriver == "":
+        return
+    autoGenH.Append(PcdDatabaseCommonAutoGenH)
+    additionalAutoGenH, additionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (info.PlatformInfo, 'PEI')
+    autoGenH.Append(additionalAutoGenH.String)
+
+    phase = PcdPhaseMap[info.PcdIsDriver]
+    if phase == 'PEI':
+        autoGenC.Append(additionalAutoGenC.String)
+
+    if phase == 'DXE':
+        additionalAutoGenH, additionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (info.PlatformInfo, phase)
+        autoGenH.Append(additionalAutoGenH.String)
+        autoGenC.Append(additionalAutoGenC.String)
+        autoGenH.Append(PcdDatabaseEpilogueAutoGenH)
+
+def CreateLibraryConstructorCode(info, autoGenC, autoGenH):
+    if info.IsLibrary:
+        return
+    #
+    # Library Constructors
+    #
+    ConstructorList = []
+    for lib in info.DependentLibraryList:
+        if len(lib.ConstructorList) <= 0:
+            continue
+        ConstructorList.extend(lib.ConstructorList)
+
+    Dict = {'Type':'Constructor', 'Function':ConstructorList}
+    if info.ModuleType == 'BASE':
+        if len(ConstructorList) == 0:
+            autoGenC.Append(LibraryString[0], Dict)
+        else:
+            autoGenC.Append(LibraryString[3], Dict)
+    elif info.ModuleType in ['PEI_CORE','PEIM']:
+        if len(ConstructorList) == 0:
+            autoGenC.Append(LibraryString[1], Dict)
+        else:
+            autoGenC.Append(LibraryString[4], Dict)
+    elif info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION']:
+        if len(ConstructorList) == 0:
+            autoGenC.Append(LibraryString[2], Dict)
+        else:
+            autoGenC.Append(LibraryString[5], Dict)
+
+def CreateLibraryDestructorCode(info, autoGenC, autoGenH):
+    if info.IsLibrary:
+        return
+    #
+    # Library Destructors
+    #
+    DestructorList = []
+    for lib in info.DependentLibraryList:
+        if len(lib.DestructorList) <= 0:
+            continue
+        DestructorList.extend(lib.DestructorList)
+
+    DestructorList.reverse()
+    if info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION']:
+        if len(DestructorList) == 0:
+            autoGenC.Append(LibraryString[2], {'Type':'Destructor','Function':DestructorList})
+        else:
+            autoGenC.Append(LibraryString[5], {'Type':'Destructor','Function':DestructorList})
+
+
+def CreateModuleEntryPointCode(info, autoGenC, autoGenH):
+    if info.IsLibrary:
+        return
+    #
+    # Module Entry Points
+    #
+    NumEntryPoints = len(info.Module.ModuleEntryPointList)
+    Dict = {'Function':info.Module.ModuleEntryPointList}
+
+    if info.ModuleType in ['PEI_CORE', 'DXE_CORE']:
+        if NumEntryPoints != 1:
+            raise AutoGenError(msg='%s must have exactly one entry point' % info.ModuleType)
+    if info.ModuleType == 'PEI_CORE':
+        autoGenC.Append(PeiCoreEntryPointString, Dict)
+    elif info.ModuleType == 'DXE_CORE':
+        autoGenC.Append(DxeCoreEntryPointString, Dict)
+    elif info.ModuleType == 'PEIM':
+        if NumEntryPoints < 2:
+            autoGenC.Append(PeimEntryPointString[NumEntryPoints], Dict)
+        else:
+            autoGenC.Append(PeimEntryPointString[2], Dict)
+    elif info.ModuleType in ['DXE_RUNTIME_DRIVER','DXE_DRIVER','DXE_SMM_DRIVER', 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION']:
+        if info.ModuleType == 'DXE_SMM_DRIVER':
+            if NumEntryPoints == 0:
+                autoGenC.Append(DxeSmmEntryPointString[0], Dict)
+            else:
+                autoGenC.Append(DxeSmmEntryPointString[1], Dict)
+        else:
+            if NumEntryPoints < 2:
+                autoGenC.Append(UefiEntryPointString[NumEntryPoints], Dict)
+            else:
+                autoGenC.Append(UefiEntryPointString[2], Dict)
+
+def CreateModuleUnloadImageCode(info, autoGenC, autoGenH):
+    if info.IsLibrary:
+        return
+    #
+    # Unload Image Handlers
+    #
+    NumUnloadImage = len(info.Module.ModuleUnloadImageList)
+    Dict = {'Count':NumUnloadImage, 'Function':info.Module.ModuleUnloadImageList}
+    if NumUnloadImage < 2:
+        autoGenC.Append(UefiUnloadImageString[NumUnloadImage], Dict)
+    else:
+        autoGenC.Append(UefiUnloadImageString[2], Dict)
+
+def CreateGuidDefinitionCode(info, autoGenC, autoGenH):
+    if info.IsLibrary:
+        return
+    #
+    # GUIDs
+    #
+    for Key in info.GuidList:
+        autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID  %s = %s;\n' % (Key, info.GuidList[Key]))
+
+def CreateProtocolDefinitionCode(info, autoGenC, autoGenH):
+    if info.IsLibrary:
+        return
+    #
+    # Protocol GUIDs
+    #
+    for Key in info.ProtocolList:
+        autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID  %s = %s;\n' % (Key, info.ProtocolList[Key]))
+
+def CreatePpiDefinitionCode(info, autoGenC, autoGenH):
+    if info.IsLibrary:
+        return
+    #
+    # PPI GUIDs
+    #
+    for Key in info.PpiList:
+        autoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID  %s = %s;\n' % (Key, info.PpiList[Key]))
+
+def CreatePcdCode(info, autoGenC, autoGenH):
+    if info.IsLibrary:
+        for pcd in info.PcdList:
+            CreateLibraryPcdCode(info, autoGenC, autoGenH, pcd)
+    else:
+        for pcd in info.PcdList:
+            CreateModulePcdCode(info, autoGenC, autoGenH, pcd)
+    CreatePcdDatabaseCode(info, autoGenC, autoGenH)
+
+def CreateUnicodeStringCode(info, autoGenC, autoGenH):
+    if len(info.UnicodeFileList) == 0:
+        return
+
+    cwd = os.getcwd()
+    os.chdir(info.WorkspaceDir)
+
+    incList = [os.path.join(info.WorkspaceDir, inc) for inc in info.IncludePathList]
+    hCode, cCode = GetStringFiles(info.UnicodeFileList, incList, [], info.Name)
+    autoGenC.Append("\n//\n//Unicode String Pack Definition\n//\n")
+    autoGenC.Append(cCode)
+    autoGenC.Append("\n")
+    autoGenH.Append("\n//\n//Unicode String ID\n//\n")
+    autoGenH.Append(hCode)
+    autoGenH.Append("\n#define STRING_ARRAY_NAME %sStrings\n" % info.Name)
+    os.chdir(cwd)
+
+def CreateHeaderCode(info, autoGenC, autoGenH):
+    # file header
+    autoGenH.Append(AutoGenHeaderString,   {'FileName':'AutoGen.h'})
+    # header file Prologue
+    autoGenH.Append(AutoGenHPrologueString,{'Guid':info.Guid.replace('-','_')})
+    # specification macros
+    autoGenH.Append(SpecificationString,   {'Specification':info.MacroList})
+    # header files includes
+    autoGenH.Append("#include <%s>\n" % BasicHeaderFile)
+
+    if info.IsLibrary:
+        return
+
+    # C file header
+    autoGenC.Append(AutoGenHeaderString, {'FileName':'AutoGen.c'})
+    # C file header files includes
+    for inc in ModuleTypeHeaderFile[info.ModuleType]:
+        autoGenC.Append("#include <%s>\n" % inc)
+
+    #
+    # Publish the CallerId Guid
+    #
+    if info.ModuleType == 'BASE':
+        autoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED GUID  gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(info.Guid))
+    else:
+        autoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID  gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(info.Guid))
+
+def CreateFooterCode(info, autoGenC, autoGenH):
+    autoGenH.Append(AutoGenHEpilogueString)
+
+def CreateCode(info, autoGenC, autoGenH):
+    CreateHeaderCode(info, autoGenC, autoGenH)
+
+    CreateLibraryConstructorCode(info, autoGenC, autoGenH)
+    CreateLibraryDestructorCode(info, autoGenC, autoGenH)
+    CreateModuleEntryPointCode(info, autoGenC, autoGenH)
+    CreateModuleUnloadImageCode(info, autoGenC, autoGenH)
+    CreateGuidDefinitionCode(info, autoGenC, autoGenH)
+    CreateProtocolDefinitionCode(info, autoGenC, autoGenH)
+    CreatePpiDefinitionCode(info, autoGenC, autoGenH)
+    CreatePcdCode(info, autoGenC, autoGenH)
+    CreateUnicodeStringCode(info, autoGenC, autoGenH)
+
+    CreateFooterCode(info, autoGenC, autoGenH)
+
+def Generate(filePath, autoGenC, autoGenH):
+    CreateDirectory(filePath)
+
+    autoGenFileList = []
+    SaveFile(os.path.join(filePath, "AutoGen.h"), autoGenH.String)
+    autoGenFileList.append("AutoGen.h")
+
+    if autoGenC.String != "":
+        SaveFile(os.path.join(filePath, "AutoGen.c"), autoGenC.String)
+        autoGenFileList.append("AutoGen.c")
+
+    return autoGenFileList
+
+def SaveFile(file, content):
+    f = None
+    if os.path.exists(file):
+        f = open(file, "r")
+        if content == f.read():
+            f.close()
+            return
+        f.close()
+    f = open(file, "w")
+    f.write(content)
+    f.close()
diff --git a/Source/Python/AutoGen/GenDepex.py b/Source/Python/AutoGen/GenDepex.py
new file mode 100644 (file)
index 0000000..24f028c
--- /dev/null
@@ -0,0 +1,237 @@
+# Copyright (c) 2007, Intel Corporation
+# All rights reserved. This program and the accompanying materials
+# are licensed and made available under the terms and conditions of the BSD License
+# which accompanies this distribution.    The full text of the license may be found at
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+
+#
+# This file is used to generate DEPEX file for module's dependency expression
+#
+
+import sys
+import os
+import re
+from StringIO import StringIO
+from struct import pack
+from EdkIIWorkspace import CreateDirectory
+from BuildToolError import *
+
+gType2Phase = {
+    "BASE"              :   None,
+    "SEC"               :   "PEI",
+    "PEI_CORE"          :   "PEI",
+    "PEIM"              :   "PEI",
+    "DXE_CORE"          :   "DXE",
+    "DXE_DRIVER"        :   "DXE",
+    "DXE_SMM_DRIVER"    :   "DXE",
+    "DXE_RUNTIME_DRIVER":   "DXE",
+    "DXE_SAL_DRIVER"    :   "DXE",
+    "UEFI_DRIVER"       :   "DXE",
+    "UEFI_APPLICATION"  :   "DXE",
+}
+
+class DependencyExpression:
+
+    OpcodePriority = {
+        "AND"   :   1,
+        "OR"    :   1,
+        "NOT"   :   2,
+        "SOR"   :   9,
+        "BEFORE":   9,
+        "AFTER" :   9,
+    }
+
+    Opcode = {
+        "PEI"   : {
+            "PUSH"  :   0x02,
+            "AND"   :   0x03,
+            "OR"    :   0x04,
+            "NOT"   :   0x05,
+            "TRUE"  :   0x06,
+            "FALSE" :   0x07,
+            "END"   :   0x08
+        },
+
+        "DXE"   : {
+            "BEFORE":   0x00,
+            "AFTER" :   0x01,
+            "PUSH"  :   0x02,
+            "AND"   :   0x03,
+            "OR"    :   0x04,
+            "NOT"   :   0x05,
+            "TRUE"  :   0x06,
+            "FALSE" :   0x07,
+            "END"   :   0x08,
+            "SOR"   :   0x09
+        }
+    }
+
+    SupportedOpcode = ["BEFORE", "AFTER", "PUSH", "AND", "OR", "NOT", "TRUE", "FALSE", "END", "SOR"]
+    
+    NonEndingOpcode = ["AND", "OR"]
+
+    ExclusiveOpcode = ["BEFORE", "AFTER"]
+    
+    AboveAllOpcode = ["SOR"]
+
+    #
+    # open and close brace must be taken as individual tokens
+    #
+    TokenPattern = re.compile("(\(|\)|\{[^{}]+\{[^{}]+\}[ ]*\}|\w+)")
+    
+    def __init__(self, expression, mtype):
+        self.Phase = gType2Phase[mtype]
+        if type(expression) == type([]):
+            self.ExpressionString = " ".join(expression)
+            self.TokenList = expression
+        else:
+            self.ExpressionString = expression
+            self.GetExpressionTokenList()
+
+        self.PostfixNotation = []
+        self.OpcodeList = []
+
+        self.GetPostfixNotation()
+        self.ValidateOpcode()
+
+    def GetExpressionTokenList(self):
+        self.TokenList = self.TokenPattern.findall(self.ExpressionString)
+
+    def GetPostfixNotation(self):
+        stack = []
+        for token in self.TokenList:
+            if token == "(":
+                stack.append(token)
+            elif token == ")":
+                while len(stack) > 0:
+                    if stack[-1] == '(':
+                        stack.pop()
+                        break
+                    self.PostfixNotation.append(stack.pop())
+            elif token in self.OpcodePriority:
+                while len(stack) > 0:
+                    if stack[-1] == "(" or self.OpcodePriority[token] > self.OpcodePriority[stack[-1]]:
+                        break
+                    self.PostfixNotation.append(stack.pop())
+                stack.append(token)
+                self.OpcodeList.append(token)
+            else:
+                if token not in self.Opcode[self.Phase]:
+                    self.PostfixNotation.append("PUSH")
+                else:
+                    self.OpcodeList.append(token)
+                self.PostfixNotation.append(token)
+        while len(stack) > 0:
+            self.PostfixNotation.append(stack.pop())
+        self.PostfixNotation.append("END")
+        #print "  ","\n   ".join(self.PostfixNotation)
+
+    def ValidateOpcode(self):
+        for op in self.AboveAllOpcode:
+            if op in self.OpcodeList and op != self.OpcodeList[0]:
+                raise AutoGenError("Opcode=%s should be the first one in expression", op)
+        for op in self.ExclusiveOpcode:
+            if op in self.OpcodeList and len(self.OpcodeList) > 1:
+                raise AutoGenError("Opcode=%s should be only opcode in expression", op)
+        # print "######", self.ExpressionString
+        if self.TokenList[-1] in self.NonEndingOpcode:
+            raise AutoGenError("Extra %s at the end of dependency expression" % self.TokenList[-1])
+
+    def GetGuidValue(self, guid):
+        guidValueString = guid.replace("{", "").replace("}", "").replace(" ", "")
+        guidValueList = guidValueString.split(",")
+        if len(guidValueList) != 11:
+            raise AutoGenError("Invalid GUID value string or opcode: %s" % guid)
+        return pack("1I2H8B", *(int(value, 16) for value in guidValueList))
+
+    def SaveFile(self, file, content):
+        CreateDirectory(os.path.dirname(file))
+        f = None
+        if os.path.exists(file):
+            f = open(file, 'rb')
+            if content == f.read():
+                f.close()
+                return
+            f.close()
+        f = open(file, "wb")
+        f.write(content)
+        f.close()
+
+    def Generate(self, file=None):
+        buffer = StringIO()
+        for item in self.PostfixNotation:
+            if item in self.Opcode[self.Phase]:
+                buffer.write(pack("B", self.Opcode[self.Phase][item]))
+            else:
+                buffer.write(self.GetGuidValue(item))
+
+        filePath = ""
+        if file == None:
+            sys.stdout.write(buffer.getvalue())
+            filePath = "STDOUT"
+        else:
+            self.SaveFile(file, buffer.getvalue())
+            filePath = file
+
+        buffer.close()
+        return filePath
+
+versionNumber = "0.01"
+__version__ = "%prog Version " + versionNumber
+__copyright__ = "Copyright (c) 2007, Intel Corporation  All rights reserved."
+__usage__ = "%prog [options] [dependency_expression_file]"
+
+def GetOptions():
+    from optparse import OptionParser
+
+    parser = OptionParser(description=__copyright__, version=__version__, usage=__usage__)
+
+    parser.add_option("-o", "--output", dest="OutputFile", default=None, metavar="FILE",
+                      help="Specify the name of depex file to be generated")
+    parser.add_option("-t", "--module-type", dest="ModuleType", default=None,
+                      help="The type of module for which the dependency expression serves")
+    parser.add_option("-e", "--dependency-expression", dest="Expression", default="",
+                      help="The string of dependency expression. If this option presents, the input file will be ignored.")
+    parser.add_option("-v", "--verbose", dest="verbose", default=False, action="store_true",
+                      help="build with verbose information")
+    parser.add_option("-d", "--debug", dest="debug", default=False, action="store_true",
+                      help="build with debug information")
+    parser.add_option("-q", "--quiet", dest="quiet", default=False, action="store_true",
+                      help="build with little information")
+
+    return parser.parse_args()
+
+
+def Main():
+    option, input = GetOptions()
+    if option.ModuleType == None or option.ModuleType not in gType2Phase:
+        print "Module type is not specified or supported"
+        return -1
+
+    try:
+        if len(input) > 0 and option.Expression == "":
+            dxsFile = input[0]
+            dxsString = open(dxsFile, 'r').read().replace("\n", " ").replace("\r", " ")
+            dxsString = re.compile("DEPENDENCY_START(.+)DEPENDENCY_END").findall(dxsString)[0]
+        elif option.Expression != "":
+            dxsString = option.Expression
+        else:
+            print "No expression string or file given"
+            return -1
+
+        dpx = DependencyExpression(dxsString, option.ModuleType)
+
+        if option.OutputFile != None:
+            dpx.Generate(option.OutputFile)
+        else:
+            dpx.Generate()
+    except Exception, e:
+        return -1
+
+    return 0
+
+if __name__ == '__main__':
+    sys.exit(Main())
diff --git a/Source/Python/AutoGen/GenMake.py b/Source/Python/AutoGen/GenMake.py
new file mode 100644 (file)
index 0000000..d1d2f03
--- /dev/null
@@ -0,0 +1,1155 @@
+#!/usr/bin/env python\r
+\r
+"""Create makefile for MS nmake and GNU make"""\r
+\r
+import os, sys, string, re\r
+import os.path as path\r
+\r
+from SequentialDict import *\r
+from EdkIIWorkspaceBuild import *\r
+from EdkIIWorkspace import *\r
+from BuildInfo import *\r
+from BuildToolError import *\r
+\r
+gDependencyDatabase = {}    # file path : [dependent files list]\r
+gIncludePattern = re.compile("^[ \t#]*include[ \t]+[\"<]*([^\"<>]+)[>\" \t\n\r]*", re.MULTILINE | re.UNICODE)\r
+\r
+class AutoGenString(object):\r
+    def __init__(self):\r
+        self.String = ''\r
+\r
+    def __str__(self):\r
+        return self.String\r
+\r
+    def Append(self, AppendString, Dictionary=None):\r
+        if Dictionary == None:\r
+            self.String += AppendString\r
+        else:\r
+            while AppendString.find('${BEGIN}') >= 0:\r
+                Start = AppendString.find('${BEGIN}')\r
+                End   = AppendString.find('${END}')\r
+                SubString = AppendString[AppendString.find('${BEGIN}'):AppendString.find('${END}')+6]\r
+                \r
+                RepeatTime = -1\r
+                NewDict = {"BEGIN":"", "END":""}\r
+                for Key in Dictionary:\r
+                    if SubString.find('$' + Key) >= 0 or SubString.find('${' + Key + '}') >= 0:\r
+                        Value = Dictionary[Key]\r
+                        if type(Value) != type([]):\r
+                            NewDict[Key] = Value\r
+                            continue\r
+                        if RepeatTime < 0:\r
+                            RepeatTime = len(Value)\r
+                        elif RepeatTime != len(Value):\r
+                            raise AutoGenError(msg=Key + " has different repeat time from others!")\r
+                        NewDict[Key] = ""\r
+\r
+                NewString = ''\r
+                for Index in range(0, RepeatTime):\r
+                    for Key in NewDict:\r
+                        if Key == "BEGIN" or Key == "END" or type(Dictionary[Key]) != type([]):\r
+                            continue\r
+                        #print "###",Key\r
+                        NewDict[Key] = Dictionary[Key][Index]\r
+                    NewString += string.Template(SubString).safe_substitute(NewDict)\r
+                AppendString = AppendString[0:Start] + NewString + AppendString[End + 6:]\r
+\r
+            NewDict = {}\r
+            for Key in Dictionary:\r
+                if type(Dictionary[Key]) == type([]):\r
+                    continue\r
+                NewDict[Key] = Dictionary[Key]\r
+            self.String += string.Template(AppendString).safe_substitute(NewDict)\r
+\r
+\r
+MakefileHeader = '''#\r
+# DO NOT EDIT\r
+# This file is auto-generated by build utility\r
+#\r
+# Module Name:\r
+#\r
+#   %s\r
+#\r
+# Abstract:\r
+#\r
+#   Auto-generated makefile for building module and libraries\r
+#\r
+'''\r
+\r
+LibraryMakeCommand = '''cd %(makedir)s\r
+\t$(MAKE) $(MAKE_FLAGS) -f %(makefile)s %(target)s\r
+\tcd $(MODULE_BUILD_DIR)'''\r
+\r
+gMakeType = ""\r
+if sys.platform == "win32":\r
+    gMakeType = "nmake"\r
+else:\r
+    gMakeType = "gmake"\r
+\r
+gMakefileName = {"nmake" : "Makefile", "gmake" : "GNUmakefile"}\r
+\r
+gDirectorySeparator = {"nmake" : "\\", "gmake" : "/"}\r
+\r
+gCreateDirectoryCommand = {"nmake" : "mkdir", "gmake" : "mkdir -p"}\r
+gRemoveDirectoryCommand = {"nmake" : "rmdir /s /q", "gmake" : "rm -r -f"}\r
+gRemoveFileCommand = {"nmake" : "del /f /q", "gmake" : "rm -f"}\r
+\r
+OutputFlag = {\r
+    ("MSFT", "CC", "OUTPUT")      :   "/Fo",\r
+    ("MSFT", "SLINK", "OUTPUT")   :   "/OUT:",\r
+    ("MSFT", "DLINK", "OUTPUT")   :   "/OUT:",\r
+    ("MSFT", "ASMLINK", "OUTPUT") :   "/OUT:",\r
+    ("MSFT", "PCH", "OUTPUT")     :   "/Fp",\r
+    ("MSFT", "ASM", "OUTPUT")     :   "/Fo",\r
+    \r
+    ("INTEL", "CC", "OUTPUT")          :   "/Fo",\r
+    ("INTEL", "SLINK", "OUTPUT")       :   "/OUT:",\r
+    ("INTEL", "DLINK", "OUTPUT")       :   "/OUT:",\r
+    ("INTEL", "ASMLINK", "OUTPUT")     :   "/OUT:",\r
+    ("INTEL", "PCH", "OUTPUT")         :   "/Fp",\r
+    ("INTEL", "ASM", "OUTPUT")         :   "/Fo",\r
+    ("INTEL", "IPF", "ASM", "OUTPUT")  :   "-o ",\r
+\r
+    ("GCC", "CC", "OUTPUT")        :   "-o ",\r
+    ("GCC", "SLINK", "OUTPUT")     :   "-cr ",\r
+    ("GCC", "DLINK", "OUTPUT")     :   "-o ",\r
+    ("GCC", "ASMLINK", "OUTPUT")   :   "-o ",\r
+    ("GCC", "PCH", "OUTPUT")       :   "-o ",\r
+    ("GCC", "ASM", "OUTPUT")       :   "-o ",\r
+\r
+    ("OUTPUT")                     : "-o "\r
+}\r
+\r
+IncludeFlag = {"MSFT" : "/I", "GCC" : "-I"}\r
+\r
+gCustomMakefileTemplate = '''\r
+${makefile_header}\r
+\r
+#\r
+# Platform Macro Definition\r
+#\r
+PLATFORM_NAME = ${platform_name}\r
+PLATFORM_GUID = ${platform_guid}\r
+PLATFORM_VERSION = ${platform_version}\r
+PLATFORM_RELATIVE_DIR = ${platform_relative_directory}\r
+PLATFORM_DIR = $(WORKSPACE)${separator}${platform_relative_directory}\r
+PLATFORM_OUTPUT_DIR = ${platform_output_directory}\r
+\r
+#\r
+# Package Macro Definition\r
+#\r
+PACKAGE_NAME = ${package_name}\r
+PACKAGE_GUID = ${package_guid}\r
+PACKAGE_VERSION = ${package_version}\r
+PACKAGE_RELATIVE_DIR = ${package_relative_directory}\r
+PACKAGE_DIR = $(WORKSPACE)${separator}${package_relative_directory}\r
+\r
+#\r
+# Module Macro Definition\r
+#\r
+MODULE_NAME = ${module_name}\r
+MODULE_GUID = ${module_guid}\r
+MODULE_VERSION = ${module_version}\r
+MODULE_TYPE = ${module_type}\r
+MODULE_FILE_BASE_NAME = ${module_file_base_name}\r
+BASE_NAME = $(MODULE_NAME)\r
+MODULE_RELATIVE_DIR = ${module_relative_directory}\r
+MODULE_DIR = $(WORKSPACE)${separator}${module_relative_directory}\r
+\r
+#\r
+# Build Configuration Macro Definition\r
+#\r
+ARCH = ${architecture}\r
+TOOLCHAIN_TAG = ${toolchain_tag}\r
+TARGET = ${build_target}\r
+\r
+#\r
+# Build Directory Macro Definition\r
+#\r
+PLATFORM_BUILD_DIR = ${platform_build_directory}\r
+BUILD_DIR = ${platform_build_directory}${separator}${build_target}_${toolchain_tag}\r
+BIN_DIR = $(BUILD_DIR)${separator}${architecture}\r
+LIB_DIR = $(BIN_DIR)\r
+MODULE_BUILD_DIR = $(BUILD_DIR)${separator}${architecture}${separator}${module_relative_directory}${separator}${module_file_base_name}\r
+OUTPUT_DIR = $(MODULE_BUILD_DIR)${separator}OUTPUT\r
+DEBUG_DIR = $(MODULE_BUILD_DIR)${separator}DEBUG\r
+DEST_DIR_OUTPUT = $(OUTPUT_DIR)\r
+DEST_DIR_DEBUG = $(DEBUG_DIR)\r
+\r
+#\r
+# Default Tools Flags Macro Definition (from tools_def.txt by default)\r
+#\r
+${BEGIN}DEFAULT_${tool_code}_FLAGS = ${default_tool_flags}\r
+${END}\r
+\r
+#\r
+# Platform Tools Flags Macro Definition (from platform description file)\r
+#\r
+${BEGIN}PLATFORM_${tool_code}_FLAGS = ${platform_tool_flags}\r
+${END}\r
+\r
+#\r
+# Platform Tools Flags Macro Definition (from platform description file)\r
+#\r
+${BEGIN}MODULE_${tool_code}_FLAGS = ${module_tool_flags}\r
+${END}\r
+\r
+#\r
+# ToolsFlagMacro\r
+#\r
+${BEGIN}${tool_code}_FLAGS = $(DEFAULT_${tool_code}_FLAGS) $(PLATFORM_${tool_code}_FLAGS) $(MODULE_${tool_code}_FLAGS)\r
+${END}\r
+MAKE_FLAGS = /nologo\r
+\r
+#\r
+# ToolsPathMacro\r
+#\r
+${BEGIN}${tool_code} = ${tool_path}\r
+${END}\r
+\r
+${custom_makefile_content}\r
+\r
+#\r
+# Target used when called from platform makefile, which will bypass the build of dependent libraries\r
+#\r
+\r
+pbuild: init all\r
+\r
+\r
+#\r
+# Target used for library build, which will bypass the build of dependent libraries\r
+#\r
+\r
+lbuild: init all\r
+\r
+\r
+#\r
+# ModuleTarget\r
+#\r
+\r
+mbuild: init all\r
+\r
+\r
+#\r
+# Initialization target: print build information and create necessary directories\r
+#\r
+init:\r
+\t-@echo Building ... $(MODULE_NAME)-$(MODULE_VERSION) [$(ARCH)] in package $(PACKAGE_NAME)-$(PACKAGE_VERSION)\r
+\t-${create_directory_command} $(DEBUG_DIR) > NUL 2>&1\r
+\t-${create_directory_command} $(OUTPUT_DIR) > NUL 2>&1\r
+\t${BEGIN}-${create_directory_command} $(OUTPUT_DIR)${separator}${directory_to_be_created} > NUL 2>&1\r
+\t${END}\r
+\r
+'''\r
+\r
+gModuleMakefileTemplate = '''\r
+${makefile_header}\r
+\r
+#\r
+# Platform Macro Definition\r
+#\r
+PLATFORM_NAME = ${platform_name}\r
+PLATFORM_GUID = ${platform_guid}\r
+PLATFORM_VERSION = ${platform_version}\r
+PLATFORM_RELATIVE_DIR = ${platform_relative_directory}\r
+PLATFORM_DIR = $(WORKSPACE)${separator}${platform_relative_directory}\r
+PLATFORM_OUTPUT_DIR = ${platform_output_directory}\r
+\r
+#\r
+# Package Macro Definition\r
+#\r
+PACKAGE_NAME = ${package_name}\r
+PACKAGE_GUID = ${package_guid}\r
+PACKAGE_VERSION = ${package_version}\r
+PACKAGE_RELATIVE_DIR = ${package_relative_directory}\r
+PACKAGE_DIR = $(WORKSPACE)${separator}${package_relative_directory}\r
+\r
+#\r
+# Module Macro Definition\r
+#\r
+MODULE_NAME = ${module_name}\r
+MODULE_GUID = ${module_guid}\r
+MODULE_VERSION = ${module_version}\r
+MODULE_TYPE = ${module_type}\r
+MODULE_FILE_BASE_NAME = ${module_file_base_name}\r
+BASE_NAME = $(MODULE_NAME)\r
+MODULE_RELATIVE_DIR = ${module_relative_directory}\r
+MODULE_DIR = $(WORKSPACE)${separator}${module_relative_directory}\r
+\r
+#\r
+# Build Configuration Macro Definition\r
+#\r
+ARCH = ${architecture}\r
+TOOLCHAIN_TAG = ${toolchain_tag}\r
+TARGET = ${build_target}\r
+\r
+#\r
+# Build Directory Macro Definition\r
+#\r
+PLATFORM_BUILD_DIR = ${platform_build_directory}\r
+BUILD_DIR = ${platform_build_directory}${separator}${build_target}_${toolchain_tag}\r
+BIN_DIR = $(BUILD_DIR)${separator}${architecture}\r
+LIB_DIR = $(BIN_DIR)\r
+MODULE_BUILD_DIR = $(BUILD_DIR)${separator}${architecture}${separator}${module_relative_directory}${separator}${module_file_base_name}\r
+OUTPUT_DIR = $(MODULE_BUILD_DIR)${separator}OUTPUT\r
+DEBUG_DIR = $(MODULE_BUILD_DIR)${separator}DEBUG\r
+DEST_DIR_OUTPUT = $(OUTPUT_DIR)\r
+DEST_DIR_DEBUG = $(DEBUG_DIR)\r
+\r
+#\r
+# Default Tools Flags Macro Definition (from tools_def.txt by default)\r
+#\r
+${BEGIN}DEFAULT_${tool_code}_FLAGS = ${default_tool_flags}\r
+${END}\r
+\r
+#\r
+# Platform Tools Flags Macro Definition (from platform description file)\r
+#\r
+${BEGIN}PLATFORM_${tool_code}_FLAGS = ${platform_tool_flags}\r
+${END}\r
+\r
+#\r
+# Module Tools Flags Macro Definition (from platform/module description file)\r
+#\r
+${BEGIN}MODULE_${tool_code}_FLAGS = ${module_tool_flags}\r
+${END}\r
+\r
+#\r
+# Tools Flag Macro\r
+#\r
+${BEGIN}${tool_code}_FLAGS = $(DEFAULT_${tool_code}_FLAGS) $(PLATFORM_${tool_code}_FLAGS) $(MODULE_${tool_code}_FLAGS)\r
+${END}\r
+MAKE_FLAGS = /nologo\r
+\r
+#\r
+# Tools Path Macro\r
+#\r
+${BEGIN}${tool_code} = ${tool_path}\r
+${END}\r
+\r
+#\r
+# Build Macro\r
+#\r
+SOURCE_FILES = ${BEGIN}$(MODULE_DIR)${separator}${source_file} \\\r
+               ${END}${BEGIN}$(DEBUG_DIR)${separator}${auto_generated_file}\r
+               ${END}\r
+\r
+INC = ${BEGIN}${include_path_prefix}$(WORKSPACE)${separator}${include_path} \\\r
+      ${END}\r
+\r
+OBJECTS = ${BEGIN}$(OUTPUT_DIR)${separator}${object_file} \\\r
+          ${END}\r
+\r
+LIBS = ${BEGIN}$(LIB_DIR)${separator}${library_file} \\\r
+       ${END}\r
+\r
+COMMON_DEPS = ${BEGIN}$(WORKSPACE)${separator}${common_dependency_file} \\\r
+              ${END}\r
+\r
+ENTRYPOINT = ${module_entry_point}\r
+\r
+#\r
+# Target File Macro Definitions\r
+#\r
+PCH_FILE = $(OUTPUT_DIR)\$(MODULE_NAME).pch\r
+LIB_FILE = $(LIB_DIR)\$(MODULE_NAME).lib\r
+LLIB_FILE = $(OUTPUT_DIR)\$(MODULE_NAME)Local.lib\r
+DLL_FILE = $(DEBUG_DIR)\$(MODULE_NAME).dll\r
+EFI_FILE = $(OUTPUT_DIR)\$(MODULE_NAME).efi\r
+\r
+#\r
+# Overridable Target Macro Definitions\r
+#\r
+INIT_TARGET = init\r
+PCH_TARGET =\r
+LLIB_TARGET = $(LLIB_FILE)\r
+\r
+#\r
+# Default target, which will build dependent libraries in addition to source files\r
+#\r
+\r
+all: ${build_type}\r
+\r
+\r
+#\r
+# Target used when called from platform makefile, which will bypass the build of dependent libraries\r
+#\r
+\r
+pbuild: $(INIT_TARGET) $(PCH_TARGET) gen_obj $(LLIB_TARGET) $(EFI_FILE) $(DLL_FILE)\r
+\r
+\r
+#\r
+# Target used for library build, which will bypass the build of dependent libraries\r
+#\r
+\r
+lbuild: $(INIT_TARGET) $(PCH_TARGET) gen_obj $(LIB_FILE)\r
+\r
+\r
+#\r
+# ModuleTarget\r
+#\r
+\r
+mbuild: $(INIT_TARGET) gen_libs $(PCH_TARGET) gen_obj $(LLIB_TARGET) $(EFI_FILE) $(DLL_FILE)\r
+\r
+\r
+#\r
+# Initialization target: print build information and create necessary directories\r
+#\r
+init:\r
+\t-@echo Building ... $(MODULE_NAME)-$(MODULE_VERSION) [$(ARCH)] in package $(PACKAGE_NAME)-$(PACKAGE_VERSION)\r
+\t-${create_directory_command} $(DEBUG_DIR) > NUL 2>&1\r
+\t-${create_directory_command} $(OUTPUT_DIR) > NUL 2>&1\r
+\t${BEGIN}-${create_directory_command} $(OUTPUT_DIR)${separator}${directory_to_be_created} > NUL 2>&1\r
+\t${END}\r
+\r
+#\r
+# PCH Target\r
+#\r
+pch: $(PCH_FILE)\r
+\r
+\r
+#\r
+# Libs Target\r
+#\r
+libs: gen_libs\r
+\r
+\r
+#\r
+# Vfr Target\r
+#\r
+vfr: gen_vfr\r
+\r
+\r
+#\r
+# Obj Target\r
+#\r
+obj: $(PCH_TARGET) gen_obj\r
+\r
+\r
+#\r
+# LocalLib Target\r
+#\r
+locallib: $(PCH_TARGET) gen_obj $(LLIB_FILE)\r
+\r
+\r
+#\r
+# Dll Target\r
+#\r
+dll: gen_libs $(PCH_TARGET) gen_obj $(LLIB_TARGET) $(DLL_FILE)\r
+\r
+\r
+#\r
+# Efi Target\r
+#\r
+efi: gen_libs $(PCH_TARGET) gen_obj $(LLIB_TARGET) $(DLL_FILE) $(EFI_FILE)\r
+\r
+\r
+#\r
+# GenLibsTarget\r
+#\r
+gen_libs:\r
+\t${BEGIN}cd $(BUILD_DIR)${separator}$(ARCH)${separator}${dependent_library_build_directory}\r
+\t$(MAKE) $(MAKE_FLAGS)\r
+\t${END}cd $(MODULE_BUILD_DIR)\r
+\r
+#\r
+# GenVfrTarget\r
+#\r
+\r
+gen_vfr:\r
+\t@echo placeholder: processing vfr files\r
+\r
+#\r
+# Phony targets for objects\r
+#\r
+\r
+gen_obj: $(PCH_TARGET) $(OBJECTS)\r
+\r
+\r
+#\r
+# PCH file build target\r
+#\r
+\r
+$(PCH_FILE): $(DEP_FILES)\r
+\t$(PCH) $(CC_FLAGS) $(PCH_FLAGS) $(DEP_FILES)\r
+\r
+#\r
+# Local Lib file build target\r
+#\r
+\r
+$(LLIB_FILE): $(OBJECTS)\r
+\t"$(SLINK)" $(SLINK_FLAGS) /OUT:$(LLIB_FILE) $(OBJECTS)\r
+\r
+#\r
+# Library file build target\r
+#\r
+\r
+$(LIB_FILE): $(OBJECTS)\r
+\t"$(SLINK)" $(SLINK_FLAGS) /OUT:$(LIB_FILE) $(OBJECTS)\r
+\r
+#\r
+# DLL file build target\r
+#\r
+\r
+$(DLL_FILE): $(LIBS) $(LLIB_FILE)\r
+\t"$(DLINK)" $(DLINK_FLAGS) /OUT:$(DLL_FILE) $(DLINK_SPATH) $(LIBS) $(LLIB_FILE)\r
+\r
+#\r
+# EFI file build target\r
+#\r
+\r
+$(EFI_FILE): $(LIBS) $(LLIB_FILE)\r
+\t"$(DLINK)" $(DLINK_FLAGS) /OUT:$(EFI_FILE) $(DLINK_SPATH) $(LIBS) $(LLIB_FILE)\r
+\tGenFw -e ${module_type} -o $(EFI_FILE) $(EFI_FILE)\r
+\tcopy /y $(EFI_FILE) $(BIN_DIR)\r
+\r
+#\r
+# Individual Object Build Targets\r
+#\r
+${BEGIN}${object_build_target}\r
+${END}\r
+\r
+\r
+#\r
+# clean all intermediate files\r
+#\r
+\r
+clean:\r
+\t${remove_directory_command} $(OUTPUT_DIR) > NUL 2>&1\r
+\r
+#\r
+# clean all generated files\r
+#\r
+\r
+cleanall:\r
+\t${remove_directory_command} $(OUTPUT_DIR) $(DEBUG_DIR) > NUL 2>&1\r
+\t${remove_file_command} *.pdb *.idb > NUL 2>&1\r
+\r
+#\r
+# clean pre-compiled header files\r
+#\r
+\r
+cleanpch:\r
+\t${remove_file_command} /f /q $(OUTPUT_DIR)\*.pch > NUL 2>&1\r
+\r
+#\r
+# clean all dependent libraries built\r
+#\r
+\r
+cleanlib:\r
+\t${BEGIN}cd $(BUILD_DIR)${separator}$(ARCH)${separator}${dependent_library_build_directory}\r
+\t$(MAKE) $(MAKE_FLAGS) cleanall\r
+\t${END}cd $(MODULE_BUILD_DIR)\r
+\r
+'''\r
+\r
+gPlatformMakefileTemplate = '''\r
+${makefile_header}\r
+\r
+#\r
+# Platform Macro Definition\r
+#\r
+PLATFORM_NAME = ${platform_name}\r
+PLATFORM_GUID = ${platform_guid}\r
+PLATFORM_VERSION = ${platform_version}\r
+PLATFORM_DIR = $(WORKSPACE)${separator}${platform_relative_directory}\r
+PLATFORM_OUTPUT_DIR = ${platform_output_directory}\r
+\r
+#\r
+# Build Configuration Macro Definition\r
+#\r
+TOOLCHAIN_TAG = ${toolchain_tag}\r
+TARGET = ${build_target}\r
+MAKE_FLAGS = /nologo\r
+\r
+#\r
+# Build Directory Macro Definition\r
+#\r
+BUILD_DIR = ${platform_build_directory}${separator}${build_target}_${toolchain_tag}\r
+FV_DIR = ${platform_build_directory}${separator}${build_target}_${toolchain_tag}${separator}FV\r
+\r
+#\r
+# Default target\r
+#\r
+all: init build_libraries build_modules build_fds\r
+\r
+#\r
+# Initialization target: print build information and create necessary directories\r
+#\r
+init:\r
+\t-@echo Building ... $(PLATFORM_NAME)-$(PLATFORM_VERSION) [${build_architecture_list}]\r
+\t-${create_directory_command} $(FV_DIR) > NUL 2>&1\r
+\t${BEGIN}-${create_directory_command} $(BUILD_DIR)${separator}${architecture} > NUL 2>&1\r
+\t${END}\r
+\t${BEGIN}-${create_directory_command} $(BUILD_DIR)${separator}${directory_to_be_created} > NUL 2>&1\r
+\t${END}\r
+#\r
+# library build target\r
+#\r
+libraries: init build_libraries\r
+\r
+#\r
+# module build target\r
+#\r
+modules: init build_libraries build_modules\r
+\r
+#\r
+# Flash Device Image Target\r
+#\r
+fds: init build_libraries build_modules build_fds\r
+\r
+#\r
+# Build all libraries:\r
+#\r
+build_libraries:\r
+\t${BEGIN}cd $(WORKSPACE)${separator}${library_build_directory}\r
+\t$(MAKE) $(MAKE_FLAGS) lbuild\r
+\t${END}cd $(BUILD_DIR)\r
+\r
+#\r
+# Build all modules:\r
+#\r
+build_modules:\r
+\t${BEGIN}cd $(WORKSPACE)${separator}${module_build_directory}\r
+\t$(MAKE) $(MAKE_FLAGS) pbuild\r
+\t${END}cd $(BUILD_DIR)\r
+\r
+#\r
+# Build Flash Device Image\r
+#\r
+build_fds:\r
+\t-@echo Generating flash image, if any ...\r
+${BEGIN}\tGenFds -f ${fdf_file} -o $(BUILD_DIR) -p ${active_platform}${END}\r
+\r
+#\r
+# run command for emulator platform only\r
+#\r
+run:\r
+\tcd $(BUILD_DIR)${separator}IA32\r
+\tSecMain\r
+\tcd $(BUILD_DIR)\r
+\r
+#\r
+# Clean intermediate files\r
+#\r
+clean:\r
+\t${BEGIN}cd $(WORKSPACE)${separator}${library_build_directory}\r
+\t$(MAKE) $(MAKE_FLAGS) clean\r
+\t${END}${BEGIN}cd $(WORKSPACE)${separator}${module_build_directory}\r
+\t$(MAKE) $(MAKE_FLAGS) clean\r
+\t${END}cd $(BUILD_DIR)\r
+\r
+#\r
+# Clean all generated files except to makefile\r
+#\r
+cleanall:\r
+\t${remove_directory_command} $(FV_DIR) > NUL 2>&1\r
+\t${BEGIN}${remove_directory_command} $(BUILD_DIR)${separator}${architecture} > NUL 2>&1\r
+\t${END}\r
+\r
+#\r
+# Clean all library files\r
+#\r
+cleanlib:\r
+\t${BEGIN}cd $(WORKSPACE)${separator}${library_build_directory}\r
+\t$(MAKE) $(MAKE_FLAGS) cleanall\r
+\t${END}cd $(BUILD_DIR)\r
+\r
+'''\r
+\r
+class Makefile(object):\r
+    def __init__(self, info, opt):\r
+        if isinstance(info, ModuleBuildInfo):\r
+            self.ModuleInfo = info\r
+            self.PlatformInfo = info.PlatformInfo\r
+            self.PackageInfo = info.PackageInfo\r
+            self.ModuleBuild = True\r
+            \r
+            self.BuildType = "mbuild"\r
+            if self.ModuleInfo.IsLibrary:\r
+                self.BuildType = "lbuild"\r
+                \r
+            self.BuildFileList = []\r
+            self.ObjectFileList = []\r
+            self.ObjectBuildTargetList = []\r
+\r
+            self.FileDependency = []\r
+            self.LibraryBuildCommandList = []\r
+            self.LibraryFileList = []\r
+            self.LibraryMakefileList = []\r
+            self.LibraryBuildDirectoryList = []\r
+\r
+        elif type(info) == type({}):    # and isinstance(info, PlatformBuildInfo):\r
+            self.PlatformInfo = info\r
+            self.ModuleBuild = False\r
+            self.ModuleBuildCommandList = []\r
+            self.ModuleMakefileList = []\r
+            self.ModuleBuildDirectoryList = self.GetModuleBuildDirectoryList()\r
+            self.LibraryBuildDirectoryList = self.GetLibraryBuildDirectoryList()\r
+        else:\r
+            raise AutoGenError(msg="Non-buildable item:%s" % str(info))\r
+\r
+        self.Opt = opt\r
+        self.BuildWithPch = opt["ENABLE_PCH"]\r
+        self.BuildWithLocalLib = opt["ENABLE_LOCAL_LIB"]\r
+        self.IntermediateDirectoryList = []\r
+\r
+    def PrepareDirectory(self):\r
+        if self.ModuleBuild:\r
+            CreateDirectory(path.join(self.ModuleInfo.WorkspaceDir, self.PlatformInfo.BuildDir))\r
+            CreateDirectory(path.join(self.ModuleInfo.WorkspaceDir, self.ModuleInfo.BuildDir))\r
+            CreateDirectory(path.join(self.ModuleInfo.WorkspaceDir, self.ModuleInfo.DebugDir))\r
+\r
+    def Generate(self, file=None, makeType=gMakeType):\r
+        if self.ModuleBuild:\r
+            return self.GenerateModuleMakefile(file, makeType)\r
+        else:\r
+            return self.GeneratePlatformMakefile(file, makeType)\r
+    \r
+    def GeneratePlatformMakefile(self, file=None, makeType=gMakeType):\r
+        separator = gDirectorySeparator[makeType]\r
+\r
+        activePlatform = self.PlatformInfo.values()[0].Platform\r
+        platformInfo = self.PlatformInfo.values()[0]\r
+        \r
+        outputDir = platformInfo.OutputDir\r
+        if os.path.isabs(outputDir):\r
+            self.PlatformBuildDirectory = outputDir\r
+        else:\r
+            self.PlatformBuildDirectory = "$(WORKSPACE)" + separator + outputDir\r
+\r
+        makefileName = gMakefileName[makeType]\r
+        makefileTemplateDict = {\r
+            "makefile_header"           : MakefileHeader % makefileName,\r
+            "platform_name"             : platformInfo.Name,\r
+            "platform_guid"             : platformInfo.Guid,\r
+            "platform_version"          : platformInfo.Version,\r
+            "platform_relative_directory": platformInfo.SourceDir,\r
+            "platform_output_directory" : platformInfo.OutputDir,\r
+            "platform_build_directory"  : self.PlatformBuildDirectory,\r
+\r
+            "toolchain_tag"             : platformInfo.ToolChain,\r
+            "build_target"              : platformInfo.BuildTarget,\r
+            "build_architecture_list"   : " ".join(self.PlatformInfo.keys()),\r
+            "architecture"              : self.PlatformInfo.keys(),\r
+            "separator"                 : separator,\r
+            "create_directory_command"  : gCreateDirectoryCommand[makeType],\r
+            "remove_directory_command"  : gRemoveDirectoryCommand[makeType],\r
+            "remove_file_command"       : gRemoveFileCommand[makeType],\r
+            "directory_to_be_created"   : self.IntermediateDirectoryList,\r
+            "library_build_directory"   : self.LibraryBuildDirectoryList,\r
+            "module_build_directory"    : self.ModuleBuildDirectoryList,\r
+            "fdf_file"                  : platformInfo.FdfFileList,\r
+            "active_platform"           : activePlatform.DescFilePath\r
+        }\r
+\r
+        self.PrepareDirectory()\r
+\r
+        autoGenMakefile = AutoGenString()\r
+        autoGenMakefile.Append(gPlatformMakefileTemplate, makefileTemplateDict)\r
+        #print autoGenMakefile.String\r
+\r
+        filePath = ""\r
+        if file == None:\r
+            filePath = path.join(platformInfo.WorkspaceDir, platformInfo.MakefileDir, makefileName)\r
+        else:\r
+            filePath = file\r
+\r
+        self.SaveFile(filePath, str(autoGenMakefile))\r
+        return filePath\r
+\r
+    def GenerateModuleMakefile(self, file=None, makeType=gMakeType):\r
+        if makeType in self.ModuleInfo.CustomMakefile and self.ModuleInfo.CustomMakefile[makeType] != "":\r
+            return self.GenerateCustomBuildMakefile(file, makeType)\r
+\r
+        separator = gDirectorySeparator[makeType]\r
+\r
+        if os.path.isabs(self.PlatformInfo.OutputDir):\r
+            self.PlatformBuildDirectory = self.PlatformInfo.OutputDir\r
+        else:\r
+            self.PlatformBuildDirectory = "$(WORKSPACE)" + separator + self.PlatformInfo.OutputDir\r
+\r
+        self.ProcessSourceFileList(makeType)\r
+        self.ProcessDependentLibrary(makeType)\r
+\r
+        entryPoint = "_ModuleEntryPoint"\r
+        if self.ModuleInfo.Arch == "EBC":\r
+            entryPoint = "EfiStart"\r
+\r
+        defaultToolFlag = self.PlatformInfo.DefaultToolOption.values()\r
+        if self.ModuleInfo.ModuleType == "USER_DEFINED":\r
+            defaultToolFlag = ["" for p in defaultToolFlag]\r
+            \r
+        makefileName = gMakefileName[makeType]\r
+        makefileTemplateDict = {\r
+            "makefile_header"           : MakefileHeader % makefileName,\r
+            "platform_name"             : self.PlatformInfo.Name,\r
+            "platform_guid"             : self.PlatformInfo.Guid,\r
+            "platform_version"          : self.PlatformInfo.Version,\r
+            "platform_relative_directory": self.PlatformInfo.SourceDir,\r
+            "platform_output_directory" : self.PlatformInfo.OutputDir,\r
+\r
+            "package_name"              : self.PackageInfo.Name,\r
+            "package_guid"              : self.PackageInfo.Guid,\r
+            "package_version"           : self.PackageInfo.Version,\r
+            "package_relative_directory": self.PackageInfo.SourceDir,\r
+\r
+            "module_name"               : self.ModuleInfo.Name,\r
+            "module_guid"               : self.ModuleInfo.Guid,\r
+            "module_version"            : self.ModuleInfo.Version,\r
+            "module_type"               : self.ModuleInfo.ModuleType,\r
+            "module_file_base_name"     : self.ModuleInfo.FileBase,\r
+            "module_relative_directory" : self.ModuleInfo.SourceDir,\r
+\r
+            "architecture"              : self.ModuleInfo.Arch,\r
+            "toolchain_tag"             : self.ModuleInfo.ToolChain,\r
+            "build_target"              : self.ModuleInfo.BuildTarget,\r
+\r
+            "platform_build_directory"  : self.PlatformBuildDirectory,\r
+\r
+            "separator"                 : separator,\r
+            "default_tool_flags"        : defaultToolFlag,\r
+            "platform_tool_flags"       : [self.PlatformInfo.BuildOption[tool] for tool in self.PlatformInfo.ToolPath],\r
+            "module_tool_flags"         : [self.ModuleInfo.BuildOption[tool] for tool in self.PlatformInfo.ToolPath],\r
+\r
+            "tool_code"                 : self.PlatformInfo.ToolPath.keys(),\r
+            "tool_path"                 : self.PlatformInfo.ToolPath.values(),\r
+\r
+            "module_entry_point"        : entryPoint,\r
+            "source_file"               : self.BuildFileList,\r
+            #"auto_generated_file"       : self.AutoGenBuildFileList,\r
+            "include_path_prefix"       : "-I",\r
+            "include_path"              : self.ModuleInfo.IncludePathList,\r
+            "object_file"               : self.ObjectFileList,\r
+            "library_file"              : self.LibraryFileList,\r
+            "common_dependency_file"    : self.CommonFileDependency,\r
+            "create_directory_command"  : gCreateDirectoryCommand[makeType],\r
+            "remove_directory_command"  : gRemoveDirectoryCommand[makeType],\r
+            "remove_file_command"       : gRemoveFileCommand[makeType],\r
+            "directory_to_be_created"   : self.IntermediateDirectoryList,\r
+            "dependent_library_build_directory" : self.LibraryBuildDirectoryList,\r
+            #"dependent_library_makefile"        : [path.join(bdir, makefileName) for bdir in self.LibraryBuildDirectoryList],\r
+            "object_build_target"               : self.ObjectBuildTargetList,\r
+            "build_type"                        : self.BuildType,\r
+        }\r
+        \r
+        self.PrepareDirectory()\r
+        \r
+        autoGenMakefile = AutoGenString()\r
+        autoGenMakefile.Append(gModuleMakefileTemplate, makefileTemplateDict)\r
+        #print autoGenMakefile.String\r
+        \r
+        filePath = ""\r
+        if file == None:\r
+            filePath = path.join(self.ModuleInfo.WorkspaceDir, self.ModuleInfo.MakefileDir, makefileName)\r
+        else:\r
+            filePath = file\r
+\r
+        self.SaveFile(filePath, str(autoGenMakefile))\r
+        return filePath\r
+\r
+    def GenerateCustomBuildMakefile(self, file=None, makeType=gMakeType):\r
+        separator = gDirectorySeparator[makeType]\r
+\r
+        if os.path.isabs(self.PlatformInfo.OutputDir):\r
+            self.PlatformBuildDirectory = self.PlatformInfo.OutputDir\r
+        else:\r
+            self.PlatformBuildDirectory = "$(WORKSPACE)" + separator + self.PlatformInfo.OutputDir\r
+\r
+        customMakefile = open(os.path.join(self.ModuleInfo.WorkspaceDir, self .ModuleInfo.CustomMakefile[makeType]), 'r').read()\r
+        \r
+        makefileName = gMakefileName[makeType]\r
+        makefileTemplateDict = {\r
+            "makefile_header"           : MakefileHeader % makefileName,\r
+            "platform_name"             : self.PlatformInfo.Name,\r
+            "platform_guid"             : self.PlatformInfo.Guid,\r
+            "platform_version"          : self.PlatformInfo.Version,\r
+            "platform_relative_directory": self.PlatformInfo.SourceDir,\r
+            "platform_output_directory" : self.PlatformInfo.OutputDir,\r
+\r
+            "package_name"              : self.PackageInfo.Name,\r
+            "package_guid"              : self.PackageInfo.Guid,\r
+            "package_version"           : self.PackageInfo.Version,\r
+            "package_relative_directory": self.PackageInfo.SourceDir,\r
+\r
+            "module_name"               : self.ModuleInfo.Name,\r
+            "module_guid"               : self.ModuleInfo.Guid,\r
+            "module_version"            : self.ModuleInfo.Version,\r
+            "module_type"               : self.ModuleInfo.ModuleType,\r
+            "module_file_base_name"     : self.ModuleInfo.FileBase,\r
+            "module_relative_directory" : self.ModuleInfo.SourceDir,\r
+\r
+            "architecture"              : self.ModuleInfo.Arch,\r
+            "toolchain_tag"             : self.ModuleInfo.ToolChain,\r
+            "build_target"              : self.ModuleInfo.BuildTarget,\r
+\r
+            "platform_build_directory"  : self.PlatformBuildDirectory,\r
+\r
+            "separator"                 : separator,\r
+            "default_tool_flags"        : self.PlatformInfo.DefaultToolOption.values(),\r
+            "platform_tool_flags"       : self.PlatformInfo.BuildOption.values(),\r
+            "module_tool_flags"         : self.ModuleInfo.BuildOption.values(),\r
+\r
+            "tool_code"                 : self.PlatformInfo.ToolPath.keys(),\r
+            "tool_path"                 : self.PlatformInfo.ToolPath.values(),\r
+\r
+            "create_directory_command"  : "-@mkdir",\r
+            "directory_to_be_created"   : self.IntermediateDirectoryList,\r
+            "dependent_library_build_directory" : self.LibraryBuildDirectoryList,\r
+            "custom_makefile_content"   : customMakefile\r
+        }\r
+\r
+        self.PrepareDirectory()\r
+\r
+        autoGenMakefile = AutoGenString()\r
+        autoGenMakefile.Append(gCustomMakefileTemplate, makefileTemplateDict)\r
+        #print autoGenMakefile.String\r
+\r
+        filePath = ""\r
+        if file == None:\r
+            filePath = path.join(self.ModuleInfo.WorkspaceDir, self.ModuleInfo.MakefileDir, makefileName)\r
+        else:\r
+            filePath = file\r
+\r
+        self.SaveFile(filePath, str(autoGenMakefile))\r
+        return filePath\r
+\r
+    def SaveFile(self, file, content):\r
+        # print "######",file,"######"\r
+        f = None\r
+        if os.path.exists(file):\r
+            f = open(file, 'r')\r
+            if content == f.read():\r
+                f.close()\r
+                return\r
+            f.close()\r
+        f = open(file, "w")\r
+        f.write(content)\r
+        f.close()\r
+\r
+    def ProcessSourceFileList(self, makeType=gMakeType):\r
+        rule = self.PlatformInfo.BuildRule\r
+        separator = gDirectorySeparator[makeType]\r
+\r
+        self.BuildFileList = []\r
+        self.ObjectFileList = []\r
+        self.ObjectBuildTargetList = []\r
+        self.AutoGenBuildFileList = []\r
+        self.IntermediateDirectoryList = []\r
+\r
+        fileBuildTemplatetList = []\r
+        forceIncludedFile = []\r
+\r
+        for f in self.ModuleInfo.AutoGenFileList:\r
+            fpath = path.join(self.ModuleInfo.DebugDir, f)\r
+            fdir = path.dirname(f)\r
+            if fdir == "":\r
+                fdir = "."\r
+            fname = path.basename(f)\r
+            fbase, fext = path.splitext(fname)\r
+\r
+            ftype = rule.FileTypeMapping[fext]\r
+            if ftype == "C-Header":\r
+                forceIncludedFile.append(fpath)\r
+            if ftype not in rule.Makefile[makeType]:\r
+                continue\r
+\r
+            self.BuildFileList.append(fpath)\r
+            self.ObjectFileList.append(fdir + separator + fbase + ".obj")\r
+\r
+            fileBuildTemplatetList.append({\r
+                                   "string" : rule.Makefile[makeType][ftype],\r
+                                   "ftype"  : ftype,\r
+                                   "fpath"  : fpath,\r
+                                   "fdir"   : fdir,\r
+                                   "fname"  : fname,\r
+                                   "fbase"  : fbase,\r
+                                   "fext"   : fext,\r
+                                   "fdep"   : "",\r
+                                   "sep"    : separator,\r
+                                   })\r
+\r
+        fileList = self.ModuleInfo.SourceFileList\r
+        for f in fileList:\r
+            fpath = os.path.join(self.ModuleInfo.SourceDir, f)\r
+            fname = path.basename(f)\r
+            fbase, fext = path.splitext(fname)\r
+            fdir = path.dirname(f)\r
+            \r
+            if fdir == "":\r
+                fdir = "."\r
+            elif fdir not in self.IntermediateDirectoryList:\r
+                self.IntermediateDirectoryList.append(fdir)\r
+                \r
+            ftype = rule.FileTypeMapping[fext]\r
+            if ftype not in rule.Makefile[makeType]:\r
+                continue\r
+\r
+            self.BuildFileList.append(fpath)\r
+            self.ObjectFileList.append(fdir + separator + fbase + ".obj")\r
+            \r
+            fileBuildTemplatetList.append({\r
+                                   "string" : rule.Makefile[makeType][ftype],\r
+                                   "ftype"  : ftype,\r
+                                   "fpath"  : fpath,\r
+                                   "fdir"   : fdir,\r
+                                   "fname"  : fname,\r
+                                   "fbase"  : fbase,\r
+                                   "fext"   : fext,\r
+                                   "fdep"   : "",\r
+                                   "sep"    : separator,\r
+                                   })\r
+\r
+        #\r
+        # Search dependency file list for each source file\r
+        #\r
+        self.FileDependency = self.GetFileDependency(forceIncludedFile)\r
+        depSet = set(self.FileDependency.values()[0])\r
+        for dep in self.FileDependency.values():\r
+            depSet &= set(dep)\r
+        #\r
+        # Extract comman files list in the dependency files\r
+        #\r
+        self.CommonFileDependency = forceIncludedFile + list(depSet)\r
+        for f in self.FileDependency:\r
+            newDepSet = set(self.FileDependency[f])\r
+            newDepSet -= depSet\r
+            self.FileDependency[f] = list(newDepSet)\r
+\r
+        #\r
+        # Expand "fdep"\r
+        #\r
+        for template in fileBuildTemplatetList:\r
+            makefileString = AutoGenString()\r
+            template["fdep"] = self.FileDependency[template["fpath"]]\r
+            makefileString.Append(template["string"], template)\r
+            self.ObjectBuildTargetList.append(makefileString)\r
+\r
+    def ProcessDependentLibrary(self, makeType=gMakeType):\r
+        for libm in self.ModuleInfo.DependentLibraryList:\r
+            libf = str(libm)\r
+            libp = path.dirname(libf)\r
+            base = path.basename(libf).split(".")[0]\r
+            self.LibraryBuildDirectoryList.append(libp + gDirectorySeparator[makeType] + base)\r
+            self.LibraryFileList.append(libm.BaseName + ".lib")\r
+\r
+    def GetPlatformBuildDirectory(self):\r
+        if os.path.isabs(self.PlatformInfo.OutputDir):\r
+            return self.PlatformInfo.OutputDir\r
+        else:\r
+            return os.path.join("$(WORKSPACE)", self.PlatformInfo.OutputDir)\r
+\r
+    def GetFileDependency(self, forceList):\r
+        cwd = os.getcwd()\r
+        os.chdir(self.ModuleInfo.WorkspaceDir)\r
+        dependency = {}\r
+        for f in self.BuildFileList:\r
+            dependency[f] = self.GetDependencyList(f, forceList, self.ModuleInfo.IncludePathList)\r
+        os.chdir(cwd)\r
+        return dependency\r
+\r
+    def GetDependencyList(self, file, forceList, searchPathList):\r
+        cwd = os.getcwd()\r
+        os.chdir(self.ModuleInfo.WorkspaceDir)\r
+\r
+        EdkLogger.debug(EdkLogger.DEBUG_3, "Get dependency files for %s" % file)\r
+        EdkLogger.debug(EdkLogger.DEBUG_2, "Including %s" % " ".join(forceList))\r
+        fileStack = [file] + forceList\r
+        dependencyList = []\r
+        while len(fileStack) > 0:\r
+            EdkLogger.debug(EdkLogger.DEBUG_2, "Stack %s" % "\n\t".join(fileStack))\r
+            f = fileStack.pop()\r
+\r
+            currentFileDependencyList = []\r
+            if f in gDependencyDatabase:\r
+                currentFileDependencyList = gDependencyDatabase[f]\r
+                for dep in currentFileDependencyList:\r
+                    if dep not in fileStack and dep not in dependencyList:\r
+                        fileStack.append(dep)\r
+            else:\r
+                fd = open(f, 'r')\r
+                fileContent = fd.read()\r
+                fd.close()\r
+                if len(fileContent) == 0:\r
+                    continue\r
+\r
+                if fileContent[0] == 0xff or fileContent[0] == 0xfe:\r
+                    fileContent = unicode(fileContent, "utf-16")\r
+                includedFileList = gIncludePattern.findall(fileContent)\r
+\r
+                currentFilePath = os.path.dirname(f)\r
+                for inc in includedFileList:\r
+                    inc = os.path.normpath(inc)\r
+                    for searchPath in [currentFilePath] + searchPathList:\r
+                        filePath = os.path.join(searchPath, inc)\r
+                        if not os.path.exists(filePath) or filePath in currentFileDependencyList:\r
+                            continue\r
+                        currentFileDependencyList.append(filePath)\r
+                        if filePath not in fileStack and filePath not in dependencyList:\r
+                            fileStack.append(filePath)\r
+                        break\r
+                    else:\r
+                        #raise AutoGenError("%s included by %s was not found in any given path:\n\t%s" % (inc, f, "\n\t".join(searchPathList)))\r
+                        EdkLogger.verbose("%s included by %s was not found in any given path:\n\t%s" % (inc, f, "\n\t".join(searchPathList)))\r
+                gDependencyDatabase[f] = currentFileDependencyList\r
+            dependencyList.extend(currentFileDependencyList)\r
+        dependencyList = list(set(dependencyList))  # remove duplicate ones\r
+\r
+        os.chdir(cwd)\r
+        dependencyList.append(file)\r
+        return dependencyList\r
+\r
+    def GetModuleBuildDirectoryList(self):\r
+        dirList = []\r
+        for arch in self.PlatformInfo:\r
+            for ma in self.PlatformInfo[arch].ModuleAutoGenList:\r
+                dirList.append(ma.BuildInfo.BuildDir)\r
+        return dirList\r
+\r
+    def GetLibraryBuildDirectoryList(self):\r
+        dirList = []\r
+        for arch in self.PlatformInfo:\r
+            for la in self.PlatformInfo[arch].LibraryAutoGenList:\r
+                dirList.append(la.BuildInfo.BuildDir)\r
+        return dirList\r
+\r
+# This acts like the main() function for the script, unless it is 'import'ed into another\r
+# script.\r
+if __name__ == '__main__':\r
+    print "Running Operating System =", sys.platform\r
+    ewb = WorkspaceBuild()\r
+    #print ewb.Build.keys()\r
+    \r
+    myArch = ewb.Build["IA32"].Arch\r
+    #print myArch\r
+\r
+    myBuild = ewb.Build["IA32"]\r
+    \r
+    myWorkspace = ewb\r
+    apf = ewb.TargetTxt.TargetTxtDictionary["ACTIVE_PLATFORM"][0]\r
+    myPlatform = myBuild.PlatformDatabase[os.path.normpath(apf)]\r
+\r
+    for mf in myBuild.ModuleDatabase:\r
+        #mf = "MdePkg\\Library\\BaseLib\\BaseLib.inf"\r
+        #if mf in myPlatform.Modules and mf in myBuild.ModuleDatabase:\r
+        #print mf\r
+\r
+        myModule = myBuild.ModuleDatabase[mf]\r
+\r
+        myPackage = FindModuleOwner(myModule.DescFilePath, myBuild.PackageDatabase)\r
+\r
+        myToolchain = ewb.TargetTxt.TargetTxtDictionary["TOOL_CHAIN_TAG"][0]\r
+        #print myToolchain\r
+\r
+        myBuildTarget = ewb.TargetTxt.TargetTxtDictionary["TARGET"][0]\r
+        #print myBuildTarget\r
+\r
+        myBuildOption = {\r
+            "ENABLE_PCH"        :   False,\r
+            "ENABLE_LOCAL_LIB"  :   True,\r
+        }\r
+\r
+        myMakefile = Makefile(myModule, myPackage, myPlatform, myWorkspace, myToolchain, myBuildTarget,\r
+                              myArch, myBuildOption, "nmake")\r
+\r
+        myMakefile.NewGenerate()\r
diff --git a/Source/Python/AutoGen/StrGather.py b/Source/Python/AutoGen/StrGather.py
new file mode 100644 (file)
index 0000000..b93582a
--- /dev/null
@@ -0,0 +1,290 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+#\r
+#This file is used to parse a strings file and create or add to a string database file.\r
+#\r
+\r
+import EdkLogger\r
+from UniClassObject import *\r
+from BuildToolError import *\r
+\r
+HexHeader = '0x'\r
+\r
+COMMENT = '// '\r
+DEFINE_STR = '#define'\r
+COMMENT_DEFINE_STR = COMMENT + DEFINE_STR\r
+NOT_REFERENCED = 'not referenced'\r
+COMMENT_NOT_REFERENCED = ' ' + COMMENT + NOT_REFERENCED\r
+CHAR_ARRAY_DEFIN = 'unsigned char'\r
+COMMON_FILE_NAME = 'Strings'\r
+OFFSET = 'offset'\r
+STRING = 'string'\r
+TO = 'to'\r
+STRING_TOKEN = 'STRING_TOKEN'\r
+\r
+LENGTH_EFI_HII_STRING_PACK_HEADER = 22\r
+LENGTH_STRING_OFFSET = 4\r
+\r
+H_C_FILE_HEADER = ['//', \\r
+                   '//  DO NOT EDIT -- auto-generated file', \\r
+                   '//', \\r
+                   '//  This file is generated by the string gather utility', \\r
+                   '//']\r
+LANGUAGE_NAME_STRING_NAME = '$LANGUAGE_NAME'\r
+PRINTABLE_LANGUAGE_NAME_STRING_NAME = '$PRINTABLE_LANGUAGE_NAME'\r
+\r
+def DecToHexStr(Dec, Digit):\r
+    return eval("'0x%0" + str(Digit) + "X' % int(Dec)")\r
+\r
+def DecToHexList(Dec):\r
+    Hex = "%08X" % int(Dec)\r
+    List = [HexHeader + Hex[6:8], HexHeader + Hex[4:6], HexHeader + Hex[2:4], HexHeader + Hex[0:2]]\r
+    return List\r
+\r
+def CreateHFileHeader(BaseName):\r
+    Str = ''\r
+    for Item in H_C_FILE_HEADER:\r
+        Str = WriteLine(Str, Item)\r
+    Str = WriteLine(Str, '#ifndef _' + BaseName.upper() + '_STRINGS_DEFINE_H_')\r
+    Str = WriteLine(Str, '#define _' + BaseName.upper() + '_STRINGS_DEFINE_H_')\r
+    return Str\r
+\r
+def CreateHFileContent(BaseName, UniObjectClass):\r
+    Str = ''\r
+    ValueStartPtr = 60\r
+    Line = COMMENT_DEFINE_STR + ' ' + LANGUAGE_NAME_STRING_NAME + ' ' * (ValueStartPtr - len(DEFINE_STR + LANGUAGE_NAME_STRING_NAME)) + DecToHexStr(0, 4) + COMMENT_NOT_REFERENCED\r
+    Str = WriteLine(Str, Line)\r
+    Line = COMMENT_DEFINE_STR + ' ' + PRINTABLE_LANGUAGE_NAME_STRING_NAME + ' ' * (ValueStartPtr - len(DEFINE_STR + PRINTABLE_LANGUAGE_NAME_STRING_NAME)) + DecToHexStr(1, 4) + COMMENT_NOT_REFERENCED\r
+    Str = WriteLine(Str, Line)\r
+    for Index in range(2, len(UniObjectClass.OrderedStringList[UniObjectClass.LanguageDef[0][0]])):\r
+        StringItem = UniObjectClass.OrderedStringList[UniObjectClass.LanguageDef[0][0]][Index]\r
+        Name = StringItem.StringName\r
+        Token = StringItem.Token\r
+        Referenced = StringItem.Referenced\r
+        if Name != None:\r
+            Line = ''\r
+            if Referenced == True:\r
+                Line = DEFINE_STR + ' ' + Name + ' ' * (ValueStartPtr - len(DEFINE_STR + Name)) + DecToHexStr(Token, 4)\r
+            else:\r
+                Line = COMMENT_DEFINE_STR + ' ' + Name + ' ' * (ValueStartPtr - len(DEFINE_STR + Name)) + DecToHexStr(Token, 4) + COMMENT_NOT_REFERENCED\r
+            Str = WriteLine(Str, Line)\r
+    \r
+    Str =  WriteLine(Str, '')\r
+    Str = WriteLine(Str, 'extern unsigned char ' + BaseName + 'Strings[];')\r
+    return Str\r
+\r
+def CreateHFile(BaseName, UniObjectClass):\r
+    #HFile = WriteLine('', CreateHFileHeader(BaseName))\r
+    HFile = WriteLine('', CreateHFileContent(BaseName, UniObjectClass))\r
+    #HFile = WriteLine(HFile, '#endif')\r
+    return HFile\r
+\r
+def CreateCFileHeader():\r
+    Str = ''\r
+    for Item in H_C_FILE_HEADER:\r
+        Str = WriteLine(Str, Item)\r
+    \r
+    return Str\r
+  \r
+def CreateArrayItem(Value, Width = 16):\r
+    MaxLength = Width\r
+    Index = 0\r
+    Line = '  '\r
+    ArrayItem = ''\r
+    \r
+    for Item in Value:\r
+        if Index < MaxLength:\r
+            Line = Line + Item + ', '\r
+            Index = Index + 1\r
+        else:\r
+            ArrayItem = WriteLine(ArrayItem, Line)\r
+            Line = '  ' + Item +  ', '\r
+            Index = 1\r
+    ArrayItem = Write(ArrayItem, Line.rstrip())\r
+    \r
+    return ArrayItem\r
+\r
+def CreateCFileStringDef(Name, Offset, Token, UseOtherLangDef = ''):\r
+    Comment = ''\r
+    if UseOtherLangDef != '':\r
+        Comment = ' - not defined for this language -- using secondary language ' + UniToStr(UseOtherLangDef) + ' definition'\r
+    Str = Write('', CreateArrayItem(DecToHexList(Offset)) + '  ' + COMMENT + 'offset to string ' + Name + ' (' + DecToHexStr(Token, 4) + ')' + Comment)\r
+\r
+    return Str\r
+    \r
+def CreateCFileStringValue(Name, Language, Value, Offset):    \r
+    Str = WriteLine('  ', COMMENT + STRING + ' ' + Name + ' ' + OFFSET + ' ' + DecToHexStr(Offset, 8))\r
+    Str = WriteLine(Str, CreateArrayItem(Value))\r
+    \r
+    return Str\r
+\r
+def CreateCFileContent(BaseName, UniObjectClass):\r
+    Str = ''\r
+\r
+    Str = WriteLine(Str, CHAR_ARRAY_DEFIN + ' ' + BaseName + COMMON_FILE_NAME + '[] = {\n' )\r
+    for IndexI in range(len(UniObjectClass.LanguageDef)):\r
+        Language = UniObjectClass.LanguageDef[IndexI][0]\r
+        LangPrintName = UniObjectClass.LanguageDef[IndexI][1]\r
+        Length = 0\r
+        NameLength = 0\r
+        Count = 0\r
+        for Item in UniObjectClass.OrderedStringList[Language]:\r
+            if Item.Referenced:\r
+                Length = Length + Item.Length\r
+                Count = Count + 1\r
+\r
+        Str = WriteLine(Str, '//******************************************************************************')\r
+        Str = WriteLine(Str, COMMENT + 'Start of string definitions for ' + Language)\r
+        \r
+        #\r
+        # EFI_HII_STRING_PACK_HEADER\r
+        #\r
+        Offset = LENGTH_EFI_HII_STRING_PACK_HEADER + LENGTH_STRING_OFFSET * Count\r
+        Length = Offset + Length\r
+        List = DecToHexList(Length) + DecToHexList(2)[0:2] + DecToHexList(Offset) + DecToHexList(Offset + len(UniToHexList(Language)) + 2) + DecToHexList(Count) + DecToHexList(0)\r
+        Str = WriteLine(Str, CreateArrayItem(List, 8))\r
+        \r
+        Str = WriteLine(Str, '  // offset 0x16')\r
+        StrStringDef = ''\r
+        StrStringValue = ''\r
+        for Item in UniObjectClass.OrderedStringList[Language]:\r
+            Name = Item.StringName\r
+            Value = Item.StringValueByteList\r
+            Referenced = Item.Referenced\r
+            Token = Item.Token\r
+            Length = Item.Length\r
+            UseOtherLangDef = Item.UseOtherLangDef\r
+             \r
+            if Referenced:\r
+                StrStringDef = WriteLine(StrStringDef, CreateCFileStringDef(Name, Offset, Token, UseOtherLangDef))\r
+                StrStringValue = Write(StrStringValue, CreateCFileStringValue(Name, Language, Value, Offset))\r
+                Offset = Offset + Length\r
+            else:\r
+                StrStringDef = WriteLine(StrStringDef, '  ' + COMMENT + Name + ' ' + NOT_REFERENCED)\r
+\r
+        Str = WriteLine(Str, StrStringDef)\r
+        Str = WriteLine(Str, StrStringValue)\r
+    return Str\r
+\r
+def CreateCFileEnd():\r
+    Str = WriteLine('  ', '// strings terminator pack')\r
+    Str = WriteLine(Str, '  ' + '0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ')\r
+    Str = WriteLine(Str, '  ' + '0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ')\r
+    Str = Write(Str, '};')\r
+    return Str\r
+\r
+def CreateCFile(BaseName, UniObjectClass):\r
+    #CFile = WriteLine('', CreateCFileHeader())\r
+    CFile = WriteLine('', CreateCFileContent(BaseName, UniObjectClass))\r
+    CFile = WriteLine(CFile, CreateCFileEnd())\r
+    return CFile\r
+\r
+def GetFileList(IncludeList, SkipList):\r
+    if IncludeList == None:\r
+        raise AutoGenError("Include path for unicode file is not defined")\r
+    \r
+    FileList = []\r
+    if SkipList == None:\r
+        SkipList = []\r
+        \r
+    for Dir in IncludeList:\r
+        for File in os.listdir(Dir):\r
+            File = os.path.join(Dir, os.path.normcase(File))\r
+            #\r
+            # Ignore Dir\r
+            #\r
+            if os.path.isfile(File) != True:\r
+                continue\r
+            #\r
+            # Ignore file listed in skip list\r
+            #\r
+            IsSkip = False\r
+            for Skip in SkipList:\r
+                if os.path.splitext(File)[1].upper() == Skip.upper():\r
+                    IsSkip = True\r
+                    break\r
+            \r
+            if not IsSkip:\r
+                FileList.append(File)\r
+    \r
+    return FileList\r
+\r
+def SearchString(UniObjectClass, FileList):\r
+    if FileList == []:\r
+        return UniObjectClass\r
+    \r
+    for File in FileList:\r
+        if os.path.isfile(File):\r
+            Lines = open(File, 'r')\r
+            for Line in Lines:\r
+                if Line.find(STRING_TOKEN) > 0:\r
+                    Line = Line[Line.find(STRING_TOKEN) : ]\r
+                    StringList = Line.split(STRING_TOKEN)\r
+                    for Line in StringList:\r
+                        Line = Line.strip()\r
+                        StrName = Line[Line.find('(') + len('(') : Line.find(')')].strip()\r
+                        UniObjectClass.SetStringReferenced(StrName)\r
+     \r
+    UniObjectClass.ReToken()\r
+\r
+    return UniObjectClass\r
+\r
+def GetStringFiles(UniFilList, IncludeList, SkipList, BaseName):\r
+    Status = True\r
+    ErrorMessage = ''\r
+    \r
+    if len(UniFilList) > 0:\r
+        Uni = UniFileClassObject(UniFilList)\r
+    else:\r
+        raise AutoGenError('No unicode files given')\r
+    \r
+    FileList = GetFileList(IncludeList, SkipList)\r
+    \r
+    Uni = SearchString(Uni, FileList)\r
+    \r
+    HFile = CreateHFile(BaseName, Uni)\r
+    CFile = CreateCFile(BaseName, Uni)\r
+    \r
+    return HFile, CFile\r
+\r
+def Write(Target, Item):\r
+    return Target + Item\r
+\r
+def WriteLine(Target, Item):\r
+    return Target + Item + '\n'\r
+    \r
+# This acts like the main() function for the script, unless it is 'import'ed into another\r
+# script.\r
+if __name__ == '__main__':\r
+    EdkLogger.info('start')\r
+    \r
+    UniFileList = ['C:\\Tiano\\Edk\\Sample\\Universal\\UserInterface\\SetupBrowser\\Dxe\\DriverSample\\inventorystrings.uni', 'C:\\Tiano\\Edk\\Sample\\Universal\\UserInterface\\SetupBrowser\\Dxe\\DriverSample\\VfrStrings.uni']\r
+    IncludeList = ['C:\\Tiano\\Edk\\Sample\\Universal\\UserInterface\\SetupBrowser\\Dxe\\DriverSample']\r
+#    UniFileList = (['C:\\Tiano\\Edk\\Sample\\Platform\\Generic\\Dxe\\PlatformBds\\DeviceMngr\\DeviceManagerStrings.uni'])\r
+#    UniFileList.append('C:\\Tiano\\Edk\\Sample\\Platform\\Generic\\Dxe\\PlatformBds\\BootMngr\\BootManagerStrings.uni')\r
+#    UniFileList.append('C:\\Tiano\\Edk\\Sample\\Platform\\Generic\\Dxe\\PlatformBds\\Strings.uni')\r
+#    UniFileList.append('C:\\Tiano\\Edk\\Sample\\Platform\\Generic\\Dxe\\PlatformBds\\FrontPageStrings.uni')\r
+#\r
+#    IncludeList = ['C:\\Tiano\\Edk\\Sample\\Platform\\Generic\\']\r
+#    IncludeList.append('C:\\Tiano\\Edk\\Sample\\Platform\\Generic\\Dxe\\PlatformBds\\BootMngr\\')\r
+#    IncludeList.append('C:\\Tiano\\Edk\\Sample\\Platform\\Generic\\Dxe\\')\r
+#    IncludeList.append('C:\\Tiano\\Edk\\Sample\\Platform\\Generic\\Dxe\\PlatformBds\\')\r
+#    IncludeList.append('C:\\Tiano\\Edk\\Sample\\Platform\\Generic\\Dxe\\PlatformBds\\DeviceMngr\\')\r
+   \r
+    \r
+    SkipList = ['.inf', '.uni']\r
+    BaseName = 'SetupBrowser'\r
+    (h, c) = GetStringFiles(UniFileList, IncludeList, SkipList, BaseName)\r
+    hfile = open('C:\string.h', 'w')\r
+    cfile = open('C:\string.c', 'w')\r
+    hfile.write(h)\r
+    cfile.write(c)\r
+    \r
+    EdkLogger.info('end')\r
diff --git a/Source/Python/AutoGen/UniClassObject.py b/Source/Python/AutoGen/UniClassObject.py
new file mode 100644 (file)
index 0000000..282149b
--- /dev/null
@@ -0,0 +1,322 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+#\r
+#This file is used to collect all defined strings in multiple uni files \r
+#\r
+\r
+import os, codecs\r
+import EdkLogger\r
+from BuildToolError import *\r
+\r
+UNICODE_WIDE_CHAR = u'\\wide'\r
+UNICODE_NARROW_CHAR = u'\\narrow'\r
+UNICODE_NON_BREAKING_CHAR = u'\\nbr'\r
+UNICODE_UNICODE_CR = '\r'\r
+UNICODE_UNICODE_LF = '\n'\r
+\r
+NARROW_CHAR = u'\uFFF0'\r
+WIDE_CHAR = u'\uFFF1'\r
+NON_BREAKING_CHAR = u'\uFFF2'\r
+CR = u'\u000D'\r
+LF = u'\u000A'\r
+NULL = u'\u0000'\r
+TAB = u'\t'\r
+BACK_SPLASH = u'\\'\r
+\r
+def UniToStr(Uni):\r
+    return repr(Uni)[2:-1]\r
+\r
+def UniToHexList(Uni):\r
+    List = []\r
+    for Item in Uni:\r
+        Temp = '%04X' % ord(Item)\r
+        List.append('0x' + Temp[2:4])\r
+        List.append('0x' + Temp[0:2])\r
+    return List\r
+\r
+class StringDefClassObject(object):\r
+    def __init__(self, Name = None, Value = None, Referenced = False, Token = None, UseOtherLangDef = ''):\r
+        self.StringName = ''\r
+        self.StringNameByteList = []\r
+        self.StringValue = ''\r
+        self.StringValueByteList = ''\r
+        self.Token = 0\r
+        self.Referenced = Referenced\r
+        self.UseOtherLangDef = UseOtherLangDef\r
+        self.Length = 0\r
+        \r
+        if Name != None:\r
+            self.StringName = Name\r
+            self.StringNameByteList = UniToHexList(Name)\r
+        if Value != None:\r
+            self.StringValue = Value + u'\x00'        # Add a NULL at string tail\r
+            self.StringValueByteList = UniToHexList(self.StringValue)\r
+            self.Length = len(self.StringValueByteList)\r
+        if Token != None:\r
+            self.Token = Token\r
+\r
+    def __str__(self):\r
+        return repr(self.StringName) + ' ' + \\r
+               repr(self.Token) + ' ' + \\r
+               repr(self.Referenced) + ' ' + \\r
+               repr(self.StringValue)\r
+\r
+class UniFileClassObject(object):\r
+    def __init__(self, FileList = []):\r
+        self.FileList = FileList\r
+        self.Token = 2\r
+        self.LanguageDef = []                   #[ [u'LanguageIdentifier', u'PrintableName'], ... ]\r
+        self.OrderedStringList = {}             #{ u'LanguageIdentifier' : [StringDefClassObject]  }\r
+        \r
+        if len(self.FileList) > 0:\r
+            self.LoadUniFiles(FileList)\r
+\r
+    def GetLangDef(self, Line):\r
+        Lang = Line.split()\r
+        if len(Lang) != 3:\r
+            raise ParseError("""Wrong language definition '""" + Line + """' which should be '#langdef eng "English"'""")\r
+        else:\r
+            LangName = Lang[1]\r
+            LangPrintName = Lang[2][1:-1]\r
+\r
+        if [LangName, LangPrintName] not in self.LanguageDef:\r
+            self.LanguageDef.append([LangName, LangPrintName])\r
+        \r
+        #\r
+        # Add language string\r
+        #\r
+        self.AddStringToList(u'$LANGUAGE_NAME', LangName, LangName, 0, True)\r
+        self.AddStringToList(u'$PRINTABLE_LANGUAGE_NAME', LangName, LangPrintName, 1, True)\r
+\r
+        return True\r
+        \r
+    def GetStringObject(self, Item):\r
+        Name = ''\r
+        Language = ''\r
+        Value = ''\r
+        \r
+        Name = Item.split()[1]\r
+        LanguageList = Item.split(u'#language ')\r
+        for IndexI in range(len(LanguageList)):\r
+            if IndexI == 0:\r
+                continue\r
+            else:\r
+                Language = LanguageList[IndexI].split()[0]\r
+                Value = LanguageList[IndexI][LanguageList[IndexI].find(u'\"') + len(u'\"') : LanguageList[IndexI].rfind(u'\"')].replace(u'\r\n', u'')\r
+                self.AddStringToList(Name, Language, Value)\r
+    \r
+    def GetIncludeFile(self, Item, Dir):\r
+        FileName = Item[Item.find(u'#include ') + len(u'#include ') :Item.find(u' ', len(u'#include '))][1:-1]\r
+        self.LoadUniFile(FileName)\r
+    \r
+    def PreProcess(self, FileIn):\r
+        Lines = []\r
+        #\r
+        # Use unique identifier\r
+        #\r
+        for Index in range(len(FileIn)):\r
+            if FileIn[Index].startswith(u'//') or FileIn[Index] == u'\r\n':\r
+                continue\r
+            FileIn[Index] = FileIn[Index].replace(u'/langdef', u'#langdef')\r
+            FileIn[Index] = FileIn[Index].replace(u'/string', u'#string')\r
+            FileIn[Index] = FileIn[Index].replace(u'/language', u'#language')\r
+            FileIn[Index] = FileIn[Index].replace(u'/include', u'#include')\r
+                        \r
+            FileIn[Index] = FileIn[Index].replace(UNICODE_WIDE_CHAR, WIDE_CHAR)\r
+            FileIn[Index] = FileIn[Index].replace(UNICODE_NARROW_CHAR, NARROW_CHAR)\r
+            FileIn[Index] = FileIn[Index].replace(UNICODE_NON_BREAKING_CHAR, NON_BREAKING_CHAR)\r
+            FileIn[Index] = FileIn[Index].replace(u'\\r\\n', CR + LF)\r
+            FileIn[Index] = FileIn[Index].replace(u'\\n', CR + LF)\r
+            FileIn[Index] = FileIn[Index].replace(u'\\r', CR)\r
+            FileIn[Index] = FileIn[Index].replace(u'\\t', u'\t')\r
+            FileIn[Index] = FileIn[Index].replace(u'\\\\', u'\\')\r
+            FileIn[Index] = FileIn[Index].replace(u'''\"''', u'''"''')\r
+            FileIn[Index] = FileIn[Index].replace(u'\t', u' ')\r
+#           if FileIn[Index].find(u'\\x'):\r
+#               hex = FileIn[Index][FileIn[Index].find(u'\\x') + 2 : FileIn[Index].find(u'\\x') + 6]\r
+#               hex = "u'\\u" + hex + "'"\r
+                        \r
+            Lines.append(FileIn[Index])\r
+        \r
+        return Lines\r
+    \r
+    def LoadUniFile(self, File = None):\r
+        if File != None:\r
+            if os.path.exists(File) and os.path.isfile(File):\r
+                Dir = File.rsplit('\\', 1)[0]\r
+                FileIn = codecs.open(File, mode='rb', encoding='utf-16').readlines()             \r
+                \r
+                #\r
+                # Process special char in file\r
+                #\r
+                Lines = self.PreProcess(FileIn)\r
+                \r
+                #\r
+                # Get Unicode Information\r
+                #\r
+                for IndexI in range(len(Lines)):\r
+                    Line = Lines[IndexI]\r
+                    #\r
+                    # Ignore comment line and empty line\r
+                    #\r
+                    if Line.startswith(u'//') or Line.strip() == u'\r\n':\r
+                        continue\r
+                    \r
+                    if (IndexI + 1) < len(Lines):\r
+                        SecondLine = Lines[IndexI + 1]\r
+                    if (IndexI + 2) < len(Lines):\r
+                        ThirdLine = Lines[IndexI + 2]\r
+                                            \r
+                    #\r
+                    # Get Language def information\r
+                    # \r
+                    if Line.find(u'#langdef ') >= 0:\r
+                        self.GetLangDef(Line)\r
+                        continue\r
+                    \r
+#                    if Line.find(u'#include ') >= 0:\r
+#                        self.GetIncludeFile(Line, Dir)\r
+#                        continue\r
+                    \r
+                    Name = ''\r
+                    Language = ''\r
+                    Value = ''\r
+                    #\r
+                    # Get string def information format 1 as below\r
+                    #\r
+                    #     #string MY_STRING_1\r
+                    #     #language eng\r
+                    #     My first English string line 1\r
+                    #     My first English string line 2\r
+                    #     #string MY_STRING_1\r
+                    #     #language spa\r
+                    #     Mi segunda secuencia 1\r
+                    #     Mi segunda secuencia 2\r
+                    #\r
+                    if Line.find(u'#string ') >= 0 and Line.find(u'#language ') < 0 and \\r
+                        SecondLine.find(u'#string ') < 0 and SecondLine.find(u'#language ') >= 0 and \\r
+                        ThirdLine.find(u'#string ') < 0 and ThirdLine.find(u'#language ') < 0:\r
+                        Name = Line[Line.find(u'#string ') + len(u'#string ') : ].strip()\r
+                        Language = SecondLine[SecondLine.find(u'#language ') + len(u'#language ') : ].strip()\r
+                        for IndexJ in range(IndexI + 2, len(Lines)):\r
+                            if Lines[IndexJ].find(u'#string ') < 0 and Lines[IndexJ].find(u'#language ') < 0:\r
+                                Value = Value + Lines[IndexJ]\r
+                            else:\r
+                                IndexI = IndexJ\r
+                                break\r
+                        Value = Value.replace(u'\r\n', u'')\r
+                        self.AddStringToList(Name, Language, Value)\r
+                        continue\r
+                    \r
+                    #\r
+                    # Get string def information format 2 as below\r
+                    #\r
+                    #     #string MY_STRING_1     #language eng     "My first English string line 1"\r
+                    #                                               "My first English string line 2"\r
+                    #                             #language spa     "Mi segunda secuencia 1"\r
+                    #                                               "Mi segunda secuencia 2"\r
+                    #     #string MY_STRING_2     #language eng     "My first English string line 1"\r
+                    #                                               "My first English string line 2"\r
+                    #     #string MY_STRING_2     #language spa     "Mi segunda secuencia 1"\r
+                    #                                               "Mi segunda secuencia 2"\r
+                    #\r
+                    if Line.find(u'#string ') >= 0 and Line.find(u'#language ') >= 0:\r
+                        StringItem = Line\r
+                        for IndexJ in range(IndexI + 1, len(Lines)):\r
+                            if Lines[IndexJ].find(u'#string ') >= 0 and Lines[IndexJ].find(u'#language ') >= 0:\r
+                                IndexI = IndexJ\r
+                                break\r
+                            elif Lines[IndexJ].find(u'#string ') < 0 and Lines[IndexJ].find(u'#language ') >= 0:\r
+                                StringItem = StringItem + Lines[IndexJ]\r
+                            elif Lines[IndexJ].find(u'\"') >= 2:\r
+                                StringItem = StringItem[ : StringItem.rfind(u'\"')] + Lines[IndexJ][Lines[IndexJ].find(u'\"') + len(u'\"') : ]\r
+                        self.GetStringObject(StringItem)              \r
+            else:\r
+                raise ParseError(File + ' is not a valid file')\r
+    \r
+    def LoadUniFiles(self, FileList = []):\r
+        if len(FileList) > 0:\r
+            for File in FileList:\r
+                self.LoadUniFile(File)\r
+                \r
+    def AddStringToList(self, Name, Language, Value, Token = None, Referenced = False, UseOtherLangDef = ''):\r
+        if Language not in self.OrderedStringList:\r
+            self.OrderedStringList[Language] = []\r
+        \r
+        IsAdded = False\r
+        for Item in self.OrderedStringList[Language]:\r
+            if Name == Item.StringName:\r
+                IsAdded = True\r
+                break\r
+        if not IsAdded:\r
+            Token = len(self.OrderedStringList[Language])\r
+            self.OrderedStringList[Language].append(StringDefClassObject(Name, Value, Referenced, Token, UseOtherLangDef))\r
+    \r
+    def SetStringReferenced(self, Name):\r
+        for Lang in self.OrderedStringList:\r
+            for Item in self.OrderedStringList[Lang]:\r
+                if Name == Item.StringName:\r
+                    Item.Referenced = True\r
+                    break\r
+    \r
+    def FindStringValue(self, Name, Lang):\r
+        for Item in self.OrderedStringList[Lang]:\r
+            if Item.StringName == Name:\r
+                return Item\r
+        \r
+        return None\r
+    \r
+    def ReToken(self):\r
+        #\r
+        # Search each string to find if it is defined for each language\r
+        # Use secondary language value to replace if missing in any one language\r
+        #           \r
+        for IndexI in range(0, len(self.LanguageDef)):\r
+            LangKey = self.LanguageDef[IndexI][0]\r
+            for Item in self.OrderedStringList[LangKey]:\r
+                Name = Item.StringName\r
+                Value = Item.StringValue[0:-1]\r
+                Referenced = Item.Referenced\r
+                for IndexJ in range(0, len(self.LanguageDef)):\r
+                    LangFind = self.LanguageDef[IndexJ][0]\r
+                    if self.FindStringValue(Name, LangFind) == None:\r
+                        Token = len(self.OrderedStringList[LangFind])\r
+                        self.AddStringToList(Name, LangFind, Value, Token, Referenced, LangKey)\r
+        \r
+        #\r
+        # Retoken\r
+        #\r
+        for Lang in self.LanguageDef:\r
+            LangName = Lang[0]\r
+            ReferencedStringList = []\r
+            NotReferencedStringList = []\r
+            Token = 0\r
+            for Item in self.OrderedStringList[LangName]:\r
+                if Item.Referenced == True:\r
+                    Item.Token = Token\r
+                    ReferencedStringList.append(Item)\r
+                    Token = Token + 1\r
+                else:\r
+                    NotReferencedStringList.append(Item)\r
+            self.OrderedStringList[LangName] = ReferencedStringList\r
+            for Index in range(len(NotReferencedStringList)):\r
+                NotReferencedStringList[Index].Token = Token + Index\r
+                self.OrderedStringList[LangName].append(NotReferencedStringList[Index])\r
+            \r
+# This acts like the main() function for the script, unless it is 'import'ed into another\r
+# script.\r
+if __name__ == '__main__':\r
+    a = UniFileClassObject(['C:\\Tiano\\Edk\\Sample\\Universal\\UserInterface\\SetupBrowser\\Dxe\\DriverSample\\inventorystrings.uni', 'C:\\Tiano\\Edk\\Sample\\Universal\\UserInterface\\SetupBrowser\\Dxe\\DriverSample\\VfrStrings.uni'])\r
+    print a.LanguageDef\r
+    print a.OrderedStringList\r
+    for i in a.OrderedStringList:\r
+        print i\r
+        for m in a.OrderedStringList[i]:\r
+            print str(m)\r
diff --git a/Source/Python/AutoGen/__init__.py b/Source/Python/AutoGen/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/Source/Python/CalcDeps/__init__.py b/Source/Python/CalcDeps/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/Source/Python/Common/BuildToolError.py b/Source/Python/Common/BuildToolError.py
new file mode 100644 (file)
index 0000000..3dfdd7b
--- /dev/null
@@ -0,0 +1,192 @@
+#
+# name
+# type
+# lineno
+# msg
+# arg
+# arg1
+# arg2
+# directory
+# resource
+# structure
+# attribute
+# port
+#
+
+FILE_NOT_FOUND = 0
+FILE_OPEN_FAILURE = 1
+FILE_WRITE_FAILURE = 2
+FILE_PARSE_FAILURE = 3
+FILE_READ_FAILURE = 4
+FILE_CREATE_FAILURE = 5
+FILE_CHECKSUM_FAILURE = 6
+FILE_COMPRESS_FAILURE = 7
+FILE_DECOMPRESS_FAILURE = 8
+FILE_MOVE_FAILURE = 9
+FILE_DELETE_FAILURE = 10
+FILE_COPY_FAILURE = 11
+FILE_POSITIONING_FAILURE = 12
+FILE_ALREADY_EXIST = 13
+FILE_UNKNOWN_ERROR = 0x0FFF
+
+OPTION_UNKNOWN = 0x1000
+OPTION_MISSING = 0x1001
+OPTION_CONFLICT = 0x1002
+OPTION_VALUE_INVALID = 0x1003
+OPTION_DEPRECATED = 0x1004
+OPTION_NOT_SUPPORTED = 0x1005
+OPTION_UNKNOWN_ERROR = 0x1FFF
+
+PARAMETER_INVALID = 0x2000
+PARAMETER_MISSING = 0x2001
+PARAMETER_UNKNOWN_ERROR =0x2FFF
+
+FORMAT_INVALID = 0x3000
+FORMAT_NOT_SUPPORTED = 0x3001
+FORMAT_UNKNOWN = 0x3002
+FORMAT_UNKNOWN_ERROR = 0x3FFF
+
+RESOURCE_NOT_AVAILABLE = 0x4000
+RESOURCE_ALLOCATE_FAILURE = 0x4001
+RESOURCE_FULL = 0x4002
+RESOURCE_OVERFLOW = 0x4003
+RESOURCE_UNDERRUN = 0x4004
+RESOURCE_UNKNOWN_ERROR = 0x4FFF
+
+ATTRIBUTE_NOT_AVAILABLE = 0x5000
+ATTRIBUTE_GET_FAILURE = 0x5001
+ATTRIBUTE_SET_FAILURE = 0x5002
+ATTRIBUTE_UPDATE_FAILURE = 0x5003
+ATTRIBUTE_ACCESS_DENIED = 0x5004
+ATTRIBUTE_UNKNOWN_ERROR = 0x5FFF
+
+IO_NOT_READY = 0x6000
+IO_BUSY = 0x6001
+IO_TIMEOUT = 0x6002
+IO_UNKNOWN_ERROR = 0x6FFF
+
+AUTOGEN_ERROR = 0xF000
+PARSER_ERROR = 0xF001
+GENFDS_ERROR = 0xF002
+UNKNOWN_ERROR = 0xFFFF
+
+gKeyWord = ["name", "type", "lineno", "msg", "arg", "arg1", "arg2", "directory",
+            "resource", "structure", "attribute", "port", "usage"]
+
+gErrorMessage = {
+    FILE_NOT_FOUND          :   "File not found: %(name)s",
+    FILE_OPEN_FAILURE       :   "Opening file: %(name)s",
+    FILE_WRITE_FAILURE      :   "Writing file: %(name)s",
+    FILE_PARSE_FAILURE      :   "Parsing file: %(name)s",
+    FILE_READ_FAILURE       :   "Reading file: %(name)s",
+    FILE_CREATE_FAILURE     :   "Creating file: %(name)s",
+    FILE_CHECKSUM_FAILURE   :   "Invalid checksum of file: %(name)s",
+    FILE_COMPRESS_FAILURE   :   "Compressing file: %(name)s",
+    FILE_DECOMPRESS_FAILURE :   "Decompressing file: %(name)s",
+    FILE_MOVE_FAILURE       :   "Moving file: %(name)s",
+    FILE_DELETE_FAILURE     :   "Deleting file: %(name)s",
+    FILE_COPY_FAILURE       :   "Copying file: %(name)s",
+    FILE_POSITIONING_FAILURE:   "Seeking position of ile: %(name)s",
+    FILE_ALREADY_EXIST      :   "File or directory already exists: %(name)s",
+    FILE_UNKNOWN_ERROR      :   "Unknown error encountered on file: %(name)s",
+
+    OPTION_UNKNOWN          :   "Unknown option: %(name)s\n%(usage)s",
+    OPTION_MISSING          :   "Missing option: %(name)s\n%(usage)s",
+    OPTION_CONFLICT         :   "Conflict options: %(arg1) <-> %(arg2)\n%(usage)s",
+    OPTION_VALUE_INVALID    :   "Invalid value of option: %(name)s\n%(usage)s",
+    OPTION_DEPRECATED       :   "Deprecated option: %(name)s\n%(usage)s",
+    OPTION_NOT_SUPPORTED    :   "Unsupported option: %(name)s\n%(usage)s",
+    OPTION_UNKNOWN_ERROR    :   "Unknown error when processing options",
+
+    PARAMETER_INVALID       :   "Invalid parameter: %(name)s",
+    PARAMETER_MISSING       :   "Missing parameter: %(name)s",
+    PARAMETER_UNKNOWN_ERROR :   "Unknown error in parameters",
+
+    FORMAT_INVALID          :   "Invalid sytax/format at line %(lineno) in %(name)s",
+    FORMAT_NOT_SUPPORTED    :   "Not supported: %(name)s",
+    FORMAT_UNKNOWN          :   "Unknown format: %(name)s",
+    FORMAT_UNKNOWN_ERROR    :   "Unknown error in %(name)s",
+
+    RESOURCE_NOT_AVAILABLE  :   "%(name)s is not available",
+    RESOURCE_ALLOCATE_FAILURE :   "Failed to allocate %(name)s",
+    RESOURCE_FULL           :   "%(name)s is full",
+    RESOURCE_OVERFLOW       :   "%(name)s is overflow",
+    RESOURCE_UNDERRUN       :   "%(name)s is underrun",
+    RESOURCE_UNKNOWN_ERROR  :   "Unkown error in %(name)s",
+
+    ATTRIBUTE_NOT_AVAILABLE :   "%(name)s is not available",
+    ATTRIBUTE_GET_FAILURE   :   "Failed to get %(name)s",
+    ATTRIBUTE_SET_FAILURE   :   "Failed to set %(name)s",
+    ATTRIBUTE_UPDATE_FAILURE:   "Failed to update %(name)s",
+    ATTRIBUTE_ACCESS_DENIED :   "Access denied: %(name)s",
+    ATTRIBUTE_UNKNOWN_ERROR :   "Unknown error when accessing %(name)s",
+
+    IO_NOT_READY            :   "%(name)s is not ready",
+    IO_BUSY                 :   "%(name)s is busy",
+    IO_TIMEOUT              :   "%(name)s timeout",
+    IO_UNKNOWN_ERROR        :   "Unknown error in %(name)s",
+
+    AUTOGEN_ERROR           :   "%(msg)s",
+    PARSER_ERROR            :   "%(msg)s",
+    GENFDS_ERROR            :   "%(msg)s",
+
+    UNKNOWN_ERROR           :   "Unknown error: %(msg)s",
+}
+
+class BuildToolError(Exception):
+    def __init__(self, code=0xffff, **kwargs):
+        if code not in gErrorMessage:
+            code = 0xffff
+
+        for key in gKeyWord:
+            if key not in kwargs:
+                kwargs[key] = "<Unknown>"
+
+        self.ErrorMessage = gErrorMessage[code] % kwargs
+        self.ErrorCode = 0xEEEE0000 + code
+
+    def __str__(self):
+        return "ERROR: %04X: %s" % (self.ErrorCode & 0xffff, self.ErrorMessage)
+
+class AutoGenError(BuildToolError):
+    def __init__(self, code=AUTOGEN_ERROR, **kwargs):
+        BuildToolError.__init__(self, code, **kwargs)
+
+    def __str__(self):
+        return "\nAutoGen: %s" % BuildToolError.__str__(self)
+
+class ParserError(BuildToolError):
+    def __init__(self, code=PARSER_ERROR, **kwargs):
+        BuildToolError.__init__(self, code, **kwargs)
+
+    def __str__(self):
+        return "\nParser: %s" % BuildToolError.__str__(self)
+
+class GenFdsError(BuildToolError):
+    def __init__(self, code=GENFDS_ERROR, **kwargs):
+        BuildToolError.__init__(self, code, **kwargs)
+
+    def __str__(self):
+        return "\nGenFds: %s" % BuildToolError.__str__(self)
+
+if __name__ == "__main__":
+    try:
+        raise AutoGenError(FILE_ALREADY_EXIST, name="my_fault.file")
+    except BuildToolError, e:
+        print e
+    except Exception, e:
+        print "Python:", e
+
+    try:
+        raise GenFdsError(msg="my fault")
+    except BuildToolError, e:
+        print e
+    except Exception, e:
+        print "Python:", e
+
+    try:
+        xyz = abc[1]
+    except BuildToolError, e:
+        print e
+    except Exception, e:
+        print "\nPython:", e
diff --git a/Source/Python/Common/DataType.py b/Source/Python/Common/DataType.py
new file mode 100644 (file)
index 0000000..fb6561d
--- /dev/null
@@ -0,0 +1,265 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+#\r
+#This file is used to define each tab used by INF/DEC/DSC files\r
+#\r
+\r
+#\r
+#Common Definitions\r
+#\r
+TAB_SPLIT = '.'\r
+TAB_COMMENT_SPLIT = '#'\r
+TAB_EQUAL_SPLIT = '='\r
+TAB_VALUE_SPLIT = '|'\r
+TAB_SPACE_SPLIT = ' '\r
+TAB_SECTION_START = '['\r
+TAB_SECTION_END = ']'\r
+TAB_OPTION_START = '<'\r
+TAB_OPTION_END  = '>'\r
+\r
+TAB_WORKSPACE1 = '${WORKSPACE}/'\r
+TAB_WORKSPACE2 = '$(WORKSPACE)/'\r
+\r
+TAB_ARCH_NULL = ''\r
+TAB_ARCH_COMMON = 'Common'\r
+TAB_ARCH_IA32 = 'IA32'\r
+TAB_ARCH_X64 = 'X64'\r
+TAB_ARCH_IPF = 'IPF'\r
+TAB_ARCH_EBC = 'EBC'\r
+\r
+ARCH_LIST = [TAB_ARCH_IA32, TAB_ARCH_X64, TAB_ARCH_IPF, TAB_ARCH_EBC]\r
+ARCH_LIST_FULL = [TAB_ARCH_COMMON] + ARCH_LIST \r
+\r
+SUP_MODULE_BASE = 'BASE'\r
+SUP_MODULE_SEC = 'SEC'\r
+SUP_MODULE_PEI_CORE = 'PEI_CORE'\r
+SUP_MODULE_PEIM = 'PEIM'\r
+SUP_MODULE_DXE_CORE = 'DXE_CORE'\r
+SUP_MODULE_DXE_DRIVER = 'DXE_DRIVER'\r
+SUP_MODULE_DXE_RUNTIME_DRIVER = 'DXE_RUNTIME_DRIVER'\r
+SUP_MODULE_DXE_SAL_DRIVER = 'DXE_SAL_DRIVER'\r
+SUP_MODULE_DXE_SMM_DRIVER = 'DXE_SMM_DRIVER'\r
+SUP_MODULE_UEFI_DRIVER = 'UEFI_DRIVER'\r
+SUP_MODULE_UEFI_APPLICATION = 'UEFI_APPLICATION'\r
+SUP_MODULE_USER_DEFINED = 'USER_DEFINED'\r
+\r
+SUP_MODULE_LIST = [SUP_MODULE_BASE, SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MODULE_PEIM, SUP_MODULE_DXE_CORE, SUP_MODULE_DXE_DRIVER, \\r
+                   SUP_MODULE_DXE_RUNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_DXE_SMM_DRIVER, SUP_MODULE_UEFI_DRIVER, \\r
+                   SUP_MODULE_UEFI_APPLICATION, SUP_MODULE_USER_DEFINED]\r
+SUP_MODULE_LIST_STRING = TAB_SPACE_SPLIT.join(l for l in SUP_MODULE_LIST)\r
+\r
+TAB_SOURCES = 'Sources'\r
+TAB_SOURCES_COMMON = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_SOURCES_IA32 = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_SOURCES_X64 = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_SOURCES_IPF = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_SOURCES_EBC = TAB_SOURCES + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_BINARIES = 'Binaries'\r
+TAB_BINARIES_COMMON = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_BINARIES_IA32 = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_BINARIES_X64 = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_BINARIES_IPF = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_BINARIES_EBC = TAB_BINARIES + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_INCLUDES = 'Includes'\r
+TAB_INCLUDES_COMMON = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_INCLUDES_IA32 = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_INCLUDES_X64 = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_INCLUDES_IPF = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_INCLUDES_EBC = TAB_INCLUDES + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_GUIDS = 'Guids'\r
+TAB_GUIDS_COMMON = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_GUIDS_IA32 = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_GUIDS_X64 = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_GUIDS_IPF = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_GUIDS_EBC = TAB_GUIDS + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_PROTOCOLS = 'Protocols'\r
+TAB_PROTOCOLS_COMMON = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_PROTOCOLS_IA32 = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_PROTOCOLS_X64 = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_PROTOCOLS_IPF = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_PROTOCOLS_EBC = TAB_PROTOCOLS + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_PPIS = 'Ppis'\r
+TAB_PPIS_COMMON = TAB_PPIS + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_PPIS_IA32 = TAB_PPIS + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_PPIS_X64 = TAB_PPIS + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_PPIS_IPF = TAB_PPIS + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_PPIS_EBC = TAB_PPIS + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_LIBRARY_CLASSES = 'LibraryClasses'\r
+TAB_LIBRARY_CLASSES_COMMON = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_LIBRARY_CLASSES_IA32 = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_LIBRARY_CLASSES_X64 = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_LIBRARY_CLASSES_IPF = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_LIBRARY_CLASSES_EBC = TAB_LIBRARY_CLASSES + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_PACKAGES = 'Packages'\r
+TAB_PACKAGES_COMMON = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_PACKAGES_IA32 = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_PACKAGES_X64 = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_PACKAGES_IPF = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_PACKAGES_EBC = TAB_PACKAGES + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_PCDS = 'Pcds'\r
+TAB_PCDS_FIXED_AT_BUILD = 'FixedAtBuild'\r
+TAB_PCDS_PATCHABLE_IN_MODULE = 'PatchableInModule'\r
+TAB_PCDS_FEATURE_FLAG = 'FeatureFlag'\r
+TAB_PCDS_DYNAMIC_EX = 'DynamicEx'\r
+TAB_PCDS_DYNAMIC_EX_DEFAULT = 'DynamicExDefault'\r
+TAB_PCDS_DYNAMIC_EX_VPD = 'DynamicExVpd'\r
+TAB_PCDS_DYNAMIC_EX_HII = 'DynamicExHii'\r
+TAB_PCDS_DYNAMIC = 'Dynamic'\r
+TAB_PCDS_DYNAMIC_DEFAULT = 'DynamicDefault'\r
+TAB_PCDS_DYNAMIC_VPD = 'DynamicVpd'\r
+TAB_PCDS_DYNAMIC_HII = 'DynamicHii'\r
+\r
+TAB_PCDS_FIXED_AT_BUILD_NULL = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD\r
+TAB_PCDS_FIXED_AT_BUILD_COMMON = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_PCDS_FIXED_AT_BUILD_IA32 = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_PCDS_FIXED_AT_BUILD_X64 = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_PCDS_FIXED_AT_BUILD_IPF = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_PCDS_FIXED_AT_BUILD_EBC = TAB_PCDS + TAB_PCDS_FIXED_AT_BUILD + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_PCDS_PATCHABLE_IN_MODULE_NULL = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE\r
+TAB_PCDS_PATCHABLE_IN_MODULE_COMMON = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_PCDS_PATCHABLE_IN_MODULE_IA32 = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_PCDS_PATCHABLE_IN_MODULE_X64 = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_PCDS_PATCHABLE_IN_MODULE_IPF = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_PCDS_PATCHABLE_IN_MODULE_EBC = TAB_PCDS + TAB_PCDS_PATCHABLE_IN_MODULE + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_PCDS_FEATURE_FLAG_NULL = TAB_PCDS + TAB_PCDS_FEATURE_FLAG\r
+TAB_PCDS_FEATURE_FLAG_COMMON = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_PCDS_FEATURE_FLAG_IA32 = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_PCDS_FEATURE_FLAG_X64 = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_PCDS_FEATURE_FLAG_IPF = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_PCDS_FEATURE_FLAG_EBC = TAB_PCDS + TAB_PCDS_FEATURE_FLAG + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_PCDS_DYNAMIC_EX_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_EX\r
+TAB_PCDS_DYNAMIC_EX_DEFAULT_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_EX_DEFAULT\r
+TAB_PCDS_DYNAMIC_EX_HII_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_EX_HII\r
+TAB_PCDS_DYNAMIC_EX_VPD_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_EX_VPD\r
+TAB_PCDS_DYNAMIC_EX_COMMON = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_PCDS_DYNAMIC_EX_IA32 = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_PCDS_DYNAMIC_EX_X64 = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_PCDS_DYNAMIC_EX_IPF = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_PCDS_DYNAMIC_EX_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC_EX + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_PCDS_DYNAMIC_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC\r
+TAB_PCDS_DYNAMIC_DEFAULT_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_DEFAULT\r
+TAB_PCDS_DYNAMIC_HII_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_HII\r
+TAB_PCDS_DYNAMIC_VPD_NULL = TAB_PCDS + TAB_PCDS_DYNAMIC_VPD\r
+TAB_PCDS_DYNAMIC_COMMON = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_PCDS_DYNAMIC_IA32 = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_PCDS_DYNAMIC_X64 = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_PCDS_DYNAMIC_IPF = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_PCDS_DYNAMIC_EBC = TAB_PCDS + TAB_PCDS_DYNAMIC + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_DEPEX = 'Depex'\r
+TAB_DEPEX_COMMON = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_DEPEX_IA32 = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_DEPEX_X64 = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_DEPEX_IPF = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_DEPEX_EBC = TAB_DEPEX + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_SKUIDS = 'SkuIds'\r
+\r
+TAB_LIBRARIES = 'Libraries'\r
+TAB_LIBRARIES_COMMON = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_LIBRARIES_IA32 = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_LIBRARIES_X64 = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_LIBRARIES_IPF = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_LIBRARIES_EBC = TAB_LIBRARIES + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_COMPONENTS = 'Components'\r
+TAB_COMPONENTS_COMMON = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_COMMON\r
+TAB_COMPONENTS_IA32 = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_IA32\r
+TAB_COMPONENTS_X64 = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_X64\r
+TAB_COMPONENTS_IPF = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_IPF\r
+TAB_COMPONENTS_EBC = TAB_COMPONENTS + TAB_SPLIT + TAB_ARCH_EBC\r
+\r
+TAB_BUILD_OPTIONS = 'BuildOptions'\r
+\r
+TAB_DEFINE = 'DEFINE'\r
+\r
+#Common Define\r
+TAB_COMMON_DEFINES = 'Defines'\r
+\r
+#Inf Definitions\r
+TAB_INF_DEFINES = TAB_COMMON_DEFINES\r
+TAB_INF_DEFINES_INF_VERSION = 'INF_VERSION'\r
+TAB_INF_DEFINES_BASE_NAME = 'BASE_NAME'\r
+TAB_INF_DEFINES_FILE_GUID = 'FILE_GUID'\r
+TAB_INF_DEFINES_MODULE_TYPE = 'MODULE_TYPE'\r
+TAB_INF_DEFINES_EFI_SPECIFICATION_VERSION = 'EFI_SPECIFICATION_VERSION'\r
+TAB_INF_DEFINES_EDK_RELEASE_VERSION = 'EDK_RELEASE_VERSION'\r
+TAB_INF_DEFINES_BINARY_MODULE = 'BINARY_MODULE'\r
+TAB_INF_DEFINES_LIBRARY_CLASS = 'LIBRARY_CLASS'\r
+TAB_INF_DEFINES_COMPONENT_TYPE = 'COMPONENT_TYPE'\r
+TAB_INF_DEFINES_MAKEFILE_NAME = 'MAKEFILE_NAME'\r
+TAB_INF_DEFINES_BUILD_NUMBER = 'BUILD_NUMBER'\r
+TAB_INF_DEFINES_BUILD_TYPE = 'BUILD_TYPE'\r
+TAB_INF_DEFINES_FFS_EXT = 'FFS_EXT'\r
+TAB_INF_DEFINES_FV_EXT = 'FV_EXT'\r
+TAB_INF_DEFINES_SOURCE_FV = 'SOURCE_FV'\r
+TAB_INF_DEFINES_VERSION_NUMBER = 'VERSION_NUMBER'\r
+TAB_INF_DEFINES_VERSION_STRING = 'VERSION_STRING'\r
+TAB_INF_DEFINES_PCD_IS_DRIVER = 'PCD_IS_DRIVER'\r
+TAB_INF_DEFINES_TIANO_R8_FLASHMAP_H = 'TIANO_R8_FLASHMAP_H'\r
+TAB_INF_DEFINES_ENTRY_POINT = 'ENTRY_POINT'\r
+TAB_INF_DEFINES_UNLOAD_IMAGE = 'UNLOAD_IMAGE'\r
+TAB_INF_DEFINES_CONSTRUCTOR = 'CONSTRUCTOR'\r
+TAB_INF_DEFINES_DESTRUCTOR = 'DESTRUCTOR'\r
+TAB_INF_DEFINES_DEFINE = 'DEFINE'\r
+TAB_INF_DEFINES_CUSTOM_MAKEFILE = 'CUSTOM_MAKEFILE'\r
+TAB_INF_DEFINES_TOOLS_FLAGS = 'ToolFlags'              #TBD\r
+TAB_INF_DEFINES_MACRO_NAME = 'MacroName'               #TBD\r
+TAB_INF_DEFINES_VARIABLE_NAME = 'VariableName'         #TBD\r
+TAB_INF_DEFINES_SPEC = 'Spec'                          #TBD\r
+\r
+#Dec Definitions\r
+TAB_DEC_DEFINES = TAB_COMMON_DEFINES\r
+TAB_DEC_DEFINES_DEC_SPECIFICATION = 'DEC_SPECIFICATION'\r
+TAB_DEC_DEFINES_PACKAGE_NAME = 'PACKAGE_NAME'\r
+TAB_DEC_DEFINES_PACKAGE_GUID = 'PACKAGE_GUID'\r
+TAB_DEC_DEFINES_PACKAGE_VERSION = 'PACKAGE_VERSION'\r
+\r
+#Dsc Definitions\r
+TAB_DSC_DEFINES = TAB_COMMON_DEFINES\r
+TAB_DSC_DEFINES_PLATFORM_NAME = 'PLATFORM_NAME'\r
+TAB_DSC_DEFINES_PLATFORM_GUID = 'PLATFORM_GUID'\r
+TAB_DSC_DEFINES_PLATFORM_VERSION = 'PLATFORM_VERSION'\r
+TAB_DSC_DEFINES_DSC_SPECIFICATION = 'DSC_SPECIFICATION'\r
+TAB_DSC_DEFINES_OUTPUT_DIRECTORY = 'OUTPUT_DIRECTORY'\r
+TAB_DSC_DEFINES_SUPPORTED_ARCHITECTURES = 'SUPPORTED_ARCHITECTURES'\r
+TAB_DSC_DEFINES_BUILD_TARGETS = 'BUILD_TARGETS'\r
+TAB_DSC_DEFINES_SKUID_IDENTIFIER = 'SKUID_IDENTIFIER'\r
+TAB_DSC_DEFINES_FLASH_DEFINITION = 'FLASH_DEFINITION'\r
+TAB_DSC_DEFINES_BUILD_NUMBER = 'BUILD_NUMBER'\r
+TAB_DSC_DEFINES_MAKEFILE_NAME = 'MAKEFILE_NAME'\r
+\r
+#TargetTxt Definitions\r
+TAB_TAT_DEFINES_ACTIVE_PLATFORM = 'ACTIVE_PLATFORM'\r
+TAB_TAT_DEFINES_ACTIVE_MODULE = 'ACTIVE_MODULE'\r
+TAB_TAT_DEFINES_TOOL_CHAIN_CONF = 'TOOL_CHAIN_CONF'\r
+TAB_TAT_DEFINES_MULTIPLE_THREAD = 'MULTIPLE_THREAD'\r
+TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER = 'MAX_CONCURRENT_THREAD_NUMBER'\r
+TAB_TAT_DEFINES_TARGET = 'TARGET'\r
+TAB_TAT_DEFINES_TOOL_CHAIN_TAG = 'TOOL_CHAIN_TAG'\r
+TAB_TAT_DEFINES_TARGET_ARCH = 'TARGET_ARCH'\r
+\r
+#ToolDef Definitions\r
+TAB_TOD_DEFINES_TARGET = 'TARGET'\r
+TAB_TOD_DEFINES_TOOL_CHAIN_TAG = 'TOOL_CHAIN_TAG'\r
+TAB_TOD_DEFINES_TARGET_ARCH = 'TARGET_ARCH'\r
+TAB_TOD_DEFINES_COMMAND_TYPE = 'COMMAND_TYPE'\r
diff --git a/Source/Python/Common/DecClassObject.py b/Source/Python/Common/DecClassObject.py
new file mode 100644 (file)
index 0000000..df48d00
--- /dev/null
@@ -0,0 +1,124 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+#\r
+#This file is used to define each component of DEC file\r
+#\r
+\r
+import os\r
+from String import *\r
+from DataType import *\r
+from Identification import *\r
+from Dictionary import *\r
+\r
+class DecObject(object):\r
+    def __init__(self):\r
+        object.__init__()\r
+\r
+class DecDefines(DecObject):\r
+    def __init__(self):\r
+        self.DefinesDictionary = {\r
+            #Req\r
+            TAB_DEC_DEFINES_DEC_SPECIFICATION           : [''],\r
+            TAB_DEC_DEFINES_PACKAGE_NAME                : [''],\r
+            TAB_DEC_DEFINES_PACKAGE_GUID                : [''],\r
+            TAB_DEC_DEFINES_PACKAGE_VERSION             : ['']\r
+        }\r
+        \r
+class DecContents(DecObject):\r
+    def __init__(self):\r
+        self.Includes = []\r
+        self.Guids = []\r
+        self.Protocols = []\r
+        self.Ppis = []\r
+        self.LibraryClasses = []\r
+        self.PcdsFixedAtBuild = []\r
+        self.PcdsPatchableInModule = []\r
+        self.PcdsFeatureFlag = []\r
+        self.PcdsDynamic = []\r
+        self.PcdsDynamicEx = []\r
+\r
+class Dec(DecObject):\r
+    def __init__(self, filename = None, isMergeAllArches = False):\r
+        self.identification = Identification()\r
+        self.Defines = DecDefines()\r
+        \r
+        self.Contents = {}\r
+        for key in DataType.ARCH_LIST_FULL:\r
+            self.Contents[key] = DecContents()\r
+        \r
+        self.KeyList = [\r
+            TAB_INCLUDES, TAB_GUIDS, TAB_PROTOCOLS, TAB_PPIS, TAB_LIBRARY_CLASSES, \\r
+            TAB_PCDS_FIXED_AT_BUILD_NULL, TAB_PCDS_PATCHABLE_IN_MODULE_NULL, TAB_PCDS_FEATURE_FLAG_NULL, \\r
+            TAB_PCDS_DYNAMIC_NULL, TAB_PCDS_DYNAMIC_EX_NULL\r
+        ]\r
+    \r
+        if filename != None:\r
+            self.LoadDecFile(filename)\r
+            \r
+        if isMergeAllArches:\r
+            self.MergeAllArches()            \r
+    \r
+    def ParseDec(self, Lines, Key, KeyField):\r
+        GetMultipleValuesOfKeyFromLines(Lines, Key, KeyField, TAB_COMMENT_SPLIT)\r
+            \r
+    def MergeAllArches(self):\r
+        for key in self.KeyList:\r
+            for arch in DataType.ARCH_LIST:\r
+                Command = "self.Contents[arch]." + key + ".extend(" + "self.Contents['" + DataType.TAB_ARCH_COMMON + "']." + key + ")"\r
+                eval(Command)\r
+\r
+    def LoadDecFile(self, filename):\r
+        f = open(filename, 'r').read()\r
+        sects = f.split('[')\r
+        for sect in sects:\r
+            tab = (sect.split(TAB_SECTION_END, 1)[0]).upper()\r
+            if tab == TAB_INF_DEFINES.upper():\r
+                GetSingleValueOfKeyFromLines(sect, self.Defines.DefinesDictionary, TAB_COMMENT_SPLIT, TAB_EQUAL_SPLIT, True, TAB_VALUE_SPLIT)\r
+                continue\r
+            for arch in DataType.ARCH_LIST_FULL + [DataType.TAB_ARCH_NULL]:\r
+                for key in self.KeyList:\r
+                    if arch != DataType.TAB_ARCH_NULL:\r
+                        target = (key + DataType.TAB_SPLIT + arch).upper()\r
+                    else:\r
+                        target = key.upper()\r
+                    if tab == target:\r
+                        if arch != DataType.TAB_ARCH_NULL:\r
+                            Command = 'self.ParseDec(sect, tab, self.Contents[arch].' + key + ')'\r
+                            eval(Command)\r
+                            continue\r
+                        else:\r
+                            Command = "self.ParseDec(sect, tab, self.Contents['" + DataType.TAB_ARCH_COMMON + "']." + key + ')'\r
+                            eval(Command)\r
+                            continue\r
+        #EndFor\r
+\r
+    def showDec(self):\r
+        print TAB_SECTION_START + TAB_INF_DEFINES + TAB_SECTION_END\r
+        printDict(self.Defines.DefinesDictionary)\r
+\r
+        for key in self.KeyList:\r
+            for arch in DataType.ARCH_LIST_FULL:\r
+                Command = "printList(TAB_SECTION_START + '" + \\r
+                                    key + DataType.TAB_SPLIT + arch + \\r
+                                    "' + TAB_SECTION_END, self.Contents[arch]." + key + ')'\r
+                eval(Command)\r
+\r
+if __name__ == '__main__':\r
+    p = Dec()\r
+    directory = 'C:\Documents and Settings\\hchen30\\Desktop\\prototype\\dec'\r
+    fileList = []\r
+    for f in os.listdir(directory):\r
+        if os.path.splitext(os.path.normcase(f))[1] == '.dec':\r
+            fileList.append(os.path.join(directory, os.path.normcase(f)))\r
+            \r
+            \r
+    for f in fileList:\r
+        p.LoadDecFile(f)\r
+        p.showDec()\r
diff --git a/Source/Python/Common/Dictionary.py b/Source/Python/Common/Dictionary.py
new file mode 100644 (file)
index 0000000..7ef7a78
--- /dev/null
@@ -0,0 +1,45 @@
+import EdkLogger\r
+from DataType import *\r
+\r
+#\r
+# Convert a text file to a dictionary\r
+#\r
+def ConvertTextFileToDictionary(FileName, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
+  """Convert a text file to a dictionary of (name:value) pairs."""\r
+  try:\r
+    f = open(FileName,'r')\r
+  except:\r
+    EdkLogger.info('Open file failed')\r
+    return False\r
+  Keys = []\r
+  for Line in f:\r
+    if Line.startswith(CommentCharacter):\r
+      continue\r
+    LineList = Line.split(KeySplitCharacter,1)\r
+    if len(LineList) >= 2:\r
+      Key = LineList[0].split()\r
+      if len(Key) == 1 and Key[0][0] != CommentCharacter and Key[0] not in Keys:\r
+        if ValueSplitFlag:\r
+          Dictionary[Key[0]] = LineList[1].replace('\\','/').split(ValueSplitCharacter)\r
+        else:\r
+          Dictionary[Key[0]] = LineList[1].strip().replace('\\','/')\r
+        Keys += [Key[0]]\r
+  f.close()\r
+  return True\r
+\r
+def printDict(dict):\r
+  if dict != None:\r
+    KeyList = dict.keys()\r
+    for Key in KeyList:\r
+      if dict[Key] != '':\r
+        print Key + ' = ' + str(dict[Key])\r
+\r
+def printList(key, list):\r
+  if type(list) == type([]):\r
+      if len(list) > 0:\r
+        if key.find(TAB_SPLIT) != -1:\r
+          print "\n" + key\r
+          for i in list:\r
+            print i\r
+    \r
+      \r
diff --git a/Source/Python/Common/DscClassObject.py b/Source/Python/Common/DscClassObject.py
new file mode 100644 (file)
index 0000000..d6e305d
--- /dev/null
@@ -0,0 +1,150 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+#\r
+#This file is used to define each component of DSC file\r
+#\r
+\r
+import os\r
+from String import *\r
+from DataType import *\r
+from Identification import *\r
+from Dictionary import *\r
+from ClassObjects.PlatformClassObject import *\r
+\r
+class DscObject(object):\r
+    def __init__(self):\r
+        object.__init__()\r
+\r
+class DscDefines(DscObject):\r
+    def __init__(self):\r
+        self.DefinesDictionary = {\r
+            #Req\r
+            TAB_DSC_DEFINES_PLATFORM_NAME                         : [''],\r
+            TAB_DSC_DEFINES_PLATFORM_GUID                         : [''],\r
+            TAB_DSC_DEFINES_PLATFORM_VERSION                      : [''],\r
+            TAB_DSC_DEFINES_DSC_SPECIFICATION                     : [''],\r
+            TAB_DSC_DEFINES_OUTPUT_DIRECTORY                      : [''],\r
+            TAB_DSC_DEFINES_SUPPORTED_ARCHITECTURES               : [''],\r
+            TAB_DSC_DEFINES_BUILD_TARGETS                         : [''],\r
+            TAB_DSC_DEFINES_SKUID_IDENTIFIER                      : [''],\r
+            TAB_DSC_DEFINES_FLASH_DEFINITION                      : [''],\r
+            TAB_DSC_DEFINES_BUILD_NUMBER                          : [''],\r
+            TAB_DSC_DEFINES_MAKEFILE_NAME                         : ['']                        \r
+        }\r
+\r
+class DscSkuId(DscObject):\r
+    def __init__(self):\r
+        self.SkuId = {}         #{ [skuid : skuname], [skuid : skuname], ...}\r
+\r
+class DscContents(DscObject):\r
+    def __init__(self):\r
+        self.SkuIds = []\r
+        self.Libraries = []\r
+        self.Components = []                #[['component name', [lib1, lib2, lib3], [bo1, bo2, bo3]], ...]\r
+        self.LibraryClasses = []\r
+        self.PcdsFixedAtBuild = []\r
+        self.PcdsPatchableInModule = []\r
+        self.PcdsFeatureFlag = []\r
+        self.PcdsDynamicDefault = []\r
+        self.PcdsDynamicVpd = []\r
+        self.PcdsDynamicHii = []       \r
+        self.PcdsDynamicExDefault = []\r
+        self.PcdsDynamicExVpd = []\r
+        self.PcdsDynamicExHii = []                \r
+        self.BuildOptions = []\r
+\r
+class Dsc(DscObject):\r
+    def __init__(self, filename = None, isMergeAllArches = False):\r
+        self.identification = Identification()\r
+        self.Defines = DscDefines()\r
+        self.Contents = {}\r
+\r
+        for key in DataType.ARCH_LIST_FULL:\r
+            self.Contents[key] = DscContents()\r
+        \r
+        self.KeyList = [\r
+            TAB_SKUIDS, TAB_LIBRARIES, TAB_LIBRARY_CLASSES, TAB_BUILD_OPTIONS, TAB_PCDS_FIXED_AT_BUILD_NULL, \\r
+            TAB_PCDS_PATCHABLE_IN_MODULE_NULL, TAB_PCDS_FEATURE_FLAG_NULL, \\r
+            TAB_PCDS_DYNAMIC_DEFAULT_NULL, TAB_PCDS_DYNAMIC_HII_NULL, TAB_PCDS_DYNAMIC_VPD_NULL, \\r
+            TAB_PCDS_DYNAMIC_EX_DEFAULT_NULL, TAB_PCDS_DYNAMIC_EX_HII_NULL, TAB_PCDS_DYNAMIC_EX_VPD_NULL, \\r
+            TAB_COMPONENTS, TAB_BUILD_OPTIONS\r
+        ]\r
+        \r
+        if filename != None:\r
+            self.LoadDscFile(filename)\r
+            \r
+        if isMergeAllArches:\r
+            self.MergeAllArches()\r
+        \r
+    def ParseDsc(self, Lines, Key, KeyField):\r
+        newKey = SplitModuleType(Key)     \r
+        if newKey[0].find(TAB_LIBRARY_CLASSES.upper()) != -1:\r
+            GetLibraryClassesWithModuleType(Lines, Key, KeyField, TAB_COMMENT_SPLIT)\r
+        elif newKey[0].find(TAB_COMPONENTS.upper()) != -1:\r
+            GetComponents(Lines, Key, KeyField, TAB_COMMENT_SPLIT)\r
+        elif newKey[0].find(TAB_PCDS_DYNAMIC.upper()) != -1:\r
+            GetDynamics(Lines, Key, KeyField, TAB_COMMENT_SPLIT)\r
+        else:\r
+            GetMultipleValuesOfKeyFromLines(Lines, Key, KeyField, TAB_COMMENT_SPLIT)\r
+    \r
+    def MergeAllArches(self):\r
+        for key in self.KeyList:\r
+            for arch in DataType.ARCH_LIST:\r
+                Command = "self.Contents[arch]." + key + ".extend(" + "self.Contents['" + DataType.TAB_ARCH_COMMON + "']." + key + ")"\r
+                eval(Command)\r
+            \r
+    def LoadDscFile(self, filename):\r
+        EdkLogger.verbose('Open Dsc File:' + filename)\r
+        f = open(filename, 'r').read()\r
+        sects = f.split('[')\r
+        for sect in sects:\r
+            tab = (sect.split(TAB_SECTION_END, 1)[0]).upper()\r
+            if tab == TAB_INF_DEFINES.upper():\r
+                GetSingleValueOfKeyFromLines(sect, self.Defines.DefinesDictionary, TAB_COMMENT_SPLIT, TAB_EQUAL_SPLIT, True, TAB_VALUE_SPLIT)\r
+                continue\r
+            for arch in DataType.ARCH_LIST_FULL + [DataType.TAB_ARCH_NULL]:\r
+                for key in self.KeyList:\r
+                    if arch != DataType.TAB_ARCH_NULL:\r
+                        target = (key + DataType.TAB_SPLIT + arch).upper()\r
+                    else:\r
+                        target = key.upper()\r
+                    if SplitModuleType(tab)[0] == target:\r
+                        if arch != DataType.TAB_ARCH_NULL:\r
+                            Command = 'self.ParseDsc(sect, tab, self.Contents[arch].' + key + ')'\r
+                            eval(Command)\r
+                            continue\r
+                        else:\r
+                            Command = "self.ParseDsc(sect, tab, self.Contents['" + DataType.TAB_ARCH_COMMON + "']." + key + ')'\r
+                            eval(Command)\r
+                            continue\r
+\r
+    def showDsc(self):\r
+        print TAB_SECTION_START + TAB_INF_DEFINES + TAB_SECTION_END\r
+        printDict(self.Defines.DefinesDictionary)\r
+\r
+        for key in self.KeyList:\r
+            for arch in DataType.ARCH_LIST_FULL:\r
+                Command = "printList(TAB_SECTION_START + '" + \\r
+                                    key + DataType.TAB_SPLIT + arch + \\r
+                                    "' + TAB_SECTION_END, self.Contents[arch]." + key + ')'\r
+                eval(Command)\r
+        \r
+if __name__ == '__main__':\r
+    p = Dsc()\r
+    directory = 'C:\MyWorkspace\\EdkModulePkg'\r
+    fileList = []\r
+    for f in os.listdir(directory):\r
+        if os.path.splitext(os.path.normcase(f))[1] == '.dsc':\r
+            fileList.append(os.path.join(directory, os.path.normcase(f)))\r
+            \r
+    for f in fileList:\r
+        p.LoadDscFile(f)\r
+        p.MergeAllArches()\r
+        p.showDsc()\r
diff --git a/Source/Python/Common/EdkIIWorkspace.py b/Source/Python/Common/EdkIIWorkspace.py
new file mode 100644 (file)
index 0000000..c0062c7
--- /dev/null
@@ -0,0 +1,195 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+#\r
+# This is the base class for applications that operate on an EDK II Workspace \r
+#\r
+\r
+import os, sys, time\r
+from DataType import *\r
+\r
+class EdkIIWorkspace:\r
+    def __init__(self):\r
+        """Collect WorkspaceDir from the environment, the Verbose command line flag, and detect an icon bitmap file."""\r
+\r
+        self.StartTime = time.time()\r
+        self.PrintRunTime     = False\r
+        self.PrintRunStatus = False\r
+        self.RunStatus            = ''\r
+        \r
+        if os.environ.get('WORKSPACE') == None:\r
+            print 'ERROR: WORKSPACE not defined.    Please run EdkSetup from the EDK II install directory.'\r
+            return False\r
+\r
+        self.CurrentWorkingDir = os.getcwd()\r
+        \r
+        self.WorkspaceDir = os.path.realpath(os.environ.get('WORKSPACE'))\r
+        (Drive, Path) = os.path.splitdrive(self.WorkspaceDir)\r
+        if Drive == '':\r
+            (Drive, CwdPath) = os.path.splitdrive(self.CurrentWorkingDir)\r
+            if Drive != '':\r
+                self.WorkspaceDir = Drive + Path\r
+        else:\r
+            self.WorkspaceDir = Drive.upper() + Path\r
+\r
+        self.WorkspaceRelativeWorkingDir = self.WorkspaceRelativePath (self.CurrentWorkingDir)\r
+            \r
+        try:\r
+            self.Icon = wx.Icon(self.WorkspaceFile('tools/Python/TianoCoreOrgLogo.gif'),wx.BITMAP_TYPE_GIF)\r
+        except:\r
+            self.Icon = None\r
+            \r
+        self.Verbose = False\r
+        for arg in sys.argv:\r
+            if arg.lower() == '-v':\r
+                self.Verbose = True            \r
+\r
+        #return True\r
+\r
+    def Close(self):\r
+        if self.PrintRunTime:\r
+            Seconds = int(time.time() - self.StartTime)\r
+            if Seconds < 60:\r
+                print 'Run Time: %d seconds' % (Seconds)\r
+            else:\r
+                Minutes = Seconds / 60\r
+                Seconds = Seconds % 60\r
+                if Minutes < 60:\r
+                    print 'Run Time: %d minutes %d seconds' % (Minutes, Seconds)\r
+                else:\r
+                    Hours = Minutes / 60\r
+                    Minutes = Minutes % 60\r
+                    print 'Run Time: %d hours %d minutes %d seconds' % (Hours, Minutes, Seconds)\r
+        if self.RunStatus != '':\r
+            print self.RunStatus\r
+        \r
+    def WorkspaceRelativePath(self, FileName):\r
+        """Convert a full path filename to a workspace relative filename."""\r
+        FileName = os.path.realpath(FileName)\r
+        if FileName.find(self.WorkspaceDir) != 0:\r
+            return None\r
+        return FileName.replace (self.WorkspaceDir, '').strip('\\').strip('/')\r
+\r
+    def WorkspaceFile(self, FileName):\r
+        """Convert a workspace relative filename to a full path filename."""\r
+        return os.path.realpath(os.path.join(self.WorkspaceDir,FileName))\r
+\r
+    def WorkspacePathConvert(self, FileName):\r
+        """Convert ${WORKSPACE} to real path"""\r
+        return os.path.realpath(FileName.replace(TAB_WORKSPACE, self.WorkspaceDir))\r
+        \r
+    def XmlParseFile (self, FileName):\r
+        """Parse an XML file into a DOM and return the DOM."""\r
+        if self.Verbose:\r
+            print FileName\r
+        return XmlParseFile (self.WorkspaceFile(FileName))\r
+        \r
+    def XmlParseFileSection (self, FileName, SectionTag):\r
+        """Parse a section of an XML file into a DOM(Document Object Model) and return the DOM."""\r
+        if self.Verbose:\r
+            print FileName\r
+        return XmlParseFileSection (self.WorkspaceFile(FileName), SectionTag)        \r
+\r
+    def XmlSaveFile (self, Dom, FileName):\r
+        """Save a DOM(Document Object Model) into an XML file."""\r
+        if self.Verbose:\r
+            print FileName\r
+        return XmlSaveFile (Dom, self.WorkspaceFile(FileName))\r
+\r
+    def ConvertTextFileToDictionary(self, FileName, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
+        """Convert a workspace relative text file to a dictionary of (name:value) pairs."""\r
+        if self.Verbose:\r
+            print FileName\r
+        return ConvertTextFileToDictionary(self.WorkspaceFile(FileName), Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter)\r
+    \r
+    def ConvertDictionaryToTextFile(self, FileName, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
+        """Convert a dictionary of (name:value) pairs to a workspace relative text file."""\r
+        if self.Verbose:\r
+            print FileName\r
+        return ConvertDictionaryToTextFile(self.WorkspaceFile(FileName), Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter)\r
+\r
+#\r
+# Convert a text file to a dictionary\r
+#\r
+def ConvertTextFileToDictionary(FileName, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
+    """Convert a text file to a dictionary of (name:value) pairs."""\r
+    try:\r
+        f = open(FileName,'r')\r
+    except:\r
+        return False\r
+    Keys = []\r
+    for Line in f:\r
+        LineList = Line.split(KeySplitCharacter,1)\r
+        if len(LineList) >= 2:\r
+            Key = LineList[0].split()\r
+            if len(Key) == 1 and Key[0][0] != CommentCharacter and Key[0] not in Keys: \r
+                if ValueSplitFlag:\r
+                    Dictionary[Key[0]] = LineList[1].replace('\\','/').split(ValueSplitCharacter)\r
+                else:\r
+                    Dictionary[Key[0]] = LineList[1].strip().replace('\\','/')\r
+                Keys += [Key[0]]\r
+    f.close()\r
+    return True\r
+\r
+def ConvertDictionaryToTextFile(FileName, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
+    """Convert a dictionary of (name:value) pairs to a text file."""\r
+    try:\r
+        f = open(FileName,'r')\r
+        Lines = []\r
+        Lines = f.readlines()\r
+        f.close()\r
+    except:\r
+        Lines = []\r
+    Keys = Dictionary.keys()\r
+    MaxLength = 0\r
+    for Key in Keys:\r
+        if len(Key) > MaxLength:\r
+            MaxLength = len(Key)\r
+    Index = 0\r
+    for Line in Lines:\r
+        LineList = Line.split(KeySplitCharacter,1)\r
+        if len(LineList) >= 2:\r
+            Key = LineList[0].split()\r
+            if len(Key) == 1 and Key[0][0] != CommentCharacter and Key[0] in Dictionary:\r
+                if ValueSplitFlag:\r
+                    Line = '%-*s %c %s\n' % (MaxLength, Key[0], KeySplitCharacter, ' '.join(Dictionary[Key[0]]))\r
+                else:\r
+                    Line = '%-*s %c %s\n' % (MaxLength, Key[0], KeySplitCharacter, Dictionary[Key[0]])\r
+                Lines.pop(Index)\r
+                if Key[0] in Keys:\r
+                    Lines.insert(Index,Line)\r
+                    Keys.remove(Key[0])\r
+        Index += 1\r
+    for RemainingKey in Keys:\r
+        if ValueSplitFlag:\r
+            Line = '%-*s %c %s\n' % (MaxLength, RemainingKey, KeySplitCharacter,' '.join(Dictionary[RemainingKey])) \r
+        else:\r
+            Line = '%-*s %c %s\n' % (MaxLength, RemainingKey, KeySplitCharacter, Dictionary[RemainingKey])\r
+        Lines.append(Line)\r
+    try:\r
+        f = open(FileName,'w')\r
+    except:\r
+        return False\r
+    f.writelines(Lines)\r
+    f.close()\r
+    return True\r
+\r
+def CreateDirectory(Directory):\r
+    if not os.access(Directory, os.F_OK):\r
+        os.makedirs (Directory)\r
+    \r
+def CreateFile(Directory, FileName, mode='w'):\r
+    CreateDirectory (Directory)\r
+    return open(os.path.join(Directory, FileName), mode)\r
+\r
+# This acts like the main() function for the script, unless it is 'import'ed into another\r
+# script.\r
+if __name__ == '__main__':\r
+    # Nothing to do here. Could do some unit tests\r
+    pass
\ No newline at end of file
diff --git a/Source/Python/Common/EdkIIWorkspaceBuild.py b/Source/Python/Common/EdkIIWorkspaceBuild.py
new file mode 100644 (file)
index 0000000..7fa455a
--- /dev/null
@@ -0,0 +1,858 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+#\r
+# This file is used to define each component of the build database\r
+#\r
+\r
+#\r
+# Import Modules\r
+#\r
+import os, string, copy, pdb\r
+import EdkLogger\r
+import DataType\r
+from EdkIIWorkspace import *\r
+from TargetTxtClassObject import *\r
+from ToolDefClassObject import *\r
+from InfClassObject import *\r
+from DecClassObject import *\r
+from DscClassObject import *\r
+from String import *\r
+from ClassObjects.CommonClassObject import *\r
+from FdfParser import *\r
+from BuildToolError import *\r
+from Region import *\r
+\r
+class ModuleSourceFilesClassObject(object):\r
+    def __init__(self, SourceFile = '', PcdFeatureFlag = '', TagName = '', ToolCode = '', ToolChainFamily = '', String = ''):\r
+        self.SourceFile         = SourceFile\r
+        self.TagName            = TagName\r
+        self.ToolCode           = ToolCode\r
+        self.ToolChainFamily    = ToolChainFamily\r
+        self.String             = String\r
+        self.PcdFeatureFlag     = PcdFeatureFlag\r
+    \r
+    def __str__(self):\r
+        rtn = self.SourceFile + DataType.TAB_VALUE_SPLIT + \\r
+              self.PcdFeatureFlag + DataType.TAB_VALUE_SPLIT + \\r
+              self.ToolChainFamily +  DataType.TAB_VALUE_SPLIT + \\r
+              self.TagName + DataType.TAB_VALUE_SPLIT + \\r
+              self.ToolCode + DataType.TAB_VALUE_SPLIT + \\r
+              self.String\r
+        return rtn\r
+\r
+class ModuleBinaryFilesClassObject(object):\r
+    def __init__(self, BinaryFile = '', FileType = '', Target = '', PcdFeatureFlag = ''):\r
+        self.BinaryFile = BinaryFile\r
+        self.FileType =FileType\r
+        self.Target = Target\r
+        self.PcdFeatureFlag = PcdFeatureFlag\r
+    \r
+    def __str__(self):\r
+        rtn = self.BinaryFile + DataType.TAB_VALUE_SPLIT + \\r
+              self.FileType + DataType.TAB_VALUE_SPLIT + \\r
+              self.Target +  DataType.TAB_VALUE_SPLIT + \\r
+              self.PcdFeatureFlag\r
+        return rtn\r
+        \r
+class PcdClassObject(object):\r
+    def __init__(self, Name = None, Guid = None, Type = None, DatumType = None, Value = None, Token = None, MaxDatumSize = None, SkuInfoList = []):\r
+        self.TokenCName = Name\r
+        self.TokenSpaceGuidCName = Guid\r
+        self.Type = Type\r
+        self.DatumType = DatumType\r
+        self.DefaultValue = Value\r
+        self.TokenValue = Token\r
+        self.MaxDatumSize = MaxDatumSize\r
+        self.SkuInfoList = SkuInfoList\r
+        self.Phase = "DXE"\r
+        \r
+    def __str__(self):\r
+        rtn = str(self.TokenCName) + DataType.TAB_VALUE_SPLIT + \\r
+              str(self.TokenSpaceGuidCName) + DataType.TAB_VALUE_SPLIT + \\r
+              str(self.Type) + DataType.TAB_VALUE_SPLIT + \\r
+              str(self.DatumType) + DataType.TAB_VALUE_SPLIT + \\r
+              str(self.DefaultValue) + DataType.TAB_VALUE_SPLIT + \\r
+              str(self.TokenValue) + DataType.TAB_VALUE_SPLIT + \\r
+              str(self.MaxDatumSize) + DataType.TAB_VALUE_SPLIT\r
+        for Item in self.SkuInfoList:\r
+            rtn = rtn + str(Item)\r
+        return rtn\r
+\r
+    def __eq__(self, other):\r
+        return self.TokenCName == other.TokenCName and self.TokenSpaceGuidCName == other.TokenSpaceGuidCName\r
+\r
+    def __hash__(self):\r
+        return hash((self.TokenCName, self.TokenSpaceGuidCName))\r
+\r
+class LibraryClassObject(object):\r
+    def __init__(self, Name = None, Type = None):\r
+        self.LibraryClass = Name\r
+        self.SupModList = []\r
+        if Type != None:\r
+            self.SupModList = CleanString(Type).split(DataType.TAB_SPACE_SPLIT)\r
+        \r
+class ModuleBuildClassObject(object):\r
+    def __init__(self):\r
+        self.DescFilePath            = ''\r
+        self.BaseName                = ''\r
+        self.ModuleType              = ''\r
+        self.Guid                    = ''\r
+        self.Version                 = ''\r
+        self.PcdIsDriver             = ''\r
+        self.BinaryModule            = ''\r
+        self.CustomMakefile          = {}\r
+        self.Specification           = {}\r
+        self.LibraryClass            = None      # LibraryClassObject\r
+        self.ModuleEntryPointList    = []\r
+        self.ModuleUnloadImageList   = []\r
+        self.ConstructorList         = []\r
+        self.DestructorList          = []\r
+        \r
+        self.Binaries                = []        #[ ModuleBinaryClassObject, ...]\r
+        self.Sources                 = []        #[ ModuleSourceFilesClassObject, ... ]\r
+        self.LibraryClasses          = {}        #{ [LibraryClassName, ModuleType] : LibraryClassInfFile }\r
+        self.Protocols               = []        #[ ProtocolName, ... ]\r
+        self.Ppis                    = []        #[ PpiName, ... ]\r
+        self.Guids                   = []        #[ GuidName, ... ]\r
+        self.Includes                = []        #[ IncludePath, ... ]\r
+        self.Packages                = []        #[ DecFileName, ... ]\r
+        self.Pcds                    = {}        #{ [(PcdCName, PcdGuidCName)] : PcdClassObject}\r
+        self.BuildOptions            = {}        #{ [BuildOptionKey] : BuildOptionValue}\r
+        self.Depex                   = ''\r
+\r
+    def __str__(self):\r
+        return self.DescFilePath\r
+\r
+    def __eq__(self, other):\r
+        return self.DescFilePath == str(other)\r
+\r
+    def __hash__(self):\r
+        return hash(self.DescFilePath)\r
+\r
+class PackageBuildClassObject(object):\r
+    def __init__(self):\r
+        self.DescFilePath            = ''\r
+        self.PackageName             = ''\r
+        self.Guid                    = ''\r
+        self.Version                 = ''\r
+        \r
+        self.Protocols               = {}       #{ [ProtocolName] : Protocol Guid, ... }\r
+        self.Ppis                    = {}       #{ [PpiName] : Ppi Guid, ... }\r
+        self.Guids                   = {}       #{ [GuidName] : Guid, ... }\r
+        self.Includes                = []       #[ IncludePath, ... ]        \r
+        self.LibraryClasses          = {}       #{ [LibraryClassName] : LibraryClassInfFile }\r
+        self.Pcds                    = {}       #{ [(PcdCName, PcdGuidCName)] : PcdClassObject}\r
+        \r
+    def __str__(self):\r
+        return self.DescFilePath\r
+\r
+    def __eq__(self, other):\r
+        return self.DescFilePath == str(other)\r
+\r
+    def __hash__(self):\r
+        return hash(self.DescFilePath)\r
+\r
+class PlatformBuildClassObject(object):\r
+    def __init__(self):\r
+        self.DescFilePath            = ''\r
+        self.PlatformName            = ''\r
+        self.Guid                    = ''\r
+        self.Version                 = ''\r
+        self.DscSpecification        = ''\r
+        self.OutputDirectory         = ''\r
+        self.FlashDefinition         = ''\r
+        self.BuildNumber             = ''\r
+        self.MakefileName            = ''\r
+                \r
+        self.SkuIds                  = {}       #{ 'SkuName' : SkuId, '!include' : includefilename, ...}\r
+        self.Modules                 = []       #[ InfFileName, ... ]\r
+        self.LibraryClasses          = {}       #{ (LibraryClassName, ModuleType) : LibraryClassInfFile }\r
+        self.Pcds                    = {}       #{ [(PcdCName, PcdGuidCName)] : PcdClassObject }\r
+        self.BuildOptions            = {}       #{ [BuildOptionKey] : BuildOptionValue }    \r
+\r
+    def __str__(self):\r
+        return self.DescFilePath\r
+\r
+    def __eq__(self, other):\r
+        return self.DescFilePath == str(other)\r
+\r
+    def __hash__(self):\r
+        return hash(self.DescFilePath)\r
+\r
+class ItemBuild(object):\r
+    def __init__(self, arch, platform = None, package = None, module = None):\r
+        self.Arch                    = arch\r
+        self.PlatformDatabase        = {}        #{ [DscFileName] : PlatformBuildClassObject, ...}\r
+        self.PackageDatabase         = {}        #{ [DecFileName] : PacakgeBuildClassObject, ...}\r
+        self.ModuleDatabase          = {}        #{ [InfFileName] : ModuleBuildClassObject, ...}\r
+        \r
+class WorkspaceBuild(object):\r
+    def __init__(self, ActivePlatform = None):\r
+        self.Workspace               = EdkIIWorkspace()\r
+        self.PrintRunTime            = True\r
+        self.PlatformBuild           = True\r
+        self.TargetTxt               = TargetTxtClassObject()\r
+        self.ToolDef                 = ToolDefClassObject()\r
+\r
+        self.SupArchList             = []        #[ 'IA32', 'X64', ...]\r
+        self.BuildTarget             = []        #[ 'RELEASE', 'DEBUG']\r
+        self.SkuId                   = ''\r
+        \r
+        self.InfDatabase             = {}        #{ [InfFileName] : InfClassObject}\r
+        self.DecDatabase             = {}        #{ [DecFileName] : DecClassObject}\r
+        self.DscDatabase             = {}        #{ [DscFileName] : DscClassObject}\r
+        \r
+        self.Build                   = {}\r
+        for key in DataType.ARCH_LIST:\r
+            self.Build[key] = ItemBuild(key)\r
+        \r
+        self.TargetTxt.LoadTargetTxtFile(self.Workspace.WorkspaceFile('Conf/target.txt'))\r
+        self.ToolDef.LoadToolDefFile(self.Workspace.WorkspaceFile('Conf/tools_def.txt'))\r
+        \r
+        if ActivePlatform != None:\r
+            self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_ACTIVE_PLATFORM][0] = ActivePlatform\r
+        \r
+        #get active platform\r
+        dscFileName = NormPath(self.TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_ACTIVE_PLATFORM][0])\r
+        file = self.Workspace.WorkspaceFile(dscFileName)\r
+        if os.path.exists(file) and os.path.isfile(file):\r
+            self.DscDatabase[dscFileName] = Dsc(file, True)\r
+        else:\r
+            EdkLogger.verbose('No Active Platform')\r
+            return\r
+        \r
+        #parse platform to get module\r
+        for dsc in self.DscDatabase.keys():\r
+            dscObj = self.DscDatabase[dsc]\r
+            \r
+            #\r
+            # Get global information\r
+            #\r
+            self.SupArchList = dscObj.Defines.DefinesDictionary[TAB_DSC_DEFINES_SUPPORTED_ARCHITECTURES]\r
+            self.BuildTarget = dscObj.Defines.DefinesDictionary[TAB_DSC_DEFINES_BUILD_TARGETS]\r
+            self.SkuId = dscObj.Defines.DefinesDictionary[TAB_DSC_DEFINES_SKUID_IDENTIFIER][0]\r
+            \r
+            #Get all inf\r
+            for key in DataType.ARCH_LIST:\r
+                for index in range(len(dscObj.Contents[key].LibraryClasses)):\r
+                    self.AddToInfDatabase(dscObj.Contents[key].LibraryClasses[index][0].split(DataType.TAB_VALUE_SPLIT, 1)[1])\r
+                for index in range(len(dscObj.Contents[key].Components)):\r
+                    Module = dscObj.Contents[key].Components[index][0]\r
+                    LibList = dscObj.Contents[key].Components[index][1]\r
+                    self.AddToInfDatabase(Module)\r
+                    for indexOfLib in range(len(LibList)):\r
+                        Lib = LibList[indexOfLib]\r
+                        if len(Lib.split(DataType.TAB_VALUE_SPLIT)) == 2:\r
+                            self.AddToInfDatabase(CleanString(Lib.split(DataType.TAB_VALUE_SPLIT)[1]))\r
+                            self.UpdateInfDatabase(Module, CleanString(Lib.split(DataType.TAB_VALUE_SPLIT)[0]), key)\r
+        #End For of Dsc\r
+        \r
+        #parse module to get package\r
+        for inf in self.InfDatabase.keys():\r
+            infObj = self.InfDatabase[inf]\r
+            #Get all dec\r
+            for key in DataType.ARCH_LIST:\r
+                for index in range(len(infObj.Contents[key].Packages)):\r
+                    self.AddToDecDatabase(infObj.Contents[key].Packages[index])\r
+        \r
+        #Build databases\r
+        #Build PlatformDatabase\r
+        for dsc in self.DscDatabase.keys():\r
+            dscObj = self.DscDatabase[dsc]\r
+            \r
+            for key in DataType.ARCH_LIST:\r
+                pb = PlatformBuildClassObject()\r
+                pb.DescFilePath = dsc\r
+                pb.PlatformName = dscObj.Defines.DefinesDictionary[DataType.TAB_DSC_DEFINES_PLATFORM_NAME][0]\r
+                pb.Guid = dscObj.Defines.DefinesDictionary[DataType.TAB_DSC_DEFINES_PLATFORM_GUID][0]\r
+                pb.Version = dscObj.Defines.DefinesDictionary[DataType.TAB_DSC_DEFINES_PLATFORM_VERSION][0]\r
+                pb.DscSpecification = dscObj.Defines.DefinesDictionary[DataType.TAB_DSC_DEFINES_DSC_SPECIFICATION][0]\r
+                pb.OutputDirectory = NormPath(dscObj.Defines.DefinesDictionary[DataType.TAB_DSC_DEFINES_OUTPUT_DIRECTORY][0])\r
+                pb.FlashDefinition = NormPath(dscObj.Defines.DefinesDictionary[DataType.TAB_DSC_DEFINES_FLASH_DEFINITION][0])\r
+                pb.BuildNumber = dscObj.Defines.DefinesDictionary[DataType.TAB_DSC_DEFINES_BUILD_NUMBER][0]\r
+                pb.MakefileName = NormPath(dscObj.Defines.DefinesDictionary[DataType.TAB_DSC_DEFINES_MAKEFILE_NAME][0])\r
+        \r
+                #SkuId\r
+                for index in range(len(dscObj.Contents[key].SkuIds)):\r
+                    SkuInfo = dscObj.Contents[key].SkuIds[index]\r
+                    SkuName = ''\r
+                    SkuId = ''\r
+                    if SkuInfo.find('!include') > -1:\r
+                        SkuName = '!include'\r
+                        SkuId = NormPath(CleanString(SkuInfo[SkuInfo.find('!include') + len('!include'):]))\r
+                    elif len(SkuInfo.split(DataType.TAB_VALUE_SPLIT)) == 2:\r
+                        SkuName = CleanString(SkuInfo.split(DataType.TAB_VALUE_SPLIT)[1])\r
+                        SkuId = CleanString(SkuInfo.split(DataType.TAB_VALUE_SPLIT)[0])\r
+                    else:\r
+                        raise ParseError('Wrong defintion for SkuId: %s' % SkuInfo)\r
+                    pb.SkuIds[SkuName] = SkuId\r
+                \r
+                #Module\r
+                for index in range(len(dscObj.Contents[key].Components)):\r
+                    pb.Modules.append(NormPath(dscObj.Contents[key].Components[index][0]))\r
+                \r
+                #BuildOptions\r
+                for index in range(len(dscObj.Contents[key].BuildOptions)):\r
+                    b = dscObj.Contents[key].BuildOptions[index].split(DataType.TAB_EQUAL_SPLIT, 1)\r
+                    Family = ''\r
+                    ToolChain = ''\r
+                    Flag = ''\r
+                    if b[0].find(':') > -1:\r
+                        Family = CleanString(b[0][ : b[0].find(':')])\r
+                        ToolChain = CleanString(b[0][b[0].find(':') + 1 : ])\r
+                    else:\r
+                        ToolChain = CleanString(b[0])\r
+                    Flag = CleanString(b[1])\r
+                    pb.BuildOptions[(Family, ToolChain)] = Flag\r
+                    \r
+                #LibraryClass\r
+                for index in range(len(dscObj.Contents[key].LibraryClasses)):\r
+                    #['DebugLib|MdePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf', 'DXE_CORE']\r
+                    list = dscObj.Contents[key].LibraryClasses[index][0].split(DataType.TAB_VALUE_SPLIT, 1)\r
+                    type = dscObj.Contents[key].LibraryClasses[index][1]\r
+                    pb.LibraryClasses[(list[0], type)] = NormPath(list[1])\r
+\r
+                #Pcds\r
+                for index in range(len(dscObj.Contents[key].PcdsFixedAtBuild)):\r
+                    pcd = dscObj.Contents[key].PcdsFixedAtBuild[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pcd.append(None)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_FIXED_AT_BUILD, None, pcd[2], None, pcd[3])\r
+                for index in range(len(dscObj.Contents[key].PcdsPatchableInModule)):\r
+                    pcd = dscObj.Contents[key].PcdsPatchableInModule[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pcd.append(None)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_PATCHABLE_IN_MODULE, None, pcd[2], None, pcd[3])\r
+                for index in range(len(dscObj.Contents[key].PcdsFeatureFlag)):\r
+                    pcd = dscObj.Contents[key].PcdsFeatureFlag[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pcd.append(None)                    \r
+                    pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_FEATURE_FLAG, None, pcd[2], None, pcd[3])\r
+                #\r
+                # PcdsDynamic\r
+                #\r
+                for index in range(len(dscObj.Contents[key].PcdsDynamicDefault)):\r
+                    pcd = dscObj.Contents[key].PcdsDynamicDefault[index][0].split(DataType.TAB_VALUE_SPLIT)\r
+                    pcd.append(None)\r
+                    SkuName = dscObj.Contents[key].PcdsDynamicDefault[index][1]\r
+                    SkuInfoList = []\r
+                    if SkuName == None:\r
+                        SkuName = 'DEFAULT'\r
+                    SkuNameList = map(lambda l: l.strip(), SkuName.split(DataType.TAB_VALUE_SPLIT))\r
+                    for Item in SkuNameList:\r
+                        SkuInfo = SkuInfoClassObject()\r
+                        SkuInfo.SkuId = pb.SkuIds[Item]\r
+                        SkuInfo.DefaultValue = pcd[2]\r
+                        SkuInfoList.append(SkuInfo)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC_DEFAULT, None, None, None, pcd[3], SkuInfoList)\r
+                for index in range(len(dscObj.Contents[key].PcdsDynamicVpd)):\r
+                    pcd = dscObj.Contents[key].PcdsDynamicVpd[index][0].split(DataType.TAB_VALUE_SPLIT)\r
+                    pcd.append(None)\r
+                    SkuId = dscObj.Contents[key].PcdsDynamicVpd[index][1]\r
+                    SkuInfoList = []\r
+                    if SkuId == None:\r
+                        SkuId = 'DEFAULT'\r
+                    SkuIdList = map(lambda l: l.strip(), SkuId.split(DataType.TAB_VALUE_SPLIT))\r
+                    for Item in SkuIdList:\r
+                        SkuInfo = SkuInfoClassObject()\r
+                        SkuInfo.SkuId = Item\r
+                        SkuInfo.VpdOffset = pcd[2]\r
+                        SkuInfoList.append(SkuInfo)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC_VPD, None, None, None, pcd[3], SkuInfoList)\r
+                for index in range(len(dscObj.Contents[key].PcdsDynamicHii)):\r
+                    pcd = dscObj.Contents[key].PcdsDynamicHii[index][0].split(DataType.TAB_VALUE_SPLIT)\r
+                    pcd.append(None)\r
+                    SkuId = dscObj.Contents[key].PcdsDynamicHii[index][1]\r
+                    SkuInfoList = []\r
+                    if SkuId == None:\r
+                        SkuId = 'DEFAULT'\r
+                    SkuIdList = map(lambda l: l.strip(), SkuId.split(DataType.TAB_VALUE_SPLIT))\r
+                    for Item in SkuIdList:\r
+                        SkuInfo = SkuInfoClassObject()\r
+                        SkuInfo.SkuId = Item\r
+                        SkuInfo.VariableName = pcd[2]\r
+                        SkuInfo.VariableGuid = pcd[3]\r
+                        SkuInfo.VariableOffset = pcd[4]\r
+                        SkuInfo.HiiDefaultValue = pcd[5]                                                \r
+                        SkuInfoList.append(SkuInfo)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC_HII, None, None, None, pcd[6], SkuInfoList)\r
+                #\r
+                # PcdsDynamicEx\r
+                #\r
+                for index in range(len(dscObj.Contents[key].PcdsDynamicExDefault)):\r
+                    pcd = dscObj.Contents[key].PcdsDynamicExDefault[index][0].split(DataType.TAB_VALUE_SPLIT)\r
+                    pcd.append(None)\r
+                    SkuId = dscObj.Contents[key].PcdsDynamicExDefault[index][1]\r
+                    SkuInfoList = []\r
+                    if SkuId == None:\r
+                        SkuId = 'DEFAULT'\r
+                    SkuIdList = map(lambda l: l.strip(), SkuId.split(DataType.TAB_VALUE_SPLIT))\r
+                    for Item in SkuIdList:\r
+                        SkuInfo = SkuInfoClassObject()\r
+                        SkuInfo.SkuId = Item\r
+                        SkuInfo.DefaultValue = pcd[2]\r
+                        SkuInfoList.append(SkuInfo)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC_EX_DEFAULT, None, None, None, pcd[3], SkuInfoList)\r
+                for index in range(len(dscObj.Contents[key].PcdsDynamicExVpd)):\r
+                    pcd = dscObj.Contents[key].PcdsDynamicExVpd[index][0].split(DataType.TAB_VALUE_SPLIT)\r
+                    pcd.append(None)\r
+                    SkuId = dscObj.Contents[key].PcdsDynamicExVpd[index][1]\r
+                    SkuInfoList = []\r
+                    if SkuId == None:\r
+                        SkuId = 'DEFAULT'\r
+                    SkuIdList = map(lambda l: l.strip(), SkuId.split(DataType.TAB_VALUE_SPLIT))\r
+                    for Item in SkuIdList:\r
+                        SkuInfo = SkuInfoClassObject()\r
+                        SkuInfo.SkuId = Item\r
+                        SkuInfo.VpdOffset = pcd[2]\r
+                        SkuInfoList.append(SkuInfo)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC_EX_VPD, None, None, None, pcd[3], SkuInfoList)\r
+                for index in range(len(dscObj.Contents[key].PcdsDynamicExHii)):\r
+                    pcd = dscObj.Contents[key].PcdsDynamicExHii[index][0].split(DataType.TAB_VALUE_SPLIT)\r
+                    pcd.append(None)\r
+                    SkuId = dscObj.Contents[key].PcdsDynamicExHii[index][1]\r
+                    SkuInfoList = []\r
+                    if SkuId == None:\r
+                        SkuId = 'DEFAULT'\r
+                    SkuIdList = map(lambda l: l.strip(), SkuId.split(DataType.TAB_VALUE_SPLIT))\r
+                    for Item in SkuIdList:\r
+                        SkuInfo = SkuInfoClassObject()\r
+                        SkuInfo.SkuId = Item\r
+                        SkuInfo.VariableName = pcd[2]\r
+                        SkuInfo.VariableGuid = pcd[3]\r
+                        SkuInfo.VariableOffset = pcd[4]\r
+                        SkuInfo.HiiDefaultValue = pcd[5]                                                \r
+                        SkuInfoList.append(SkuInfo)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC_EX_HII, None, None, None, pcd[6], SkuInfoList)\r
+              \r
+                self.Build[key].PlatformDatabase[dsc] = pb\r
+                pb = None    \r
+            #End of Arch List Go Through    \r
+                \r
+        #End of Dsc Go Through\r
+        \r
+        #End of build PlatformDatabase\r
+        \r
+        #Build PackageDatabase\r
+        for dec in self.DecDatabase.keys():\r
+            decObj = self.DecDatabase[dec]\r
+\r
+            for key in DataType.ARCH_LIST:\r
+                pb = PackageBuildClassObject()\r
+                #Defines\r
+                pb.DescFilePath = dec\r
+                pb.PackageName = decObj.Defines.DefinesDictionary[TAB_DEC_DEFINES_PACKAGE_NAME][0]\r
+                pb.Guid = decObj.Defines.DefinesDictionary[TAB_DEC_DEFINES_PACKAGE_GUID][0]\r
+                pb.Version = decObj.Defines.DefinesDictionary[TAB_DEC_DEFINES_PACKAGE_VERSION][0]\r
+                \r
+                #Protocols\r
+                for index in range(len(decObj.Contents[key].Protocols)):\r
+                    list = decObj.Contents[key].Protocols[index].split(DataType.TAB_EQUAL_SPLIT)\r
+                    pb.Protocols[CleanString(list[0])] = CleanString(list[1])\r
+\r
+                #Ppis\r
+                for index in range(len(decObj.Contents[key].Ppis)):\r
+                    list = decObj.Contents[key].Ppis[index].split(DataType.TAB_EQUAL_SPLIT)\r
+                    pb.Ppis[CleanString(list[0])] = CleanString(list[1])            \r
+\r
+                #Guids\r
+                for index in range(len(decObj.Contents[key].Guids)):\r
+                    list = decObj.Contents[key].Guids[index].split(DataType.TAB_EQUAL_SPLIT)\r
+                    pb.Guids[CleanString(list[0])] = CleanString(list[1])        \r
+                \r
+                #Includes\r
+                for index in range(len(decObj.Contents[key].Includes)):\r
+                    pb.Includes.append(NormPath(decObj.Contents[key].Includes[index]))\r
+            \r
+                #LibraryClasses\r
+                for index in range(len(decObj.Contents[key].LibraryClasses)):\r
+                    list = decObj.Contents[key].LibraryClasses[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.LibraryClasses[CleanString(list[0])] = NormPath(CleanString(list[1]))\r
+                                                \r
+                #Pcds\r
+                for index in range(len(decObj.Contents[key].PcdsFixedAtBuild)):\r
+                    pcd = decObj.Contents[key].PcdsFixedAtBuild[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[2])] = PcdClassObject(pcd[0], pcd[2], DataType.TAB_PCDS_FIXED_AT_BUILD, pcd[3], pcd[4], pcd[1], None)\r
+                for index in range(len(decObj.Contents[key].PcdsPatchableInModule)):\r
+                    pcd = decObj.Contents[key].PcdsPatchableInModule[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[2])] = PcdClassObject(pcd[0], pcd[2], DataType.TAB_PCDS_PATCHABLE_IN_MODULE, pcd[3], pcd[4], pcd[1], None)\r
+                for index in range(len(decObj.Contents[key].PcdsFeatureFlag)):\r
+                    pcd = decObj.Contents[key].PcdsFeatureFlag[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[2])] = PcdClassObject(pcd[0], pcd[2], DataType.TAB_PCDS_FEATURE_FLAG, pcd[3], pcd[4], pcd[1], None)\r
+                for index in range(len(decObj.Contents[key].PcdsDynamic)):\r
+                    pcd = decObj.Contents[key].PcdsDynamic[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[2])] = PcdClassObject(pcd[0], pcd[2], DataType.TAB_PCDS_DYNAMIC, pcd[3], pcd[4], pcd[1], None)\r
+                for index in range(len(decObj.Contents[key].PcdsDynamicEx)):\r
+                    pcd = decObj.Contents[key].PcdsDynamicEx[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[2])] = PcdClassObject(pcd[0], pcd[2], DataType.TAB_PCDS_DYNAMIC_EX, pcd[3], pcd[4], pcd[1], None)\r
+            \r
+                #Add to database\r
+                self.Build[key].PackageDatabase[dec] = pb\r
+                pb = None    \r
+            #End of Arch List Go Through\r
+        \r
+        #End of Dec Go Through    \r
+        \r
+        #End of build PackageDatabase\r
+    \r
+        #Build ModuleDatabase\r
+        for inf in self.InfDatabase.keys():\r
+            infObj = self.InfDatabase[inf]\r
+            \r
+            for key in DataType.ARCH_LIST:\r
+                #Defines\r
+                pb = ModuleBuildClassObject()\r
+                pb.DescFilePath = inf\r
+                pb.BaseName = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_BASE_NAME][0]\r
+                pb.Guid = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_FILE_GUID][0]\r
+                pb.Version = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_VERSION_STRING][0]\r
+                pb.ModuleType = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_MODULE_TYPE][0]\r
+                pb.PcdIsDriver = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_PCD_IS_DRIVER][0]\r
+                pb.BinaryModule = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_BINARY_MODULE][0]\r
+                \r
+                for Index in range(len(infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_CUSTOM_MAKEFILE])):\r
+                    Makefile = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_CUSTOM_MAKEFILE][Index]\r
+                    if Makefile != '':\r
+                        MakefileList = Makefile.split(DataType.TAB_VALUE_SPLIT)\r
+                        if len(MakefileList) == 2:\r
+                            pb.CustomMakefile[CleanString(MakefileList[0])] = CleanString(MakefileList[1])\r
+                        else:\r
+                            raise ParseError('Wrong custom makefile defined in file ' + inf + ', correct format is CUSTOM_MAKEFILE = Family|Filename')\r
+                \r
+                if infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_EDK_RELEASE_VERSION][0] != '':\r
+                    pb.Specification[TAB_INF_DEFINES_EDK_RELEASE_VERSION] = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_EDK_RELEASE_VERSION][0]\r
+                if infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_EFI_SPECIFICATION_VERSION][0] != '':\r
+                    pb.Specification[TAB_INF_DEFINES_EFI_SPECIFICATION_VERSION] = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_EFI_SPECIFICATION_VERSION][0]                \r
+                \r
+                LibraryClass = infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_LIBRARY_CLASS][0]\r
+                if LibraryClass != '':\r
+                    l = LibraryClass.split(DataType.TAB_VALUE_SPLIT, 1)\r
+                    if len(l) == 1:\r
+                        pb.LibraryClass = LibraryClassObject(l[0], DataType.SUP_MODULE_LIST_STRING)\r
+                    else:\r
+                        pb.LibraryClass = LibraryClassObject(l[0], l[1])\r
+\r
+                pb.ModuleEntryPointList.extend(infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_ENTRY_POINT])\r
+                pb.ModuleUnloadImageList.extend(infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_UNLOAD_IMAGE])\r
+                pb.ConstructorList.extend(infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_CONSTRUCTOR])\r
+                pb.DestructorList.extend(infObj.Defines.DefinesDictionary[TAB_INF_DEFINES_DESTRUCTOR])\r
+\r
+                #Binaries\r
+                for index in range(len(infObj.Contents[key].Binaries)):\r
+                    BinaryFile = infObj.Contents[key].Binaries[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    BinaryFile.append('')\r
+                    FileType = BinaryFile[0].strip()\r
+                    Target = BinaryFile[1].strip()\r
+                    FileName = NormPath(BinaryFile[2].strip())\r
+                    PcdFeatureFlag = BinaryFile[3].strip()\r
+                    pb.Binaries.append(ModuleBinaryFilesClassObject(FileName, FileType, Target, PcdFeatureFlag))\r
+                    \r
+                #Sources\r
+                for index in range(len(infObj.Contents[key].Sources)):\r
+                    SourceFile = infObj.Contents[key].Sources[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    if len(SourceFile) == 6:\r
+                        FileName = NormPath(SourceFile[0].strip())\r
+                        PcdFeatureFlag = SourceFile[1].strip()\r
+                        TagName = SourceFile[3].strip()\r
+                        ToolCode = SourceFile[4].strip()\r
+                        ToolChainFamily = SourceFile[2].strip()\r
+                        String = SourceFile[5].strip()\r
+                        pb.Sources.append(ModuleSourceFilesClassObject(FileName, PcdFeatureFlag, TagName, ToolCode, ToolChainFamily, String))\r
+                    elif len(SourceFile) == 1:\r
+                        pb.Sources.append(ModuleSourceFilesClassObject(NormPath(infObj.Contents[key].Sources[index])))\r
+                    else:\r
+                        raise ParseError("Inconsistent '|' value defined in SourceFiles." + key + " section in file " + inf)\r
+\r
+                #Protocols\r
+                for index in range(len(infObj.Contents[key].Protocols)):\r
+                    pb.Protocols.append(infObj.Contents[key].Protocols[index])\r
+            \r
+                #Ppis\r
+                for index in range(len(infObj.Contents[key].Ppis)):\r
+                    pb.Ppis.append(infObj.Contents[key].Ppis[index])\r
+                                \r
+                #Guids\r
+                for index in range(len(infObj.Contents[key].Guids)):\r
+                    pb.Guids.append(infObj.Contents[key].Guids[index])\r
+            \r
+                #Includes\r
+                for index in range(len(infObj.Contents[key].Includes)):\r
+                    pb.Includes.append(NormPath(infObj.Contents[key].Includes[index]))\r
+            \r
+                #Packages\r
+                for index in range(len(infObj.Contents[key].Packages)):\r
+                    pb.Packages.append(NormPath(infObj.Contents[key].Packages[index]))\r
+                    \r
+                #BuildOptions\r
+                for index in range(len(infObj.Contents[key].BuildOptions)):\r
+                    b = infObj.Contents[key].BuildOptions[index].split(DataType.TAB_EQUAL_SPLIT, 1)\r
+                    Family = ''\r
+                    ToolChain = ''\r
+                    Flag = ''\r
+                    if b[0].find(':') > -1:\r
+                        Family = CleanString(b[0][ : b[0].find(':')])\r
+                        ToolChain = CleanString(b[0][b[0].find(':') + 1 : ])\r
+                    else:\r
+                        ToolChain = CleanString(b[0])\r
+                    Flag = CleanString(b[1])\r
+                    pb.BuildOptions[(Family, ToolChain)] = Flag\r
+                self.FindBuildOptions(key, inf, pb.BuildOptions)\r
+                \r
+                #Depex\r
+                pb.Depex = ' '.join(infObj.Contents[key].Depex)\r
+                \r
+                #LibraryClasses\r
+                for index in range(len(infObj.Contents[key].LibraryClasses)):\r
+                    #Get LibraryClass name and default instance if existing\r
+                    list = infObj.Contents[key].LibraryClasses[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    if len(list) < 2:\r
+                        v = ''\r
+                    else:\r
+                        v = list[1]\r
+                    \r
+                    if pb.LibraryClass != None:\r
+                        #For Library\r
+                        for type in pb.LibraryClass.SupModList:\r
+                            instance = self.FindLibraryClassInstanceOfLibrary(CleanString(list[0]), key, type)\r
+                            if instance != None:\r
+                                v = instance\r
+                                pb.LibraryClasses[(CleanString(list[0]), type)] = NormPath(CleanString(v))\r
+                    else:\r
+                        #For Module                        \r
+                        instance = self.FindLibraryClassInstanceOfModule(CleanString(list[0]), key, pb.ModuleType, inf) \r
+                        if instance != None:\r
+                            v = instance\r
+                            pb.LibraryClasses[(CleanString(list[0]), pb.ModuleType)] = NormPath(CleanString(v))\r
+\r
+                #Pcds\r
+                for index in range(len(infObj.Contents[key].PcdsFixedAtBuild)):\r
+                    pcd = infObj.Contents[key].PcdsFixedAtBuild[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = self.FindPcd(key, pcd[0], pcd[1], DataType.TAB_PCDS_FIXED_AT_BUILD)\r
+                for index in range(len(infObj.Contents[key].PcdsPatchableInModule)):\r
+                    pcd = infObj.Contents[key].PcdsPatchableInModule[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = self.FindPcd(key, pcd[0], pcd[1], DataType.TAB_PCDS_PATCHABLE_IN_MODULE)\r
+                    #pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_PATCHABLE_IN_MODULE, None, None, None, None)                    \r
+                for index in range(len(infObj.Contents[key].PcdsFeatureFlag)):\r
+                    pcd = infObj.Contents[key].PcdsFeatureFlag[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = self.FindPcd(key, pcd[0], pcd[1], DataType.TAB_PCDS_FEATURE_FLAG)\r
+                    #pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_FEATURE_FLAG, None, None, None, None)                    \r
+                for index in range(len(infObj.Contents[key].PcdsDynamic)):\r
+                    pcd = infObj.Contents[key].PcdsDynamic[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = self.FindPcd(key, pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC)\r
+                    #pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC, None, None, None, None)\r
+                for index in range(len(infObj.Contents[key].PcdsDynamicEx)):\r
+                    pcd = infObj.Contents[key].PcdsDynamicEx[index].split(DataType.TAB_VALUE_SPLIT)\r
+                    pb.Pcds[(pcd[0], pcd[1])] = self.FindPcd(key, pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC_EX)\r
+                    #pb.Pcds[(pcd[0], pcd[1])] = PcdClassObject(pcd[0], pcd[1], DataType.TAB_PCDS_DYNAMIC_EX, None, None, None, None)\r
+                                        \r
+                #Add to database\r
+                self.Build[key].ModuleDatabase[inf] = pb\r
+                pb = None    \r
+            #End of Arch List Go Through\r
+        \r
+        #End of Inf Go Through\r
+        \r
+        #End of build ModuleDatabase    \r
+    \r
+    #End of self.Init\r
+    \r
+    def UpdateInfDatabase(self, infFileName, LibraryClass, Arch):\r
+        infFileName = NormPath(infFileName)\r
+        LibList = self.InfDatabase[infFileName].Contents[Arch].LibraryClasses\r
+        NotFound = True\r
+        for Item in LibList:\r
+            LibName = Item.split(DataType.TAB_VALUE_SPLIT)[0].strip()\r
+            if LibName == LibraryClass:\r
+                return\r
+        \r
+        if NotFound:\r
+            self.InfDatabase[infFileName].Contents[Arch].LibraryClasses.extend([LibraryClass])\r
+    \r
+    def AddToInfDatabase(self, infFileName):\r
+        infFileName = NormPath(infFileName)\r
+        file = self.Workspace.WorkspaceFile(infFileName)\r
+        if os.path.exists(file) and os.path.isfile(file):\r
+            if infFileName not in self.InfDatabase:\r
+                self.InfDatabase[infFileName] = Inf(file, True)\r
+                \r
+    def AddToDecDatabase(self, decFileName):\r
+        decFileName = NormPath(decFileName)\r
+        file = self.Workspace.WorkspaceFile(decFileName)\r
+        if os.path.exists(file) and os.path.isfile(file):\r
+            if decFileName not in self.DecDatabase:\r
+                self.DecDatabase[decFileName] = Dec(file, True)\r
+                \r
+    def FindLibraryClassInstanceOfModule(self, lib, arch, moduleType, moduleName):\r
+        for dsc in self.DscDatabase.keys():\r
+            #First find if exist in <LibraryClass> of <Components> from dsc file            \r
+            dscObj = self.DscDatabase[dsc]\r
+            for index in range(len(dscObj.Contents[arch].Components)):\r
+                if NormPath(dscObj.Contents[arch].Components[index][0]) == moduleName and len(dscObj.Contents[arch].Components[index][1]) > 0:\r
+                    #Search each library class\r
+                    LibList = dscObj.Contents[arch].Components[index][1]\r
+                    for indexOfLib in range(len(LibList)):\r
+                        if LibList[indexOfLib].split(DataType.TAB_VALUE_SPLIT)[0].strip() == lib:\r
+                            return LibList[indexOfLib].split(DataType.TAB_VALUE_SPLIT)[1].strip()\r
+            \r
+            #Second find if exist in <LibraryClass> of <LibraryClasses> from dsc file            \r
+            if (lib, moduleType) in self.Build[arch].PlatformDatabase[dsc].LibraryClasses:\r
+                return self.Build[arch].PlatformDatabase[dsc].LibraryClasses[(lib, moduleType)]\r
+            elif (lib, None) in self.Build[arch].PlatformDatabase[dsc].LibraryClasses:\r
+                return self.Build[arch].PlatformDatabase[dsc].LibraryClasses[(lib, None)]\r
+            \r
+    def FindLibraryClassInstanceOfLibrary(self, lib, arch, type):\r
+        for dsc in self.DscDatabase.keys():\r
+            dscObj = self.DscDatabase[dsc]\r
+            if (lib, type) in self.Build[arch].PlatformDatabase[dsc].LibraryClasses:\r
+                return self.Build[arch].PlatformDatabase[dsc].LibraryClasses[(lib, type)]\r
+            elif (lib, None) in self.Build[arch].PlatformDatabase[dsc].LibraryClasses:\r
+                return self.Build[arch].PlatformDatabase[dsc].LibraryClasses[(lib, None)]\r
+            \r
+    def FindBuildOptions(self, arch, moduleName, BuildOptions):\r
+        for dsc in self.DscDatabase.keys():\r
+            #First find if exist in <BuildOptions> of <Components> from dsc file\r
+            dscObj = self.DscDatabase[dsc]\r
+            for index in range(len(dscObj.Contents[arch].Components)):\r
+                if NormPath(dscObj.Contents[arch].Components[index][0]) == moduleName and len(dscObj.Contents[arch].Components[index][2]) > 0:\r
+                    list = dscObj.Contents[arch].Components[index][2]\r
+                    for l in list:\r
+                        b = l.split(DataType.TAB_EQUAL_SPLIT, 1)\r
+                        Family = ''\r
+                        ToolChain = ''\r
+                        Flag = ''\r
+                        if b[0].find(':') > -1:\r
+                            Family = CleanString(b[0][ : b[0].find(':')])\r
+                            ToolChain = CleanString(b[0][b[0].find(':') + 1 : ])\r
+                        else:\r
+                            ToolChain = CleanString(b[0])\r
+                        Flag = CleanString(b[1])\r
+                        BuildOptions[(Family, ToolChain)] = Flag\r
+                        \r
+    def FindPcd(self, arch, CName, GuidCName, Type):\r
+        DatumType = ''\r
+        DefaultValue = ''\r
+        TokenValue = ''\r
+        MaxDatumSize = ''\r
+        SkuInfoList = None\r
+        for dsc in self.Build[arch].PlatformDatabase.keys():\r
+            platform = self.Build[arch].PlatformDatabase[dsc]\r
+            pcds = platform.Pcds\r
+            if (CName, GuidCName) in pcds:\r
+                Type = pcds[(CName, GuidCName)].Type\r
+                DatumType = pcds[(CName, GuidCName)].DatumType\r
+                DefaultValue = pcds[(CName, GuidCName)].DefaultValue\r
+                TokenValue = pcds[(CName, GuidCName)].TokenValue\r
+                MaxDatumSize = pcds[(CName, GuidCName)].MaxDatumSize\r
+                SkuInfoList =  pcds[(CName, GuidCName)].SkuInfoList\r
+                break\r
+\r
+        for dec in self.Build[arch].PackageDatabase.keys():\r
+            package = self.Build[arch].PackageDatabase[dec]\r
+            pcds = package.Pcds\r
+            if (CName, GuidCName) in pcds:\r
+                DatumType = pcds[(CName, GuidCName)].DatumType\r
+                #DefaultValue = pcds[(CName, GuidCName)].DefaultValue\r
+                TokenValue = pcds[(CName, GuidCName)].TokenValue\r
+                #MaxDatumSize = pcds[(CName, GuidCName)].MaxDatumSize\r
+                break\r
+        \r
+        return PcdClassObject(CName, GuidCName, Type, DatumType, DefaultValue, TokenValue, MaxDatumSize, SkuInfoList)\r
+    \r
+    def ReloadPcd(self, FvDict):\r
+        pass\r
+                \r
+# This acts like the main() function for the script, unless it is 'import'ed into another\r
+# script.\r
+if __name__ == '__main__':\r
+\r
+    # Nothing to do here. Could do some unit tests.\r
+    ewb = WorkspaceBuild()\r
+    #printDict(ewb.TargetTxt.TargetTxtDictionary)\r
+    #printDict(ewb.ToolDef.ToolsDefTxtDictionary)\r
+#    print ewb.DscDatabase\r
+#    print ewb.InfDatabase\r
+#    print ewb.DecDatabase\r
+    print 'SupArchList', ewb.SupArchList\r
+    print 'BuildTarget', ewb.BuildTarget\r
+    print 'SkuId', ewb.SkuId\r
+    \r
+    #\r
+    for arch in DataType.ARCH_LIST:\r
+        print arch\r
+        print 'Platform'\r
+        for platform in ewb.Build[arch].PlatformDatabase.keys():\r
+            p = ewb.Build[arch].PlatformDatabase[platform]\r
+            print 'DescFilePath = ', p.DescFilePath     \r
+            print 'PlatformName = ', p.PlatformName     \r
+            print 'Guid = ', p.Guid                     \r
+            print 'Version = ', p.Version\r
+            print 'OutputDirectory = ', p.OutputDirectory                \r
+            print 'FlashDefinition = ', p.FlashDefinition\r
+            print 'SkuIds = ', p.SkuIds\r
+            print 'Modules = ', p.Modules\r
+            print 'LibraryClasses = ', p.LibraryClasses \r
+            print 'Pcds = ', p.Pcds\r
+            for item in p.Pcds.keys():\r
+                print p.Pcds[item]\r
+            print 'BuildOptions = ', p.BuildOptions\r
+            print ''   \r
+        #End of Platform\r
+    \r
+        print 'package'\r
+        for package in ewb.Build[arch].PackageDatabase.keys():\r
+            p = ewb.Build[arch].PackageDatabase[package]\r
+            print 'DescFilePath = ', p.DescFilePath    \r
+            print 'PackageName = ', p.PackageName     \r
+            print 'Guid = ', p.Guid                    \r
+            print 'Version = ', p.Version             \r
+            print 'Protocols = ', p.Protocols         \r
+            print 'Ppis = ', p.Ppis                    \r
+            print 'Guids = ', p.Guids                 \r
+            print 'Includes = ', p.Includes            \r
+            print 'LibraryClasses = ', p.LibraryClasses\r
+            print 'Pcds = ', p.Pcds\r
+            print ''                    \r
+        #End of Package\r
+        \r
+        print 'module'\r
+        for module in ewb.Build[arch].ModuleDatabase.keys():\r
+            p = ewb.Build[arch].ModuleDatabase[module]\r
+            print 'DescFilePath = ', p.DescFilePath                    \r
+            print 'BaseName = ', p.BaseName                         \r
+            print 'ModuleType = ', p.ModuleType                     \r
+            print 'Guid = ', p.Guid                                 \r
+            print 'Version = ', p.Version\r
+            print 'CustomMakefile = ', p.CustomMakefile\r
+            print 'Specification = ', p.Specification\r
+            print 'PcdIsDriver = ', p.PcdIsDriver\r
+            if p.LibraryClass != None:\r
+                print 'LibraryClass = ', p.LibraryClass.LibraryClass\r
+                print 'SupModList = ', p.LibraryClass.SupModList\r
+            print 'ModuleEntryPointList = ', p.ModuleEntryPointList \r
+            print 'ModuleUnloadImageList = ', p.ModuleUnloadImageList\r
+            print 'ConstructorList = ', p.ConstructorList            \r
+            print 'DestructorList = ', p.DestructorList             \r
+                                                                     \r
+            print 'Binaries = '\r
+            for item in p.Binaries:\r
+                print str(item)\r
+            print 'Sources = '\r
+            for item in p.Sources:\r
+                print str(item)\r
+            print 'LibraryClasses = ', p.LibraryClasses             \r
+            print 'Protocols = ', p.Protocols                        \r
+            print 'Ppis = ', p.Ppis                                 \r
+            print 'Guids = ', p.Guids                                \r
+            print 'Includes = ', p.Includes                         \r
+            print 'Packages = ', p.Packages                         \r
+            print 'Pcds = ', p.Pcds\r
+            print 'BuildOptions = ', p.BuildOptions\r
+            print 'Depex = ', p.Depex\r
+            print ''\r
+        #End of Module    \r
+            \r
+    #End of Arch List\r
diff --git a/Source/Python/Common/EdkLogger.py b/Source/Python/Common/EdkLogger.py
new file mode 100644 (file)
index 0000000..7d1367c
--- /dev/null
@@ -0,0 +1,70 @@
+import sys, os, logging
+
+DEBUG_0 = 1
+DEBUG_1 = 2
+DEBUG_2 = 3
+DEBUG_3 = 4
+DEBUG_4 = 5
+DEBUG_5 = 6
+DEBUG_6 = 7
+DEBUG_7 = 8
+DEBUG_8 = 9
+DEBUG_9 = 10
+VERBOSE = 15
+INFO    = logging.INFO      # 20
+QUIET   = 50
+
+_log_levels = [DEBUG_0, DEBUG_1, DEBUG_2, DEBUG_3, DEBUG_4, DEBUG_5, DEBUG_6, DEBUG_7, DEBUG_8, DEBUG_9, VERBOSE, INFO, QUIET]
+
+_debug_logger = logging.getLogger("tool_debug")
+_debug_logger.setLevel(INFO)
+_debug_ch = logging.StreamHandler(sys.stdout)
+_debug_formatter = logging.Formatter("> %(filename)s : %(lineno)d : %(funcName)s():\n>\t%(message)s")
+_debug_ch.setFormatter(_debug_formatter)
+_debug_logger.addHandler(_debug_ch)
+
+_verbose_logger = logging.getLogger("tool_verbose")
+_verbose_logger.setLevel(INFO)
+_verbose_ch = logging.StreamHandler(sys.stdout)
+#_verbose_formatter = logging.Formatter("[%(asctime)s]%(message)s")
+_verbose_formatter = logging.Formatter("> %(message)s")
+_verbose_ch.setFormatter(_verbose_formatter)
+_verbose_logger.addHandler(_verbose_ch)
+
+_info_logger = logging.getLogger("tool_info")
+_info_logger.setLevel(INFO)
+_info_ch = logging.StreamHandler(sys.stdout)
+_info_formatter = logging.Formatter("%(message)s")
+_info_ch.setFormatter(_info_formatter)
+_info_logger.addHandler(_info_ch)
+
+debug = _debug_logger.log
+
+def verbose(msg):
+    return _verbose_logger.log(VERBOSE, msg)
+
+info    = _info_logger.info
+
+def setLevel(level):
+    if level not in _log_levels:
+        info("Not supported log level (%d)" % level)
+        level = INFO
+    _debug_logger.setLevel(level)
+    _verbose_logger.setLevel(level)
+    _info_logger.setLevel(level)
+
+def setLogFile(log):
+    if os.path.exists(log):
+        os.remove(log)
+        
+    _ch = logging.FileHandler(log)
+    _ch.setFormatter(_debug_formatter)
+    _debug_logger.addHandler(_ch)
+    
+    _ch = logging.FileHandler(log)
+    _ch.setFormatter(_verbose_formatter)
+    _verbose_logger.addHandler(_ch)
+
+    _ch = logging.FileHandler(log)
+    _ch.setFormatter(_info_formatter)
+    _info_logger.addHandler(_ch)
diff --git a/Source/Python/Common/Identification.py b/Source/Python/Common/Identification.py
new file mode 100644 (file)
index 0000000..e79ba83
--- /dev/null
@@ -0,0 +1,30 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+"""\r
+This file is used to define the identification of INF/DEC/DSC files\r
+"""\r
+\r
+class Identification(object):\r
+  def __init__(self):\r
+    self.FileName = ''\r
+    self.FileFullPath = ''\r
+    self.FileRelativePath = ''\r
+\r
+  def GetFileName(self, FileFullPath, FileRelativePath):\r
+    pass\r
+\r
+  def GetFileFullPath(self, FileName, FileRelativePath):\r
+    pass\r
+\r
+  def GetFileRelativePath(self, FileName, FileFullPath):\r
+    pass\r
+\r
+if __name__ == '__main__':\r
+  id = Identification()\r
diff --git a/Source/Python/Common/InfClassObject.py b/Source/Python/Common/InfClassObject.py
new file mode 100644 (file)
index 0000000..dc36845
--- /dev/null
@@ -0,0 +1,169 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+#\r
+#This file is used to define each component of INF file\r
+#\r
+\r
+import os\r
+import EdkLogger\r
+from String import *\r
+from DataType import *\r
+from Identification import *\r
+from Dictionary import *\r
+\r
+class InfObject(object):\r
+    def __init__(self):\r
+        object.__init__()\r
+\r
+class InfDefines(InfObject):\r
+    def __init__(self):\r
+        self.DefinesDictionary = {\r
+            #Required\r
+            TAB_INF_DEFINES_BASE_NAME                               : [''],\r
+            TAB_INF_DEFINES_FILE_GUID                               : [''],\r
+            TAB_INF_DEFINES_MODULE_TYPE                             : [''],\r
+            TAB_INF_DEFINES_EFI_SPECIFICATION_VERSION               : [''],\r
+            TAB_INF_DEFINES_EDK_RELEASE_VERSION                     : [''],\r
+            \r
+            #Optional            \r
+            TAB_INF_DEFINES_INF_VERSION                             : [''],\r
+            TAB_INF_DEFINES_BINARY_MODULE                           : [''],\r
+            TAB_INF_DEFINES_LIBRARY_CLASS                           : [''],\r
+            TAB_INF_DEFINES_COMPONENT_TYPE                          : [''],\r
+            TAB_INF_DEFINES_MAKEFILE_NAME                           : [''],\r
+            TAB_INF_DEFINES_BUILD_NUMBER                            : [''],\r
+            TAB_INF_DEFINES_BUILD_TYPE                              : [''],\r
+            TAB_INF_DEFINES_FFS_EXT                                 : [''],\r
+            TAB_INF_DEFINES_FV_EXT                                  : [''],\r
+            TAB_INF_DEFINES_SOURCE_FV                               : [''],\r
+            TAB_INF_DEFINES_VERSION_NUMBER                          : [''],\r
+            TAB_INF_DEFINES_VERSION_STRING                          : [''],\r
+            TAB_INF_DEFINES_PCD_IS_DRIVER                           : [''],\r
+            TAB_INF_DEFINES_TIANO_R8_FLASHMAP_H                     : [''],\r
+            TAB_INF_DEFINES_ENTRY_POINT                             : [''],\r
+            TAB_INF_DEFINES_UNLOAD_IMAGE                            : [''],\r
+            TAB_INF_DEFINES_CONSTRUCTOR                             : [''],\r
+            TAB_INF_DEFINES_DESTRUCTOR                              : [''],\r
+            TAB_INF_DEFINES_DEFINE                                  : [''],\r
+            TAB_INF_DEFINES_CUSTOM_MAKEFILE                         : ['']\r
+        }\r
+        self.ToolFlags = []     #'${FAMILY}:${TARGET}_${TAGNAME}_${ARCH}_${TOOLCODE}_FLAGS'\r
+        self.MacroName = '$(MACRO_NAME)'\r
+\r
+class InfContents(InfObject):\r
+    def __init__(self):\r
+        self.Sources = []\r
+        self.BuildOptions = []\r
+        self.Binaries = []\r
+        self.Includes = []\r
+        self.Guids = []\r
+        self.Protocols = []\r
+        self.Ppis = []\r
+        self.LibraryClasses = []\r
+        self.Packages = []\r
+        self.PcdsFixedAtBuild = []\r
+        self.PcdsPatchableInModule = []\r
+        self.PcdsFeatureFlag = []\r
+        self.PcdsDynamic = []\r
+        self.PcdsDynamicEx = []\r
+        self.Depex = []\r
+        \r
+class Inf(InfObject):\r
+    def __init__(self, filename = None, isMergeAllArches = False):\r
+        self.identification = Identification()\r
+        self.Defines = InfDefines()\r
+        self.Contents = {}\r
+        \r
+        for key in DataType.ARCH_LIST_FULL:\r
+            self.Contents[key] = InfContents()\r
+\r
+        self.KeyList = [\r
+            TAB_BINARIES, TAB_SOURCES, TAB_INCLUDES, TAB_GUIDS, TAB_PROTOCOLS, TAB_PPIS, TAB_LIBRARY_CLASSES, TAB_PACKAGES, TAB_BUILD_OPTIONS, \\r
+            TAB_PCDS_FIXED_AT_BUILD_NULL, TAB_PCDS_PATCHABLE_IN_MODULE_NULL, TAB_PCDS_FEATURE_FLAG_NULL, \\r
+            TAB_PCDS_DYNAMIC_NULL, TAB_PCDS_DYNAMIC_EX_NULL, TAB_DEPEX\r
+        ]\r
+                \r
+        if filename != None:\r
+            self.LoadInfFile(filename)\r
+        \r
+        if isMergeAllArches:\r
+            self.MergeAllArches()\r
+    \r
+    def MergeAllArches(self):\r
+        for key in self.KeyList:\r
+            for arch in DataType.ARCH_LIST:\r
+                Command = "self.Contents[arch]." + key + ".extend(" + "self.Contents['" + DataType.TAB_ARCH_COMMON + "']." + key + ")"\r
+                eval(Command)     \r
+            \r
+    def ParseInf(self, Lines, Key, KeyField):\r
+            GetMultipleValuesOfKeyFromLines(Lines, Key, KeyField, TAB_COMMENT_SPLIT)\r
+\r
+    def LoadInfFile(self, filename):     \r
+        (filepath, name) = os.path.split(filename)\r
+        self.identification.FileName = name\r
+        self.identification.FileFullPath = filename\r
+        self.identification.FileRelativePath = filepath\r
+        \r
+        f = open(filename, 'r').read()\r
+        sects = f.split('[')\r
+        for sect in sects:\r
+            tab = (sect.split(TAB_SECTION_END, 1)[0]).upper()\r
+            if tab == TAB_INF_DEFINES.upper():\r
+                GetSingleValueOfKeyFromLines(sect, self.Defines.DefinesDictionary, TAB_COMMENT_SPLIT, TAB_EQUAL_SPLIT, False, None)\r
+                if self.Defines.DefinesDictionary[TAB_INF_DEFINES_ENTRY_POINT][0] == '':\r
+                    self.Defines.DefinesDictionary[TAB_INF_DEFINES_ENTRY_POINT] = []\r
+                if self.Defines.DefinesDictionary[TAB_INF_DEFINES_UNLOAD_IMAGE][0] == '':\r
+                    self.Defines.DefinesDictionary[TAB_INF_DEFINES_UNLOAD_IMAGE] = []\r
+                if self.Defines.DefinesDictionary[TAB_INF_DEFINES_CONSTRUCTOR][0] == '':\r
+                    self.Defines.DefinesDictionary[TAB_INF_DEFINES_CONSTRUCTOR] = []\r
+                if self.Defines.DefinesDictionary[TAB_INF_DEFINES_DESTRUCTOR][0] == '':\r
+                    self.Defines.DefinesDictionary[TAB_INF_DEFINES_DESTRUCTOR] = []\r
+                continue\r
+            for arch in DataType.ARCH_LIST_FULL + [DataType.TAB_ARCH_NULL]:\r
+                for key in self.KeyList:\r
+                    if arch != DataType.TAB_ARCH_NULL:\r
+                        target = (key + DataType.TAB_SPLIT + arch).upper()\r
+                    else:\r
+                        target = key.upper()\r
+                    if tab == target:\r
+                        if arch != DataType.TAB_ARCH_NULL:\r
+                            Command = 'self.ParseInf(sect, tab, self.Contents[arch].' + key + ')'\r
+                            eval(Command)\r
+                            continue\r
+                        else:\r
+                            Command = "self.ParseInf(sect, tab, self.Contents['" + DataType.TAB_ARCH_COMMON + "']." + key + ')'\r
+                            eval(Command)\r
+                            continue\r
+        #EndFor\r
+\r
+    def showInf(self):\r
+        print TAB_SECTION_START + TAB_INF_DEFINES + TAB_SECTION_END\r
+        printDict(self.Defines.DefinesDictionary)\r
+\r
+        for key in self.KeyList:\r
+            for arch in DataType.ARCH_LIST_FULL:\r
+                Command = "printList(TAB_SECTION_START + '" + \\r
+                                    key + DataType.TAB_SPLIT + arch + \\r
+                                    "' + TAB_SECTION_END, self.Contents[arch]." + key + ')'\r
+                eval(Command)\r
+        print ""\r
+        \r
+if __name__ == '__main__':\r
+    m = Inf()\r
+    directory = 'C:\Documents and Settings\\hchen30\\Desktop\\prototype\\inf'\r
+    fileList = []\r
+    \r
+    for f in os.listdir(directory):\r
+        if os.path.splitext(os.path.normcase(f))[1] == '.inf':\r
+            fileList.append(os.path.join(directory, os.path.normcase(f)))\r
+            \r
+    for f in fileList:\r
+        m = Inf(f)\r
+        m.showInf()\r
diff --git a/Source/Python/Common/SequentialDict.py b/Source/Python/Common/SequentialDict.py
new file mode 100644 (file)
index 0000000..afffc7a
--- /dev/null
@@ -0,0 +1,142 @@
+class SequentialDict(dict):
+    def __init__(self):
+        self._key_list = []
+
+    def __setitem__(self, key, value):
+        if key not in self._key_list:
+            self._key_list.append(key)
+        dict.__setitem__(self, key, value)
+
+    def __delitem__(self, key):
+        self._key_list.remove(key)
+        del self[key]
+    #
+    # used in "for k in dict" loop to ensure the correct order
+    #
+    def __iter__(self):
+        return self.iterkeys()
+
+    def __len__(self):
+        return len(self._key_list)
+
+    def __contains__(self, key):
+        return key in self._key_list
+
+    def has_key(self, key):
+        return key in self._key_list
+
+    def clear(self):
+        self._key_list = []
+        dict.clear(self)
+
+    def keys(self):
+        keys = []
+        for key in self._key_list:
+            keys.append(key)
+        return keys
+
+    def values(self):
+        values = []
+        for key in self._key_list:
+            values.append(self[key])
+        return values
+
+    def items(self):
+        items = []
+        for key in self._key_list:
+            items.append((key, self[key]))
+        return items
+
+    def iteritems(self):
+        return iter(self.items())
+
+    def iterkeys(self):
+        return iter(self.keys())
+
+    def itervalues(self):
+        return iter(self.values())
+
+    def pop(self, key, *dv):
+        value = None
+        if len(dv) == 0 or key in self._key_list:
+            value = self[key]
+            del self[key]
+        else:
+            value = kv[0]
+        return value
+
+    def popitem(self):
+        key = self._key_list[0]
+        value = self[key]
+        del self[key]
+        return key, value
+
+# This acts like the main() function for the script, unless it is 'import'ed into another
+# script.
+if __name__ == '__main__':
+    sd = SequentialDict()
+    print "#### 11111111111 ###"
+    sd["abc"] = 1
+    sd['efg'] = 2
+    sd['hij'] = 3
+    print "for key in dict (%d) =" % len(sd),
+    for key in sd:
+        print "(",key, sd[key],")",
+    print
+    print "keys() =",sd.keys()
+    print "values() =",sd.values()
+    print "items() =",sd.items()
+    print "iterkeys() =",[k for k in sd.iterkeys()]
+    print "itervalues() =",[v for v in sd.itervalues()]
+    print "iteritems() =",[i for i in sd.iteritems()]
+    print sd
+
+    print "#### 22222222222 ###"
+    sd.clear()
+    sd['efg'] = 1
+    sd['hij'] = 2
+    sd["abc"] = 3
+    print "for key in dict (%d) =" % len(sd),
+    for key in sd:
+        print "(",key, sd[key],")",
+    print
+    print "keys() =",sd.keys()
+    print "values() =",sd.values()
+    print "items() =",sd.items()
+    print "iterkeys() =",[k for k in sd.iterkeys()]
+    print "itervalues() =",[v for v in sd.itervalues()]
+    print "iteritems() =",[i for i in sd.iteritems()]
+    print sd
+
+    print "#### 33333333333 ###"
+    sd.clear()
+    sd['hij'] = 1
+    sd["abc"] = 2
+    sd['efg'] = 3
+    print "for key in dict (%d) =" % len(sd),
+    for key in sd:
+        print "(",key, sd[key],")",
+    print
+    print "keys() =",sd.keys()
+    print "values() =",sd.values()
+    print "items() =",sd.items()
+    print "iterkeys() =",[k for k in sd.iterkeys()]
+    print "itervalues() =",[v for v in sd.itervalues()]
+    print "iteritems() =",[i for i in sd.iteritems()]
+    print sd
+
+    print "#### 44444444444 ###"
+    sd["abc"] = 1
+    sd['efg'] = 2
+    sd['hij'] = 3
+    print "for key in dict (%d) =" % len(sd),
+    for key in sd:
+        print "(",key, sd[key],")",
+    print
+    print "keys() =",sd.keys()
+    print "values() =",sd.values()
+    print "items() =",sd.items()
+    print "iterkeys() =",[k for k in sd.iterkeys()]
+    print "itervalues() =",[v for v in sd.itervalues()]
+    print "iteritems() =",[i for i in sd.iteritems()]
+    print sd
diff --git a/Source/Python/Common/String.py b/Source/Python/Common/String.py
new file mode 100644 (file)
index 0000000..ac1d797
--- /dev/null
@@ -0,0 +1,242 @@
+# Copyright (c) 2007, Intel Corporation\r
+# All rights reserved. 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
+#\r
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+#\r
+#This file is used to define some common useful string functions\r
+#\r
+\r
+import DataType\r
+import os.path\r
+import string\r
+\r
+def MergeModulePcds(pcds, pcdsFixedAtBuild, pcdsPatchableInModule, pcdsFeatureFlag, pcdsDynamic):\r
+    #[ ['PcdName|PcdGuid|PcdType', 'IA32|X64|IPF|EBC'], ...]\r
+    \r
+    Item = pcdsFixedAtBuild\r
+    for index in range(len(Item)):\r
+        pcds.append([(Item[index][0].split(DataType.TAB_VALUE_SPLIT))[1] + DataType.TAB_VALUE_SPLIT + DataType.TAB_PCDS_FIXED_AT_BUILD, Item[index][1]])\r
+\r
+    Item = pcdsPatchableInModule\r
+    for index in range(len(Item)):\r
+        pcds.append([(Item[index][0].split(DataType.TAB_VALUE_SPLIT))[1] + DataType.TAB_VALUE_SPLIT + DataType.TAB_PCDS_PATCHABLE_IN_MODULE, Item[index][1]])\r
+                                 \r
+    Item = pcdsFeatureFlag\r
+    for index in range(len(Item)):\r
+        pcds.append([(Item[index][0].split(DataType.TAB_VALUE_SPLIT))[1] + DataType.TAB_VALUE_SPLIT + DataType.TAB_PCDS_FEATURE_FLAG, Item[index][1]])\r
+                                 \r
+    Item = pcdsDynamic\r
+    for index in range(len(Item)):\r
+        pcds.append([(Item[index][0].split(DataType.TAB_VALUE_SPLIT))[1] + DataType.TAB_VALUE_SPLIT + DataType.TAB_PCDS_DYNAMIC, Item[index][1]])\r
+\r
+def MergeAllArch(list1, listCommon, listIa32, listX64, listIpf, listEbc):\r
+    isFound = False\r
+    for j in range(len(list1)):\r
+        list1[j] = [list1[j], '']\r
+    \r
+    for i in listCommon:\r
+        if i not in list1:\r
+            list1.append([i, ''])\r
+    for i in listIa32:\r
+        for j in range(len(list1)):\r
+            if i == list1[j][0]:\r
+                isFound = True\r
+                list1[j] = [list1[j][0], 'IA32|']\r
+                break\r
+        if not isFound:\r
+            list1.append([i, 'IA32|'])\r
+        isFound = False\r
+    \r
+    for i in listX64:\r
+        for j in range(len(list1)):\r
+            if i == list1[j][0]:\r
+                isFound = True\r
+                list1[j] = [list1[j][0], list1[j][1] + 'X64|']\r
+                break\r
+        if not isFound:\r
+            list1.append([i, 'X64|'])\r
+        isFound = False\r
+    \r
+    for i in listIpf:\r
+        for j in range(len(list1)):\r
+            if i == list1[j][0]:\r
+                isFound = True\r
+                list1[j] = [list1[j][0], list1[j][1] + 'Ipf|']\r
+                break\r
+        if not isFound:\r
+            list1.append([i, 'Ipf|'])\r
+        isFound = False\r
+        \r
+    for i in listEbc:\r
+        for j in range(len(list1)):\r
+            if i == list1[j][0]:\r
+                isFound = True\r
+                list1[j] = [list1[j][0], list1[j][1] + 'Ebc|']\r
+                break\r
+        if not isFound:\r
+            list1.append([i, 'Ebc|'])\r
+        isFound = False\r
+        \r
+    #Remove DataType.TAB_VALUE_SPLIT\r
+    for i in range(len(list1)):\r
+        if list1[i][1].endswith(DataType.TAB_VALUE_SPLIT):\r
+            list1[i][1] = list1[i][1].rsplit(DataType.TAB_VALUE_SPLIT, 1)[0]\r
+\r
+    #print list1\r
+\r
+def GetComponents(Lines, Key, KeyValues, CommentCharacter):\r
+    #KeyValues [ ['component name', [lib1, lib2, lib3], [bo1, bo2, bo3]], ...]\r
+    Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
+    findBlock = False\r
+    findLibraryClass = False\r
+    findBuildOption = False\r
+    ListItem = None\r
+    LibraryClassItem = []\r
+    BuildOption = []\r
+    \r
+    LineList = Lines.split('\n')\r
+    for Line in LineList:\r
+        Line = CleanString(Line, CommentCharacter)\r
+        if Line == None or Line == '':\r
+            continue\r
+        \r
+        if findBlock == False:\r
+            ListItem = Line\r
+            #find '{' at line tail\r
+            if Line.endswith('{'):\r
+                findBlock = True\r
+                ListItem = CleanString(Line.rsplit('{', 1)[0], CommentCharacter)\r
+\r
+        if findBlock:    \r
+            if Line.find('<LibraryClass>') != -1:\r
+                findLibraryClass = True\r
+                continue\r
+            if Line.find('<BuildOptions>') != -1:\r
+                findBuildOption = True\r
+                continue\r
+            if Line.endswith('}'):\r
+                #find '}' at line tail\r
+                KeyValues.append([ListItem, LibraryClassItem, BuildOption])\r
+                findBlock = False\r
+                findLibraryClass = False\r
+                findBuildOption = False\r
+                LibraryClassItem = []\r
+                BuildOption = []\r
+                continue\r
+\r
+        if findBlock:\r
+            if findLibraryClass:\r
+                LibraryClassItem.append(Line)\r
+            elif findBuildOption:\r
+                BuildOption.append(Line)\r
+        else:\r
+            KeyValues.append([ListItem, [], []])\r
+        \r
+    return True\r
+\r
+def GetLibraryClassesWithModuleType(Lines, Key, KeyValues, CommentCharacter):\r
+    newKey = SplitModuleType(Key)\r
+    Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
+    LineList = Lines.splitlines()\r
+    for Line in LineList:\r
+        Line = CleanString(Line, CommentCharacter)\r
+        if Line != '' and Line[0] != CommentCharacter:\r
+            KeyValues.append([CleanString(Line, CommentCharacter), newKey[1]])\r
+\r
+    return True\r
+\r
+def GetDynamics(Lines, Key, KeyValues, CommentCharacter):\r
+    newKey = SplitModuleType(Key)\r
+    Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
+    LineList = Lines.splitlines()\r
+    for Line in LineList:\r
+        Line = CleanString(Line, CommentCharacter)\r
+        if Line != '' and Line[0] != CommentCharacter:\r
+            KeyValues.append([CleanString(Line, CommentCharacter), newKey[1]])\r
+\r
+    return True\r
+\r
+def SplitModuleType(Key):\r
+    #from DataType import *\r
+    KeyList = Key.split(DataType.TAB_SPLIT)\r
+    rtv = []\r
+    if len(KeyList) == 3:\r
+        rtv.append(KeyList[0] + DataType.TAB_SPLIT + KeyList[1])\r
+        rtv.append(KeyList[2])\r
+        return rtv\r
+    else:\r
+        rtv.append(Key)\r
+        rtv.append(None)\r
+        return rtv\r
+    \r
+def NormPath(path):\r
+    if path != '':\r
+        return os.path.normpath(path)\r
+    else:\r
+        return path\r
+\r
+def CleanString(Line, CommentCharacter = DataType.TAB_COMMENT_SPLIT):\r
+    #remove whitespace\r
+    Line = Line.strip();\r
+    #remove comments\r
+    Line = Line.split(CommentCharacter, 1)[0];\r
+    #replace '\\', '\' with '/'\r
+    Line = Line.replace('\\', '/')\r
+    Line = Line.replace('//', '/')\r
+    #remove ${WORKSPACE}