Ejemplo n.º 1
0
 def SetLogLevel(self, Option):
     if Option.verbose is not None:
         EdkLogger.SetLevel(EdkLogger.VERBOSE)
     elif Option.quiet is not None:
         EdkLogger.SetLevel(EdkLogger.QUIET)
     elif Option.debug is not None:
         EdkLogger.SetLevel(Option.debug + 1)
     else:
         EdkLogger.SetLevel(EdkLogger.INFO)
Ejemplo n.º 2
0
def Main():
    EdkLogger.Initialize()
    Option, Input = GetOptions()

    # Set log level
    if Option.quiet:
        EdkLogger.SetLevel(EdkLogger.QUIET)
    elif Option.verbose:
        EdkLogger.SetLevel(EdkLogger.VERBOSE)
    elif Option.debug is not None:
        EdkLogger.SetLevel(Option.debug + 1)
    else:
        EdkLogger.SetLevel(EdkLogger.INFO)

    try:
        if Option.ModuleType is None or Option.ModuleType not in gType2Phase:
            EdkLogger.error("GenDepex", OPTION_MISSING,
                            "Module type is not specified or supported")

        DxsFile = ''
        if len(Input) > 0 and Option.Expression == "":
            DxsFile = Input[0]
            DxsString = open(DxsFile,
                             'r').read().replace("\n", " ").replace("\r", " ")
            DxsString = gStartClosePattern.sub("\\1", DxsString)
        elif Option.Expression != "":
            if Option.Expression[0] == '"':
                DxsString = Option.Expression[1:-1]
            else:
                DxsString = Option.Expression
        else:
            EdkLogger.error("GenDepex", OPTION_MISSING,
                            "No expression string or file given")

        Dpx = DependencyExpression(DxsString, Option.ModuleType,
                                   Option.Optimize)
        if Option.OutputFile is not None:
            FileChangeFlag = Dpx.Generate(Option.OutputFile)
            if not FileChangeFlag and DxsFile:
                #
                # Touch the output file if its time stamp is older than the original
                # DXS file to avoid re-invoke this tool for the dependency check in build rule.
                #
                if os.stat(DxsFile)[8] > os.stat(Option.OutputFile)[8]:
                    os.utime(Option.OutputFile, None)
        else:
            Dpx.Generate()
    except BaseException as X:
        EdkLogger.quiet("")
        if Option is not None and Option.debug is not None:
            EdkLogger.quiet(traceback.format_exc())
        else:
            EdkLogger.quiet(str(X))
        return 1

    return 0
Ejemplo n.º 3
0
def Main():
    try:
        #
        # Check input parameter
        #
        EdkLogger.Initialize()
        CommandOptions, InputFile = Options()
        if CommandOptions.LogLevel < EdkLogger.DEBUG_9:
            EdkLogger.SetLevel(CommandOptions.LogLevel + 1)
        else:
            EdkLogger.SetLevel(CommandOptions.LogLevel)
        if not os.path.exists(InputFile):
            EdkLogger.error("PatchPcdValue",
                            FILE_NOT_FOUND,
                            ExtraData=InputFile)
            return 1
        if CommandOptions.PcdOffset is None or CommandOptions.PcdValue is None or CommandOptions.PcdTypeName is None:
            EdkLogger.error(
                "PatchPcdValue",
                OPTION_MISSING,
                ExtraData=
                "PcdOffset or PcdValue of PcdTypeName is not specified.")
            return 1
        if CommandOptions.PcdTypeName.upper(
        ) not in TAB_PCD_NUMERIC_TYPES_VOID:
            EdkLogger.error("PatchPcdValue",
                            PARAMETER_INVALID,
                            ExtraData="PCD type %s is not valid." %
                            (CommandOptions.PcdTypeName))
            return 1
        if CommandOptions.PcdTypeName.upper(
        ) == TAB_VOID and CommandOptions.PcdMaxSize is None:
            EdkLogger.error(
                "PatchPcdValue",
                OPTION_MISSING,
                ExtraData="PcdMaxSize is not specified for VOID* type PCD.")
            return 1
        #
        # Patch value into binary image.
        #
        ReturnValue, ErrorInfo = PatchBinaryFile(InputFile,
                                                 CommandOptions.PcdOffset,
                                                 CommandOptions.PcdTypeName,
                                                 CommandOptions.PcdValue,
                                                 CommandOptions.PcdMaxSize)
        if ReturnValue != 0:
            EdkLogger.error("PatchPcdValue", ReturnValue, ExtraData=ErrorInfo)
            return 1
        return 0
    except:
        return 1
Ejemplo n.º 4
0
def Main():
    try:
        EdkLogger.Initialize()
        CommandOptions, InputFile = Options()
        if CommandOptions.LogLevel < EdkLogger.DEBUG_9:
            EdkLogger.SetLevel(CommandOptions.LogLevel + 1)
        else:
            EdkLogger.SetLevel(CommandOptions.LogLevel)
    except FatalError as X:
        return 1

    try:
        if CommandOptions.FileType == "Vfr":
            if CommandOptions.OutputFile is None:
                CommandOptions.OutputFile = os.path.splitext(InputFile)[0] + '.iii'
            TrimPreprocessedVfr(InputFile, CommandOptions.OutputFile)
        elif CommandOptions.FileType == "Asl":
            if CommandOptions.OutputFile is None:
                CommandOptions.OutputFile = os.path.splitext(InputFile)[0] + '.iii'
            TrimAslFile(InputFile, CommandOptions.OutputFile, CommandOptions.IncludePathFile,CommandOptions.AslDeps)
        elif CommandOptions.FileType == "VfrOffsetBin":
            GenerateVfrBinSec(CommandOptions.ModuleName, CommandOptions.DebugDir, CommandOptions.OutputFile)
        elif CommandOptions.FileType == "Asm":
            TrimAsmFile(InputFile, CommandOptions.OutputFile, CommandOptions.IncludePathFile)
        else :
            if CommandOptions.OutputFile is None:
                CommandOptions.OutputFile = os.path.splitext(InputFile)[0] + '.iii'
            TrimPreprocessedFile(InputFile, CommandOptions.OutputFile, CommandOptions.ConvertHex, CommandOptions.TrimLong)
    except FatalError as X:
        import platform
        import traceback
        if CommandOptions is not None and CommandOptions.LogLevel <= EdkLogger.DEBUG_9:
            EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
        return 1
    except:
        import traceback
        import platform
        EdkLogger.error(
                    "\nTrim",
                    CODE_ERROR,
                    "Unknown fatal error when trimming [%s]" % InputFile,
                    ExtraData="\n(Please send email to %s for help, attaching following call stack trace!)\n" % MSG_EDKII_MAIL_ADDR,
                    RaiseError=False
                    )
        EdkLogger.quiet("(Python %s on %s) " % (platform.python_version(), sys.platform) + traceback.format_exc())
        return 1

    return 0
Ejemplo n.º 5
0
def main():
    global Options, Args

    # Initialize log system
    EdkLogger.Initialize()
    Options, Args = MyOptionParser()

    ReturnCode = 0

    if Options.opt_verbose:
        EdkLogger.SetLevel(EdkLogger.VERBOSE)
    elif Options.opt_quiet:
        EdkLogger.SetLevel(EdkLogger.QUIET)
    elif Options.debug_level is not None:
        EdkLogger.SetLevel(Options.debug_level + 1)
    else:
        EdkLogger.SetLevel(EdkLogger.INFO)

    if Options.bin_filename is None:
        EdkLogger.error(
            "BPDG", ATTRIBUTE_NOT_AVAILABLE,
            "Please use the -o option to specify the file name for the VPD binary file"
        )
    if Options.filename is None:
        EdkLogger.error(
            "BPDG", ATTRIBUTE_NOT_AVAILABLE,
            "Please use the -m option to specify the file name for the mapping file"
        )

    Force = False
    if Options.opt_force is not None:
        Force = True

    if (Args[0] is not None):
        StartBpdg(Args[0], Options.filename, Options.bin_filename, Force)
    else:
        EdkLogger.error(
            "BPDG", ATTRIBUTE_NOT_AVAILABLE,
            "Please specify the file which contain the VPD pcd info.", None)

    return ReturnCode
Ejemplo n.º 6
0
            FileObj = DataClass.FileClass(-1, BaseName, Ext, DirName,
                                          FullName, model, ModifiedTime,
                                          GetFunctionList(),
                                          GetIdentifierList(), [])
            FileObjList.append(FileObj)
            collector.CleanFileProfileBuffer()

    if len(ParseErrorFileList) > 0:
        EdkLogger.info("Found unrecoverable error during parsing:\n\t%s\n" %
                       "\n\t".join(ParseErrorFileList))

    Db = EotGlobalData.gDb
    for file in FileObjList:
        Db.InsertOneFile(file)

    Db.UpdateIdentifierBelongsToFunction()


##
#
# This acts like the main() function for the script, unless it is 'import'ed into another
# script.
#
if __name__ == '__main__':

    EdkLogger.Initialize()
    EdkLogger.SetLevel(EdkLogger.QUIET)
    CollectSourceCodeDataIntoDB(sys.argv[1])

    print('Done!')
Ejemplo n.º 7
0
                    LangName = LangNameItem[0]
                    OtherLangItem = self.OrderedStringList[LangName][Index]
                    OtherLangItem.Token = RefToken + UnRefToken
                    self.OrderedStringListByToken[LangName][
                        OtherLangItem.Token] = OtherLangItem
                UnRefToken = UnRefToken + 1

    #
    # Show the instance itself
    #
    def ShowMe(self):
        print(self.LanguageDef)
        #print self.OrderedStringList
        for Item in self.OrderedStringList:
            print(Item)
            for Member in self.OrderedStringList[Item]:
                print(str(Member))


# This acts like the main() function for the script, unless it is 'import'ed into another
# script.
if __name__ == '__main__':
    EdkLogger.Initialize()
    EdkLogger.SetLevel(EdkLogger.DEBUG_0)
    a = UniFileClassObject([
        PathClass("C:\\Edk\\Strings.uni"),
        PathClass("C:\\Edk\\Strings2.uni")
    ])
    a.ReToken()
    a.ShowMe()
Ejemplo n.º 8
0
    def run(self):
        try:
            taskname = "Init"
            with self.file_lock:
                try:
                    self.data_pipe = MemoryDataPipe()
                    self.data_pipe.load(self.data_pipe_file_path)
                except:
                    self.feedback_q.put(taskname + ":" + "load data pipe %s failed." % self.data_pipe_file_path)
            EdkLogger.LogClientInitialize(self.log_q)
            loglevel = self.data_pipe.Get("LogLevel")
            if not loglevel:
                loglevel = EdkLogger.INFO
            EdkLogger.SetLevel(loglevel)
            target = self.data_pipe.Get("P_Info").get("Target")
            toolchain = self.data_pipe.Get("P_Info").get("ToolChain")
            archlist = self.data_pipe.Get("P_Info").get("ArchList")

            active_p = self.data_pipe.Get("P_Info").get("ActivePlatform")
            workspacedir = self.data_pipe.Get("P_Info").get("WorkspaceDir")
            PackagesPath = os.getenv("PACKAGES_PATH")
            mws.setWs(workspacedir, PackagesPath)
            self.Wa = WorkSpaceInfo(
                workspacedir,active_p,target,toolchain,archlist
                )
            self.Wa._SrcTimeStamp = self.data_pipe.Get("Workspace_timestamp")
            GlobalData.gGlobalDefines = self.data_pipe.Get("G_defines")
            GlobalData.gCommandLineDefines = self.data_pipe.Get("CL_defines")
            GlobalData.gCommandMaxLength = self.data_pipe.Get('gCommandMaxLength')
            os.environ._data = self.data_pipe.Get("Env_Var")
            GlobalData.gWorkspace = workspacedir
            GlobalData.gDisableIncludePathCheck = False
            GlobalData.gFdfParser = self.data_pipe.Get("FdfParser")
            GlobalData.gDatabasePath = self.data_pipe.Get("DatabasePath")

            GlobalData.gUseHashCache = self.data_pipe.Get("UseHashCache")
            GlobalData.gBinCacheSource = self.data_pipe.Get("BinCacheSource")
            GlobalData.gBinCacheDest = self.data_pipe.Get("BinCacheDest")
            GlobalData.gPlatformHashFile = self.data_pipe.Get("PlatformHashFile")
            GlobalData.gModulePreMakeCacheStatus = dict()
            GlobalData.gModuleMakeCacheStatus = dict()
            GlobalData.gHashChainStatus = dict()
            GlobalData.gCMakeHashFile = dict()
            GlobalData.gModuleHashFile = dict()
            GlobalData.gFileHashDict = dict()
            GlobalData.gEnableGenfdsMultiThread = self.data_pipe.Get("EnableGenfdsMultiThread")
            GlobalData.gPlatformFinalPcds = self.data_pipe.Get("gPlatformFinalPcds")
            GlobalData.file_lock = self.file_lock
            CommandTarget = self.data_pipe.Get("CommandTarget")
            pcd_from_build_option = []
            for pcd_tuple in self.data_pipe.Get("BuildOptPcd"):
                pcd_id = ".".join((pcd_tuple[0],pcd_tuple[1]))
                if pcd_tuple[2].strip():
                    pcd_id = ".".join((pcd_id,pcd_tuple[2]))
                pcd_from_build_option.append("=".join((pcd_id,pcd_tuple[3])))
            GlobalData.BuildOptionPcd = pcd_from_build_option
            module_count = 0
            FfsCmd = self.data_pipe.Get("FfsCommand")
            if FfsCmd is None:
                FfsCmd = {}
            GlobalData.FfsCmd = FfsCmd
            PlatformMetaFile = self.GetPlatformMetaFile(self.data_pipe.Get("P_Info").get("ActivePlatform"),
                                             self.data_pipe.Get("P_Info").get("WorkspaceDir"))
            while True:
                if self.error_event.is_set():
                    break
                module_count += 1
                try:
                    module_file,module_root,module_path,module_basename,module_originalpath,module_arch,IsLib = self.module_queue.get_nowait()
                except Empty:
                    EdkLogger.debug(EdkLogger.DEBUG_9, "Worker %s: %s" % (os.getpid(), "Fake Empty."))
                    time.sleep(0.01)
                    continue
                if module_file is None:
                    EdkLogger.debug(EdkLogger.DEBUG_9, "Worker %s: %s" % (os.getpid(), "Worker get the last item in the queue."))
                    self.feedback_q.put("QueueEmpty")
                    time.sleep(0.01)
                    continue

                modulefullpath = os.path.join(module_root,module_file)
                taskname = " : ".join((modulefullpath,module_arch))
                module_metafile = PathClass(module_file,module_root)
                if module_path:
                    module_metafile.Path = module_path
                if module_basename:
                    module_metafile.BaseName = module_basename
                if module_originalpath:
                    module_metafile.OriginalPath = PathClass(module_originalpath,module_root)
                arch = module_arch
                target = self.data_pipe.Get("P_Info").get("Target")
                toolchain = self.data_pipe.Get("P_Info").get("ToolChain")
                Ma = ModuleAutoGen(self.Wa,module_metafile,target,toolchain,arch,PlatformMetaFile,self.data_pipe)
                Ma.IsLibrary = IsLib
                # SourceFileList calling sequence impact the makefile string sequence.
                # Create cached SourceFileList here to unify its calling sequence for both
                # CanSkipbyPreMakeCache and CreateCodeFile/CreateMakeFile.
                RetVal = Ma.SourceFileList
                if GlobalData.gUseHashCache and not GlobalData.gBinCacheDest and CommandTarget in [None, "", "all"]:
                    try:
                        CacheResult = Ma.CanSkipbyPreMakeCache()
                    except:
                        CacheResult = False
                        self.feedback_q.put(taskname)

                    if CacheResult:
                        self.cache_q.put((Ma.MetaFile.Path, Ma.Arch, "PreMakeCache", True))
                        continue
                    else:
                        self.cache_q.put((Ma.MetaFile.Path, Ma.Arch, "PreMakeCache", False))

                Ma.CreateCodeFile(False)
                Ma.CreateMakeFile(False,GenFfsList=FfsCmd.get((Ma.MetaFile.Path, Ma.Arch),[]))
                Ma.CreateAsBuiltInf()
                if GlobalData.gBinCacheSource and CommandTarget in [None, "", "all"]:
                    try:
                        CacheResult = Ma.CanSkipbyMakeCache()
                    except:
                        CacheResult = False
                        self.feedback_q.put(taskname)

                    if CacheResult:
                        self.cache_q.put((Ma.MetaFile.Path, Ma.Arch, "MakeCache", True))
                        continue
                    else:
                        self.cache_q.put((Ma.MetaFile.Path, Ma.Arch, "MakeCache", False))

        except Exception as e:
            EdkLogger.debug(EdkLogger.DEBUG_9, "Worker %s: %s" % (os.getpid(), str(e)))
            self.feedback_q.put(taskname)
        finally:
            EdkLogger.debug(EdkLogger.DEBUG_9, "Worker %s: %s" % (os.getpid(), "Done"))
            self.feedback_q.put("Done")
            self.cache_q.put("CacheDone")
Ejemplo n.º 9
0
def GenFdsApi(FdsCommandDict, WorkSpaceDataBase=None):
    global Workspace
    Workspace = ""
    ArchList = None
    ReturnCode = 0
    resetFdsGlobalVariable()

    try:
        if FdsCommandDict.get("verbose"):
            EdkLogger.SetLevel(EdkLogger.VERBOSE)
            GenFdsGlobalVariable.VerboseMode = True

        if FdsCommandDict.get("FixedAddress"):
            GenFdsGlobalVariable.FixedLoadAddress = True

        if FdsCommandDict.get("quiet"):
            EdkLogger.SetLevel(EdkLogger.QUIET)
        if FdsCommandDict.get("debug"):
            EdkLogger.SetLevel(FdsCommandDict.get("debug") + 1)
            GenFdsGlobalVariable.DebugLevel = FdsCommandDict.get("debug")
        else:
            EdkLogger.SetLevel(EdkLogger.INFO)

        if not FdsCommandDict.get("Workspace", os.environ.get('WORKSPACE')):
            EdkLogger.error(
                "GenFds",
                OPTION_MISSING,
                "WORKSPACE not defined",
                ExtraData=
                "Please use '-w' switch to pass it or set the WORKSPACE environment variable."
            )
        elif not os.path.exists(
                FdsCommandDict.get("Workspace", os.environ.get('WORKSPACE'))):
            EdkLogger.error(
                "GenFds",
                PARAMETER_INVALID,
                "WORKSPACE is invalid",
                ExtraData=
                "Please use '-w' switch to pass it or set the WORKSPACE environment variable."
            )
        else:
            Workspace = os.path.normcase(
                FdsCommandDict.get("Workspace", os.environ.get('WORKSPACE')))
            GenFdsGlobalVariable.WorkSpaceDir = Workspace
            if FdsCommandDict.get("debug"):
                GenFdsGlobalVariable.VerboseLogger("Using Workspace:" +
                                                   Workspace)
            if FdsCommandDict.get("GenfdsMultiThread"):
                GenFdsGlobalVariable.EnableGenfdsMultiThread = True
            else:
                GenFdsGlobalVariable.EnableGenfdsMultiThread = False
        os.chdir(GenFdsGlobalVariable.WorkSpaceDir)

        # set multiple workspace
        PackagesPath = os.getenv("PACKAGES_PATH")
        mws.setWs(GenFdsGlobalVariable.WorkSpaceDir, PackagesPath)

        if FdsCommandDict.get("fdf_file"):
            FdfFilename = FdsCommandDict.get("fdf_file")[0].Path
            FdfFilename = GenFdsGlobalVariable.ReplaceWorkspaceMacro(
                FdfFilename)

            if FdfFilename[0:2] == '..':
                FdfFilename = os.path.abspath(FdfFilename)
            if not os.path.isabs(FdfFilename):
                FdfFilename = mws.join(GenFdsGlobalVariable.WorkSpaceDir,
                                       FdfFilename)
            if not os.path.exists(FdfFilename):
                EdkLogger.error("GenFds",
                                FILE_NOT_FOUND,
                                ExtraData=FdfFilename)

            GenFdsGlobalVariable.FdfFile = FdfFilename
            GenFdsGlobalVariable.FdfFileTimeStamp = os.path.getmtime(
                FdfFilename)
        else:
            EdkLogger.error("GenFds", OPTION_MISSING, "Missing FDF filename")

        if FdsCommandDict.get("build_target"):
            GenFdsGlobalVariable.TargetName = FdsCommandDict.get(
                "build_target")

        if FdsCommandDict.get("toolchain_tag"):
            GenFdsGlobalVariable.ToolChainTag = FdsCommandDict.get(
                "toolchain_tag")

        if FdsCommandDict.get("active_platform"):
            ActivePlatform = FdsCommandDict.get("active_platform")
            ActivePlatform = GenFdsGlobalVariable.ReplaceWorkspaceMacro(
                ActivePlatform)

            if ActivePlatform[0:2] == '..':
                ActivePlatform = os.path.abspath(ActivePlatform)

            if not os.path.isabs(ActivePlatform):
                ActivePlatform = mws.join(GenFdsGlobalVariable.WorkSpaceDir,
                                          ActivePlatform)

            if not os.path.exists(ActivePlatform):
                EdkLogger.error("GenFds", FILE_NOT_FOUND,
                                "ActivePlatform doesn't exist!")
        else:
            EdkLogger.error("GenFds", OPTION_MISSING,
                            "Missing active platform")

        GenFdsGlobalVariable.ActivePlatform = PathClass(
            NormPath(ActivePlatform))

        if FdsCommandDict.get("conf_directory"):
            # Get alternate Conf location, if it is absolute, then just use the absolute directory name
            ConfDirectoryPath = os.path.normpath(
                FdsCommandDict.get("conf_directory"))
            if ConfDirectoryPath.startswith('"'):
                ConfDirectoryPath = ConfDirectoryPath[1:]
            if ConfDirectoryPath.endswith('"'):
                ConfDirectoryPath = ConfDirectoryPath[:-1]
            if not os.path.isabs(ConfDirectoryPath):
                # Since alternate directory name is not absolute, the alternate directory is located within the WORKSPACE
                # This also handles someone specifying the Conf directory in the workspace. Using --conf=Conf
                ConfDirectoryPath = os.path.join(
                    GenFdsGlobalVariable.WorkSpaceDir, ConfDirectoryPath)
        else:
            if "CONF_PATH" in os.environ:
                ConfDirectoryPath = os.path.normcase(os.environ["CONF_PATH"])
            else:
                # Get standard WORKSPACE/Conf, use the absolute path to the WORKSPACE/Conf
                ConfDirectoryPath = mws.join(GenFdsGlobalVariable.WorkSpaceDir,
                                             'Conf')
        GenFdsGlobalVariable.ConfDir = ConfDirectoryPath
        if not GlobalData.gConfDirectory:
            GlobalData.gConfDirectory = GenFdsGlobalVariable.ConfDir
        BuildConfigurationFile = os.path.normpath(
            os.path.join(ConfDirectoryPath, gDefaultTargetTxtFile))
        if os.path.isfile(BuildConfigurationFile) == True:
            # if no build target given in command line, get it from target.txt
            TargetObj = TargetTxtDict()
            TargetTxt = TargetObj.Target
            if not GenFdsGlobalVariable.TargetName:
                BuildTargetList = TargetTxt.TargetTxtDictionary[
                    TAB_TAT_DEFINES_TARGET]
                if len(BuildTargetList) != 1:
                    EdkLogger.error(
                        "GenFds",
                        OPTION_VALUE_INVALID,
                        ExtraData="Only allows one instance for Target.")
                GenFdsGlobalVariable.TargetName = BuildTargetList[0]

            # if no tool chain given in command line, get it from target.txt
            if not GenFdsGlobalVariable.ToolChainTag:
                ToolChainList = TargetTxt.TargetTxtDictionary[
                    TAB_TAT_DEFINES_TOOL_CHAIN_TAG]
                if ToolChainList is None or len(ToolChainList) == 0:
                    EdkLogger.error(
                        "GenFds",
                        RESOURCE_NOT_AVAILABLE,
                        ExtraData="No toolchain given. Don't know how to build."
                    )
                if len(ToolChainList) != 1:
                    EdkLogger.error(
                        "GenFds",
                        OPTION_VALUE_INVALID,
                        ExtraData="Only allows one instance for ToolChain.")
                GenFdsGlobalVariable.ToolChainTag = ToolChainList[0]
        else:
            EdkLogger.error("GenFds",
                            FILE_NOT_FOUND,
                            ExtraData=BuildConfigurationFile)

        #Set global flag for build mode
        GlobalData.gIgnoreSource = FdsCommandDict.get("IgnoreSources")

        if FdsCommandDict.get("macro"):
            for Pair in FdsCommandDict.get("macro"):
                if Pair.startswith('"'):
                    Pair = Pair[1:]
                if Pair.endswith('"'):
                    Pair = Pair[:-1]
                List = Pair.split('=')
                if len(List) == 2:
                    if not List[1].strip():
                        EdkLogger.error(
                            "GenFds",
                            OPTION_VALUE_INVALID,
                            ExtraData="No Value given for Macro %s" % List[0])
                    if List[0].strip() in ["WORKSPACE", "TARGET", "TOOLCHAIN"]:
                        GlobalData.gGlobalDefines[
                            List[0].strip()] = List[1].strip()
                    else:
                        GlobalData.gCommandLineDefines[
                            List[0].strip()] = List[1].strip()
                else:
                    GlobalData.gCommandLineDefines[List[0].strip()] = "TRUE"
        os.environ["WORKSPACE"] = Workspace

        # Use the -t and -b option as gGlobalDefines's TOOLCHAIN and TARGET if they are not defined
        if "TARGET" not in GlobalData.gGlobalDefines:
            GlobalData.gGlobalDefines[
                "TARGET"] = GenFdsGlobalVariable.TargetName
        if "TOOLCHAIN" not in GlobalData.gGlobalDefines:
            GlobalData.gGlobalDefines[
                "TOOLCHAIN"] = GenFdsGlobalVariable.ToolChainTag
        if "TOOL_CHAIN_TAG" not in GlobalData.gGlobalDefines:
            GlobalData.gGlobalDefines[
                'TOOL_CHAIN_TAG'] = GenFdsGlobalVariable.ToolChainTag
        """call Workspace build create database"""
        GlobalData.gDatabasePath = os.path.normpath(
            os.path.join(ConfDirectoryPath, GlobalData.gDatabasePath))

        if WorkSpaceDataBase:
            BuildWorkSpace = WorkSpaceDataBase
        else:
            BuildWorkSpace = WorkspaceDatabase()
        #
        # Get files real name in workspace dir
        #
        GlobalData.gAllFiles = DirCache(Workspace)
        GlobalData.gWorkspace = Workspace

        if FdsCommandDict.get("build_architecture_list"):
            ArchList = FdsCommandDict.get("build_architecture_list").split(',')
        else:
            ArchList = BuildWorkSpace.BuildObject[
                GenFdsGlobalVariable.ActivePlatform, TAB_COMMON,
                FdsCommandDict.get("build_target"),
                FdsCommandDict.get("toolchain_tag")].SupArchList

        TargetArchList = set(BuildWorkSpace.BuildObject[
            GenFdsGlobalVariable.ActivePlatform, TAB_COMMON,
            FdsCommandDict.get("build_target"),
            FdsCommandDict.get("toolchain_tag")].SupArchList) & set(ArchList)
        if len(TargetArchList) == 0:
            EdkLogger.error(
                "GenFds", GENFDS_ERROR,
                "Target ARCH %s not in platform supported ARCH %s" %
                (str(ArchList),
                 str(BuildWorkSpace.BuildObject[
                     GenFdsGlobalVariable.ActivePlatform,
                     TAB_COMMON].SupArchList)))

        for Arch in ArchList:
            GenFdsGlobalVariable.OutputDirFromDscDict[Arch] = NormPath(
                BuildWorkSpace.BuildObject[
                    GenFdsGlobalVariable.ActivePlatform, Arch,
                    FdsCommandDict.get("build_target"),
                    FdsCommandDict.get("toolchain_tag")].OutputDirectory)

        # assign platform name based on last entry in ArchList
        GenFdsGlobalVariable.PlatformName = BuildWorkSpace.BuildObject[
            GenFdsGlobalVariable.ActivePlatform, ArchList[-1],
            FdsCommandDict.get("build_target"),
            FdsCommandDict.get("toolchain_tag")].PlatformName

        if FdsCommandDict.get("platform_build_directory"):
            OutputDirFromCommandLine = GenFdsGlobalVariable.ReplaceWorkspaceMacro(
                FdsCommandDict.get("platform_build_directory"))
            if not os.path.isabs(OutputDirFromCommandLine):
                OutputDirFromCommandLine = os.path.join(
                    GenFdsGlobalVariable.WorkSpaceDir,
                    OutputDirFromCommandLine)
            for Arch in ArchList:
                GenFdsGlobalVariable.OutputDirDict[
                    Arch] = OutputDirFromCommandLine
        else:
            for Arch in ArchList:
                GenFdsGlobalVariable.OutputDirDict[Arch] = os.path.join(
                    GenFdsGlobalVariable.OutputDirFromDscDict[Arch],
                    GenFdsGlobalVariable.TargetName + '_' +
                    GenFdsGlobalVariable.ToolChainTag)

        for Key in GenFdsGlobalVariable.OutputDirDict:
            OutputDir = GenFdsGlobalVariable.OutputDirDict[Key]
            if OutputDir[0:2] == '..':
                OutputDir = os.path.abspath(OutputDir)

            if OutputDir[1] != ':':
                OutputDir = os.path.join(GenFdsGlobalVariable.WorkSpaceDir,
                                         OutputDir)

            if not os.path.exists(OutputDir):
                EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=OutputDir)
            GenFdsGlobalVariable.OutputDirDict[Key] = OutputDir
        """ Parse Fdf file, has to place after build Workspace as FDF may contain macros from DSC file """
        if WorkSpaceDataBase:
            FdfParserObj = GlobalData.gFdfParser
        else:
            FdfParserObj = FdfParser(FdfFilename)
            FdfParserObj.ParseFile()

        if FdfParserObj.CycleReferenceCheck():
            EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED,
                            "Cycle Reference Detected in FDF file")

        if FdsCommandDict.get("fd"):
            if FdsCommandDict.get(
                    "fd")[0].upper() in FdfParserObj.Profile.FdDict:
                GenFds.OnlyGenerateThisFd = FdsCommandDict.get("fd")[0]
            else:
                EdkLogger.error(
                    "GenFds", OPTION_VALUE_INVALID,
                    "No such an FD in FDF file: %s" %
                    FdsCommandDict.get("fd")[0])

        if FdsCommandDict.get("fv"):
            if FdsCommandDict.get(
                    "fv")[0].upper() in FdfParserObj.Profile.FvDict:
                GenFds.OnlyGenerateThisFv = FdsCommandDict.get("fv")[0]
            else:
                EdkLogger.error(
                    "GenFds", OPTION_VALUE_INVALID,
                    "No such an FV in FDF file: %s" %
                    FdsCommandDict.get("fv")[0])

        if FdsCommandDict.get("cap"):
            if FdsCommandDict.get(
                    "cap")[0].upper() in FdfParserObj.Profile.CapsuleDict:
                GenFds.OnlyGenerateThisCap = FdsCommandDict.get("cap")[0]
            else:
                EdkLogger.error(
                    "GenFds", OPTION_VALUE_INVALID,
                    "No such a Capsule in FDF file: %s" %
                    FdsCommandDict.get("cap")[0])

        GenFdsGlobalVariable.WorkSpace = BuildWorkSpace
        if ArchList:
            GenFdsGlobalVariable.ArchList = ArchList

        # Dsc Build Data will handle Pcd Settings from CommandLine.
        """Modify images from build output if the feature of loading driver at fixed address is on."""
        if GenFdsGlobalVariable.FixedLoadAddress:
            GenFds.PreprocessImage(BuildWorkSpace,
                                   GenFdsGlobalVariable.ActivePlatform)

        # Record the FV Region info that may specific in the FD
        if FdfParserObj.Profile.FvDict and FdfParserObj.Profile.FdDict:
            for FvObj in FdfParserObj.Profile.FvDict.values():
                for FdObj in FdfParserObj.Profile.FdDict.values():
                    for RegionObj in FdObj.RegionList:
                        if RegionObj.RegionType != BINARY_FILE_TYPE_FV:
                            continue
                        for RegionData in RegionObj.RegionDataList:
                            if FvObj.UiFvName.upper() == RegionData.upper():
                                if not FvObj.BaseAddress:
                                    FvObj.BaseAddress = '0x%x' % (
                                        int(FdObj.BaseAddress, 0) +
                                        RegionObj.Offset)
                                if FvObj.FvRegionInFD:
                                    if FvObj.FvRegionInFD != RegionObj.Size:
                                        EdkLogger.error(
                                            "GenFds", FORMAT_INVALID,
                                            "The FV %s's region is specified in multiple FD with different value."
                                            % FvObj.UiFvName)
                                else:
                                    FvObj.FvRegionInFD = RegionObj.Size
                                    RegionObj.BlockInfoOfRegion(
                                        FdObj.BlockSizeList, FvObj)
        """Call GenFds"""
        GenFds.GenFd('', FdfParserObj, BuildWorkSpace, ArchList)
        """Generate GUID cross reference file"""
        GenFds.GenerateGuidXRefFile(BuildWorkSpace, ArchList, FdfParserObj)
        """Display FV space info."""
        GenFds.DisplayFvSpaceInfo(FdfParserObj)

    except Warning as X:
        EdkLogger.error(X.ToolName,
                        FORMAT_INVALID,
                        File=X.FileName,
                        Line=X.LineNumber,
                        ExtraData=X.Message,
                        RaiseError=False)
        ReturnCode = FORMAT_INVALID
    except FatalError as X:
        if FdsCommandDict.get("debug") is not None:
            import traceback
            EdkLogger.quiet(traceback.format_exc())
        ReturnCode = X.args[0]
    except:
        import traceback
        EdkLogger.error(
            "\nPython",
            CODE_ERROR,
            "Tools code failure",
            ExtraData=
            "Please send email to %s for help, attaching following call stack trace!\n"
            % MSG_EDKII_MAIL_ADDR,
            RaiseError=False)
        EdkLogger.quiet(traceback.format_exc())
        ReturnCode = CODE_ERROR
    finally:
        ClearDuplicatedInf()
    return ReturnCode