Sync BaseTool trunk (version r2649) into EDKII BaseTools.

Signed-off-by: Gao, Liming <liming.gao@intel.com>


git-svn-id: https://svn.code.sf.net/p/edk2/code/trunk/edk2@15188 6f19259b-4bc3-4df7-8a09-765794883524
This commit is contained in:
Gao, Liming
2014-01-27 05:23:15 +00:00
committed by lgao4
parent 7771be9fd0
commit f51461c829
96 changed files with 71959 additions and 71964 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,154 +1,154 @@
## @file
# Standardized Error Hanlding infrastructures.
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
# 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.
#
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_NOT_FOUND = 14
FILE_TYPE_MISMATCH = 15
FILE_CASE_MISMATCH = 16
FILE_DUPLICATED = 17
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
COMMAND_FAILURE = 0x7000
PERMISSION_FAILURE = 0x8000
CODE_ERROR = 0xC0DE
AUTOGEN_ERROR = 0xF000
PARSER_ERROR = 0xF001
BUILD_ERROR = 0xF002
GENFDS_ERROR = 0xF003
ECC_ERROR = 0xF004
EOT_ERROR = 0xF005
DDC_ERROR = 0xF009
WARNING_AS_ERROR = 0xF006
MIGRATION_ERROR = 0xF010
ABORT_ERROR = 0xFFFE
UNKNOWN_ERROR = 0xFFFF
## Error message of each error code
gErrorMessage = {
FILE_NOT_FOUND : "File/directory not found in workspace",
FILE_OPEN_FAILURE : "File open failure",
FILE_WRITE_FAILURE : "File write failure",
FILE_PARSE_FAILURE : "File parse failure",
FILE_READ_FAILURE : "File read failure",
FILE_CREATE_FAILURE : "File create failure",
FILE_CHECKSUM_FAILURE : "Invalid checksum of file",
FILE_COMPRESS_FAILURE : "File compress failure",
FILE_DECOMPRESS_FAILURE : "File decompress failure",
FILE_MOVE_FAILURE : "File move failure",
FILE_DELETE_FAILURE : "File delete failure",
FILE_COPY_FAILURE : "File copy failure",
FILE_POSITIONING_FAILURE: "Failed to seeking position",
FILE_ALREADY_EXIST : "File or directory already exists",
FILE_TYPE_MISMATCH : "Incorrect file type",
FILE_CASE_MISMATCH : "File name case mismatch",
FILE_DUPLICATED : "Duplicated file found",
FILE_UNKNOWN_ERROR : "Unknown error encountered on file",
OPTION_UNKNOWN : "Unknown option",
OPTION_MISSING : "Missing option",
OPTION_CONFLICT : "Conflict options",
OPTION_VALUE_INVALID : "Invalid value of option",
OPTION_DEPRECATED : "Deprecated option",
OPTION_NOT_SUPPORTED : "Unsupported option",
OPTION_UNKNOWN_ERROR : "Unknown error when processing options",
PARAMETER_INVALID : "Invalid parameter",
PARAMETER_MISSING : "Missing parameter",
PARAMETER_UNKNOWN_ERROR : "Unknown error in parameters",
FORMAT_INVALID : "Invalid syntax/format",
FORMAT_NOT_SUPPORTED : "Not supported syntax/format",
FORMAT_UNKNOWN : "Unknown format",
FORMAT_UNKNOWN_ERROR : "Unknown error in syntax/format ",
RESOURCE_NOT_AVAILABLE : "Not available",
RESOURCE_ALLOCATE_FAILURE : "Allocate failure",
RESOURCE_FULL : "Full",
RESOURCE_OVERFLOW : "Overflow",
RESOURCE_UNDERRUN : "Underrun",
RESOURCE_UNKNOWN_ERROR : "Unknown error",
ATTRIBUTE_NOT_AVAILABLE : "Not available",
ATTRIBUTE_GET_FAILURE : "Failed to retrieve",
ATTRIBUTE_SET_FAILURE : "Failed to set",
ATTRIBUTE_UPDATE_FAILURE: "Failed to update",
ATTRIBUTE_ACCESS_DENIED : "Access denied",
ATTRIBUTE_UNKNOWN_ERROR : "Unknown error when accessing",
COMMAND_FAILURE : "Failed to execute command",
IO_NOT_READY : "Not ready",
IO_BUSY : "Busy",
IO_TIMEOUT : "Timeout",
IO_UNKNOWN_ERROR : "Unknown error in IO operation",
UNKNOWN_ERROR : "Unknown error",
}
## Exception indicating a fatal error
class FatalError(Exception):
pass
if __name__ == "__main__":
pass
## @file
# Standardized Error Hanlding infrastructures.
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
# 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.
#
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_NOT_FOUND = 14
FILE_TYPE_MISMATCH = 15
FILE_CASE_MISMATCH = 16
FILE_DUPLICATED = 17
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
COMMAND_FAILURE = 0x7000
PERMISSION_FAILURE = 0x8000
CODE_ERROR = 0xC0DE
AUTOGEN_ERROR = 0xF000
PARSER_ERROR = 0xF001
BUILD_ERROR = 0xF002
GENFDS_ERROR = 0xF003
ECC_ERROR = 0xF004
EOT_ERROR = 0xF005
DDC_ERROR = 0xF009
WARNING_AS_ERROR = 0xF006
MIGRATION_ERROR = 0xF010
ABORT_ERROR = 0xFFFE
UNKNOWN_ERROR = 0xFFFF
## Error message of each error code
gErrorMessage = {
FILE_NOT_FOUND : "File/directory not found in workspace",
FILE_OPEN_FAILURE : "File open failure",
FILE_WRITE_FAILURE : "File write failure",
FILE_PARSE_FAILURE : "File parse failure",
FILE_READ_FAILURE : "File read failure",
FILE_CREATE_FAILURE : "File create failure",
FILE_CHECKSUM_FAILURE : "Invalid checksum of file",
FILE_COMPRESS_FAILURE : "File compress failure",
FILE_DECOMPRESS_FAILURE : "File decompress failure",
FILE_MOVE_FAILURE : "File move failure",
FILE_DELETE_FAILURE : "File delete failure",
FILE_COPY_FAILURE : "File copy failure",
FILE_POSITIONING_FAILURE: "Failed to seeking position",
FILE_ALREADY_EXIST : "File or directory already exists",
FILE_TYPE_MISMATCH : "Incorrect file type",
FILE_CASE_MISMATCH : "File name case mismatch",
FILE_DUPLICATED : "Duplicated file found",
FILE_UNKNOWN_ERROR : "Unknown error encountered on file",
OPTION_UNKNOWN : "Unknown option",
OPTION_MISSING : "Missing option",
OPTION_CONFLICT : "Conflict options",
OPTION_VALUE_INVALID : "Invalid value of option",
OPTION_DEPRECATED : "Deprecated option",
OPTION_NOT_SUPPORTED : "Unsupported option",
OPTION_UNKNOWN_ERROR : "Unknown error when processing options",
PARAMETER_INVALID : "Invalid parameter",
PARAMETER_MISSING : "Missing parameter",
PARAMETER_UNKNOWN_ERROR : "Unknown error in parameters",
FORMAT_INVALID : "Invalid syntax/format",
FORMAT_NOT_SUPPORTED : "Not supported syntax/format",
FORMAT_UNKNOWN : "Unknown format",
FORMAT_UNKNOWN_ERROR : "Unknown error in syntax/format ",
RESOURCE_NOT_AVAILABLE : "Not available",
RESOURCE_ALLOCATE_FAILURE : "Allocate failure",
RESOURCE_FULL : "Full",
RESOURCE_OVERFLOW : "Overflow",
RESOURCE_UNDERRUN : "Underrun",
RESOURCE_UNKNOWN_ERROR : "Unknown error",
ATTRIBUTE_NOT_AVAILABLE : "Not available",
ATTRIBUTE_GET_FAILURE : "Failed to retrieve",
ATTRIBUTE_SET_FAILURE : "Failed to set",
ATTRIBUTE_UPDATE_FAILURE: "Failed to update",
ATTRIBUTE_ACCESS_DENIED : "Access denied",
ATTRIBUTE_UNKNOWN_ERROR : "Unknown error when accessing",
COMMAND_FAILURE : "Failed to execute command",
IO_NOT_READY : "Not ready",
IO_BUSY : "Busy",
IO_TIMEOUT : "Timeout",
IO_UNKNOWN_ERROR : "Unknown error in IO operation",
UNKNOWN_ERROR : "Unknown error",
}
## Exception indicating a fatal error
class FatalError(Exception):
pass
if __name__ == "__main__":
pass

View File

@@ -13,4 +13,4 @@
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
gBUILD_VERSION = "Build 2640"
gBUILD_VERSION = "Build 2649"

View File

@@ -1,269 +1,269 @@
## @file
# This file implements the log mechanism for Python tools.
#
# Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
# 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.
#
## Import modules
import sys, os, logging
import traceback
from BuildToolError import *
## Log level constants
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 = 20
WARN = 30
QUIET = 40
ERROR = 50
IsRaiseError = True
# Tool name
_ToolName = os.path.basename(sys.argv[0])
# For validation purpose
_LogLevels = [DEBUG_0, DEBUG_1, DEBUG_2, DEBUG_3, DEBUG_4, DEBUG_5, DEBUG_6, DEBUG_7, DEBUG_8, DEBUG_9, VERBOSE, WARN, INFO, ERROR, QUIET]
# For DEBUG level (All DEBUG_0~9 are applicable)
_DebugLogger = logging.getLogger("tool_debug")
_DebugFormatter = logging.Formatter("[%(asctime)s.%(msecs)d]: %(message)s", datefmt="%H:%M:%S")
# For VERBOSE, INFO, WARN level
_InfoLogger = logging.getLogger("tool_info")
_InfoFormatter = logging.Formatter("%(message)s")
# For ERROR level
_ErrorLogger = logging.getLogger("tool_error")
_ErrorFormatter = logging.Formatter("%(message)s")
# String templates for ERROR/WARN/DEBUG log message
_ErrorMessageTemplate = '\n\n%(tool)s...\n%(file)s(%(line)s): error %(errorcode)04X: %(msg)s\n\t%(extra)s'
_ErrorMessageTemplateWithoutFile = '\n\n%(tool)s...\n : error %(errorcode)04X: %(msg)s\n\t%(extra)s'
_WarningMessageTemplate = '%(tool)s...\n%(file)s(%(line)s): warning: %(msg)s'
_WarningMessageTemplateWithoutFile = '%(tool)s: : warning: %(msg)s'
_DebugMessageTemplate = '%(file)s(%(line)s): debug: \n %(msg)s'
#
# Flag used to take WARN as ERROR.
# By default, only ERROR message will break the tools execution.
#
_WarningAsError = False
## Log debug message
#
# @param Level DEBUG level (DEBUG0~9)
# @param Message Debug information
# @param ExtraData More information associated with "Message"
#
def debug(Level, Message, ExtraData=None):
if _DebugLogger.level > Level:
return
if Level > DEBUG_9:
return
# Find out the caller method information
CallerStack = traceback.extract_stack()[-2]
TemplateDict = {
"file" : CallerStack[0],
"line" : CallerStack[1],
"msg" : Message,
}
if ExtraData != None:
LogText = _DebugMessageTemplate % TemplateDict + "\n %s" % ExtraData
else:
LogText = _DebugMessageTemplate % TemplateDict
_DebugLogger.log(Level, LogText)
## Log verbose message
#
# @param Message Verbose information
#
def verbose(Message):
return _InfoLogger.log(VERBOSE, Message)
## Log warning message
#
# Warning messages are those which might be wrong but won't fail the tool.
#
# @param ToolName The name of the tool. If not given, the name of caller
# method will be used.
# @param Message Warning information
# @param File The name of file which caused the warning.
# @param Line The line number in the "File" which caused the warning.
# @param ExtraData More information associated with "Message"
#
def warn(ToolName, Message, File=None, Line=None, ExtraData=None):
if _InfoLogger.level > WARN:
return
# if no tool name given, use caller's source file name as tool name
if ToolName == None or ToolName == "":
ToolName = os.path.basename(traceback.extract_stack()[-2][0])
if Line == None:
Line = "..."
else:
Line = "%d" % Line
TemplateDict = {
"tool" : ToolName,
"file" : File,
"line" : Line,
"msg" : Message,
}
if File != None:
LogText = _WarningMessageTemplate % TemplateDict
else:
LogText = _WarningMessageTemplateWithoutFile % TemplateDict
if ExtraData != None:
LogText += "\n %s" % ExtraData
_InfoLogger.log(WARN, LogText)
# Raise an execption if indicated
if _WarningAsError == True:
raise FatalError(WARNING_AS_ERROR)
## Log INFO message
info = _InfoLogger.info
## Log ERROR message
#
# Once an error messages is logged, the tool's execution will be broken by raising
# an execption. If you don't want to break the execution later, you can give
# "RaiseError" with "False" value.
#
# @param ToolName The name of the tool. If not given, the name of caller
# method will be used.
# @param ErrorCode The error code
# @param Message Warning information
# @param File The name of file which caused the error.
# @param Line The line number in the "File" which caused the warning.
# @param ExtraData More information associated with "Message"
# @param RaiseError Raise an exception to break the tool's executuion if
# it's True. This is the default behavior.
#
def error(ToolName, ErrorCode, Message=None, File=None, Line=None, ExtraData=None, RaiseError=IsRaiseError):
if Line == None:
Line = "..."
else:
Line = "%d" % Line
if Message == None:
if ErrorCode in gErrorMessage:
Message = gErrorMessage[ErrorCode]
else:
Message = gErrorMessage[UNKNOWN_ERROR]
if ExtraData == None:
ExtraData = ""
TemplateDict = {
"tool" : _ToolName,
"file" : File,
"line" : Line,
"errorcode" : ErrorCode,
"msg" : Message,
"extra" : ExtraData
}
if File != None:
LogText = _ErrorMessageTemplate % TemplateDict
else:
LogText = _ErrorMessageTemplateWithoutFile % TemplateDict
_ErrorLogger.log(ERROR, LogText)
if RaiseError:
raise FatalError(ErrorCode)
# Log information which should be always put out
quiet = _ErrorLogger.error
## Initialize log system
def Initialize():
#
# Since we use different format to log different levels of message into different
# place (stdout or stderr), we have to use different "Logger" objects to do this.
#
# For DEBUG level (All DEBUG_0~9 are applicable)
_DebugLogger.setLevel(INFO)
_DebugChannel = logging.StreamHandler(sys.stdout)
_DebugChannel.setFormatter(_DebugFormatter)
_DebugLogger.addHandler(_DebugChannel)
# For VERBOSE, INFO, WARN level
_InfoLogger.setLevel(INFO)
_InfoChannel = logging.StreamHandler(sys.stdout)
_InfoChannel.setFormatter(_InfoFormatter)
_InfoLogger.addHandler(_InfoChannel)
# For ERROR level
_ErrorLogger.setLevel(INFO)
_ErrorCh = logging.StreamHandler(sys.stderr)
_ErrorCh.setFormatter(_ErrorFormatter)
_ErrorLogger.addHandler(_ErrorCh)
## Set log level
#
# @param Level One of log level in _LogLevel
def SetLevel(Level):
if Level not in _LogLevels:
info("Not supported log level (%d). Use default level instead." % Level)
Level = INFO
_DebugLogger.setLevel(Level)
_InfoLogger.setLevel(Level)
_ErrorLogger.setLevel(Level)
## Get current log level
def GetLevel():
return _InfoLogger.getEffectiveLevel()
## Raise up warning as error
def SetWarningAsError():
global _WarningAsError
_WarningAsError = True
## Specify a file to store the log message as well as put on console
#
# @param LogFile The file path used to store the log message
#
def SetLogFile(LogFile):
if os.path.exists(LogFile):
os.remove(LogFile)
_Ch = logging.FileHandler(LogFile)
_Ch.setFormatter(_DebugFormatter)
_DebugLogger.addHandler(_Ch)
_Ch= logging.FileHandler(LogFile)
_Ch.setFormatter(_InfoFormatter)
_InfoLogger.addHandler(_Ch)
_Ch = logging.FileHandler(LogFile)
_Ch.setFormatter(_ErrorFormatter)
_ErrorLogger.addHandler(_Ch)
if __name__ == '__main__':
pass
## @file
# This file implements the log mechanism for Python tools.
#
# Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
# 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.
#
## Import modules
import sys, os, logging
import traceback
from BuildToolError import *
## Log level constants
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 = 20
WARN = 30
QUIET = 40
ERROR = 50
IsRaiseError = True
# Tool name
_ToolName = os.path.basename(sys.argv[0])
# For validation purpose
_LogLevels = [DEBUG_0, DEBUG_1, DEBUG_2, DEBUG_3, DEBUG_4, DEBUG_5, DEBUG_6, DEBUG_7, DEBUG_8, DEBUG_9, VERBOSE, WARN, INFO, ERROR, QUIET]
# For DEBUG level (All DEBUG_0~9 are applicable)
_DebugLogger = logging.getLogger("tool_debug")
_DebugFormatter = logging.Formatter("[%(asctime)s.%(msecs)d]: %(message)s", datefmt="%H:%M:%S")
# For VERBOSE, INFO, WARN level
_InfoLogger = logging.getLogger("tool_info")
_InfoFormatter = logging.Formatter("%(message)s")
# For ERROR level
_ErrorLogger = logging.getLogger("tool_error")
_ErrorFormatter = logging.Formatter("%(message)s")
# String templates for ERROR/WARN/DEBUG log message
_ErrorMessageTemplate = '\n\n%(tool)s...\n%(file)s(%(line)s): error %(errorcode)04X: %(msg)s\n\t%(extra)s'
_ErrorMessageTemplateWithoutFile = '\n\n%(tool)s...\n : error %(errorcode)04X: %(msg)s\n\t%(extra)s'
_WarningMessageTemplate = '%(tool)s...\n%(file)s(%(line)s): warning: %(msg)s'
_WarningMessageTemplateWithoutFile = '%(tool)s: : warning: %(msg)s'
_DebugMessageTemplate = '%(file)s(%(line)s): debug: \n %(msg)s'
#
# Flag used to take WARN as ERROR.
# By default, only ERROR message will break the tools execution.
#
_WarningAsError = False
## Log debug message
#
# @param Level DEBUG level (DEBUG0~9)
# @param Message Debug information
# @param ExtraData More information associated with "Message"
#
def debug(Level, Message, ExtraData=None):
if _DebugLogger.level > Level:
return
if Level > DEBUG_9:
return
# Find out the caller method information
CallerStack = traceback.extract_stack()[-2]
TemplateDict = {
"file" : CallerStack[0],
"line" : CallerStack[1],
"msg" : Message,
}
if ExtraData != None:
LogText = _DebugMessageTemplate % TemplateDict + "\n %s" % ExtraData
else:
LogText = _DebugMessageTemplate % TemplateDict
_DebugLogger.log(Level, LogText)
## Log verbose message
#
# @param Message Verbose information
#
def verbose(Message):
return _InfoLogger.log(VERBOSE, Message)
## Log warning message
#
# Warning messages are those which might be wrong but won't fail the tool.
#
# @param ToolName The name of the tool. If not given, the name of caller
# method will be used.
# @param Message Warning information
# @param File The name of file which caused the warning.
# @param Line The line number in the "File" which caused the warning.
# @param ExtraData More information associated with "Message"
#
def warn(ToolName, Message, File=None, Line=None, ExtraData=None):
if _InfoLogger.level > WARN:
return
# if no tool name given, use caller's source file name as tool name
if ToolName == None or ToolName == "":
ToolName = os.path.basename(traceback.extract_stack()[-2][0])
if Line == None:
Line = "..."
else:
Line = "%d" % Line
TemplateDict = {
"tool" : ToolName,
"file" : File,
"line" : Line,
"msg" : Message,
}
if File != None:
LogText = _WarningMessageTemplate % TemplateDict
else:
LogText = _WarningMessageTemplateWithoutFile % TemplateDict
if ExtraData != None:
LogText += "\n %s" % ExtraData
_InfoLogger.log(WARN, LogText)
# Raise an execption if indicated
if _WarningAsError == True:
raise FatalError(WARNING_AS_ERROR)
## Log INFO message
info = _InfoLogger.info
## Log ERROR message
#
# Once an error messages is logged, the tool's execution will be broken by raising
# an execption. If you don't want to break the execution later, you can give
# "RaiseError" with "False" value.
#
# @param ToolName The name of the tool. If not given, the name of caller
# method will be used.
# @param ErrorCode The error code
# @param Message Warning information
# @param File The name of file which caused the error.
# @param Line The line number in the "File" which caused the warning.
# @param ExtraData More information associated with "Message"
# @param RaiseError Raise an exception to break the tool's executuion if
# it's True. This is the default behavior.
#
def error(ToolName, ErrorCode, Message=None, File=None, Line=None, ExtraData=None, RaiseError=IsRaiseError):
if Line == None:
Line = "..."
else:
Line = "%d" % Line
if Message == None:
if ErrorCode in gErrorMessage:
Message = gErrorMessage[ErrorCode]
else:
Message = gErrorMessage[UNKNOWN_ERROR]
if ExtraData == None:
ExtraData = ""
TemplateDict = {
"tool" : _ToolName,
"file" : File,
"line" : Line,
"errorcode" : ErrorCode,
"msg" : Message,
"extra" : ExtraData
}
if File != None:
LogText = _ErrorMessageTemplate % TemplateDict
else:
LogText = _ErrorMessageTemplateWithoutFile % TemplateDict
_ErrorLogger.log(ERROR, LogText)
if RaiseError:
raise FatalError(ErrorCode)
# Log information which should be always put out
quiet = _ErrorLogger.error
## Initialize log system
def Initialize():
#
# Since we use different format to log different levels of message into different
# place (stdout or stderr), we have to use different "Logger" objects to do this.
#
# For DEBUG level (All DEBUG_0~9 are applicable)
_DebugLogger.setLevel(INFO)
_DebugChannel = logging.StreamHandler(sys.stdout)
_DebugChannel.setFormatter(_DebugFormatter)
_DebugLogger.addHandler(_DebugChannel)
# For VERBOSE, INFO, WARN level
_InfoLogger.setLevel(INFO)
_InfoChannel = logging.StreamHandler(sys.stdout)
_InfoChannel.setFormatter(_InfoFormatter)
_InfoLogger.addHandler(_InfoChannel)
# For ERROR level
_ErrorLogger.setLevel(INFO)
_ErrorCh = logging.StreamHandler(sys.stderr)
_ErrorCh.setFormatter(_ErrorFormatter)
_ErrorLogger.addHandler(_ErrorCh)
## Set log level
#
# @param Level One of log level in _LogLevel
def SetLevel(Level):
if Level not in _LogLevels:
info("Not supported log level (%d). Use default level instead." % Level)
Level = INFO
_DebugLogger.setLevel(Level)
_InfoLogger.setLevel(Level)
_ErrorLogger.setLevel(Level)
## Get current log level
def GetLevel():
return _InfoLogger.getEffectiveLevel()
## Raise up warning as error
def SetWarningAsError():
global _WarningAsError
_WarningAsError = True
## Specify a file to store the log message as well as put on console
#
# @param LogFile The file path used to store the log message
#
def SetLogFile(LogFile):
if os.path.exists(LogFile):
os.remove(LogFile)
_Ch = logging.FileHandler(LogFile)
_Ch.setFormatter(_DebugFormatter)
_DebugLogger.addHandler(_Ch)
_Ch= logging.FileHandler(LogFile)
_Ch.setFormatter(_InfoFormatter)
_InfoLogger.addHandler(_Ch)
_Ch = logging.FileHandler(LogFile)
_Ch.setFormatter(_ErrorFormatter)
_ErrorLogger.addHandler(_Ch)
if __name__ == '__main__':
pass

View File

@@ -1,71 +1,71 @@
## @file
# This file is used to define common static strings used by INF/DEC/DSC files
#
# Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
# 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.
import re
gIsWindows = None
gEdkCompatibilityPkg = "EdkCompatibilityPkg"
gWorkspace = "."
gEdkSource = "EdkCompatibilityPkg"
gEfiSource = "."
gEcpSource = "EdkCompatibilityPkg"
gOptions = None
gCaseInsensitive = False
gAllFiles = None
gGlobalDefines = {}
gPlatformDefines = {}
# PCD name and value pair for fixed at build and feature flag
gPlatformPcds = {}
# PCDs with type that are not fixed at build and feature flag
gPlatformOtherPcds = {}
gActivePlatform = None
gCommandLineDefines = {}
gEdkGlobal = {}
gOverrideDir = {}
# for debug trace purpose when problem occurs
gProcessingFile = ''
gBuildingModule = ''
## Regular expression for matching macro used in DSC/DEC/INF file inclusion
gMacroRefPattern = re.compile("\$\(([A-Z][_A-Z0-9]*)\)", re.UNICODE)
gMacroDefPattern = re.compile("^(DEFINE|EDK_GLOBAL)[ \t]+")
gMacroNamePattern = re.compile("^[A-Z][A-Z0-9_]*$")
# C-style wide string pattern
gWideStringPattern = re.compile('(\W|\A)L"')
#
# A global variable for whether current build in AutoGen phase or not.
#
gAutoGenPhase = False
#
# The Conf dir outside the workspace dir
#
gConfDirectory = ''
#
# The relative default database file path
#
gDatabasePath = ".cache/build.db"
#
# Build flag for binary build
#
gIgnoreSource = False
#
# FDF parser
#
gFdfParser = None
## @file
# This file is used to define common static strings used by INF/DEC/DSC files
#
# Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
# 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.
import re
gIsWindows = None
gEdkCompatibilityPkg = "EdkCompatibilityPkg"
gWorkspace = "."
gEdkSource = "EdkCompatibilityPkg"
gEfiSource = "."
gEcpSource = "EdkCompatibilityPkg"
gOptions = None
gCaseInsensitive = False
gAllFiles = None
gGlobalDefines = {}
gPlatformDefines = {}
# PCD name and value pair for fixed at build and feature flag
gPlatformPcds = {}
# PCDs with type that are not fixed at build and feature flag
gPlatformOtherPcds = {}
gActivePlatform = None
gCommandLineDefines = {}
gEdkGlobal = {}
gOverrideDir = {}
# for debug trace purpose when problem occurs
gProcessingFile = ''
gBuildingModule = ''
## Regular expression for matching macro used in DSC/DEC/INF file inclusion
gMacroRefPattern = re.compile("\$\(([A-Z][_A-Z0-9]*)\)", re.UNICODE)
gMacroDefPattern = re.compile("^(DEFINE|EDK_GLOBAL)[ \t]+")
gMacroNamePattern = re.compile("^[A-Z][A-Z0-9_]*$")
# C-style wide string pattern
gWideStringPattern = re.compile('(\W|\A)L"')
#
# A global variable for whether current build in AutoGen phase or not.
#
gAutoGenPhase = False
#
# The Conf dir outside the workspace dir
#
gConfDirectory = ''
#
# The relative default database file path
#
gDatabasePath = ".cache/build.db"
#
# Build flag for binary build
#
gIgnoreSource = False
#
# FDF parser
#
gFdfParser = None

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +1,20 @@
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Xml
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Xml
'''

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -80,11 +80,11 @@ class EfiSection (EfiSectionClassObject):
FileList = []
if Filename != None:
Filename = GenFdsGlobalVariable.MacroExtend(Filename, Dict)
# check if the path is absolute or relative
if os.path.isabs(Filename):
Filename = os.path.normpath(Filename)
else:
Filename = os.path.normpath(os.path.join(FfsInf.EfiOutputPath, Filename))
# check if the path is absolute or relative
if os.path.isabs(Filename):
Filename = os.path.normpath(Filename)
else:
Filename = os.path.normpath(os.path.join(FfsInf.EfiOutputPath, Filename))
if not self.Optional:
FileList.append(Filename)

View File

@@ -296,13 +296,13 @@ class FV (FvClassObject):
Buffer = ''
for Index in range (0, len(self.FvExtEntryType)):
if self.FvExtEntryType[Index] == 'FILE':
# check if the path is absolute or relative
if os.path.isabs(self.FvExtEntryData[Index]):
FileFullPath = os.path.normpath(self.FvExtEntryData[Index])
else:
FileFullPath = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, self.FvExtEntryData[Index]))
# check if the file path exists or not
if not os.path.isfile(FileFullPath):
# check if the path is absolute or relative
if os.path.isabs(self.FvExtEntryData[Index]):
FileFullPath = os.path.normpath(self.FvExtEntryData[Index])
else:
FileFullPath = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, self.FvExtEntryData[Index]))
# check if the file path exists or not
if not os.path.isfile(FileFullPath):
GenFdsGlobalVariable.ErrorLogger("Error opening FV Extension Header Entry file %s." % (self.FvExtEntryData[Index]))
FvExtFile = open (FileFullPath,'rb')
FvExtFile.seek(0,2)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,8 @@
## @file
# Generate PCD table for 'Patchable In Module' type PCD with given .map file.
# The Patch PCD table like:
#
# PCD Name Offset in binary
# The Patch PCD table like:
#
# PCD Name Offset in binary
# ======== ================
#
# Copyright (c) 2008 - 2013, Intel Corporation. All rights reserved.<BR>
@@ -14,77 +14,77 @@
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
#
#====================================== External Libraries ========================================
import optparse
import os
import re
import array
from Common.BuildToolError import *
import Common.EdkLogger as EdkLogger
#
#====================================== External Libraries ========================================
import optparse
import os
import re
import array
from Common.BuildToolError import *
import Common.EdkLogger as EdkLogger
from Common.Misc import PeImageClass
from Common.BuildVersion import gBUILD_VERSION
# Version and Copyright
__version_number__ = ("0.10" + " " + gBUILD_VERSION)
__version__ = "%prog Version " + __version_number__
__copyright__ = "Copyright (c) 2008 - 2010, Intel Corporation. All rights reserved."
#====================================== Internal Libraries ========================================
#============================================== Code ===============================================
secRe = re.compile('^([\da-fA-F]+):([\da-fA-F]+) +([\da-fA-F]+)[Hh]? +([.\w\$]+) +(\w+)', re.UNICODE)
symRe = re.compile('^([\da-fA-F]+):([\da-fA-F]+) +([\.:\\\\\w\?@\$]+) +([\da-fA-F]+)', re.UNICODE)
def parsePcdInfoFromMapFile(mapfilepath, efifilepath):
""" Parse map file to get binary patch pcd information
@param path Map file absolution path
@return a list which element hold (PcdName, Offset, SectionName)
"""
lines = []
try:
f = open(mapfilepath, 'r')
lines = f.readlines()
f.close()
except:
return None
if len(lines) == 0: return None
if lines[0].strip().find("Archive member included because of file (symbol)") != -1:
return _parseForGCC(lines, efifilepath)
return _parseGeneral(lines, efifilepath)
def _parseForGCC(lines, efifilepath):
""" Parse map file generated by GCC linker """
status = 0
imageBase = -1
sections = []
bpcds = []
for line in lines:
line = line.strip()
# status machine transection
if status == 0 and line == "Memory Configuration":
status = 1
continue
elif status == 1 and line == 'Linker script and memory map':
status = 2
continue
elif status ==2 and line == 'START GROUP':
status = 3
continue
# Version and Copyright
__version_number__ = ("0.10" + " " + gBUILD_VERSION)
__version__ = "%prog Version " + __version_number__
__copyright__ = "Copyright (c) 2008 - 2010, Intel Corporation. All rights reserved."
#====================================== Internal Libraries ========================================
#============================================== Code ===============================================
secRe = re.compile('^([\da-fA-F]+):([\da-fA-F]+) +([\da-fA-F]+)[Hh]? +([.\w\$]+) +(\w+)', re.UNICODE)
symRe = re.compile('^([\da-fA-F]+):([\da-fA-F]+) +([\.:\\\\\w\?@\$]+) +([\da-fA-F]+)', re.UNICODE)
def parsePcdInfoFromMapFile(mapfilepath, efifilepath):
""" Parse map file to get binary patch pcd information
@param path Map file absolution path
@return a list which element hold (PcdName, Offset, SectionName)
"""
lines = []
try:
f = open(mapfilepath, 'r')
lines = f.readlines()
f.close()
except:
return None
if len(lines) == 0: return None
if lines[0].strip().find("Archive member included because of file (symbol)") != -1:
return _parseForGCC(lines, efifilepath)
return _parseGeneral(lines, efifilepath)
def _parseForGCC(lines, efifilepath):
""" Parse map file generated by GCC linker """
status = 0
imageBase = -1
sections = []
bpcds = []
for line in lines:
line = line.strip()
# status machine transection
if status == 0 and line == "Memory Configuration":
status = 1
continue
elif status == 1 and line == 'Linker script and memory map':
status = 2
continue
elif status ==2 and line == 'START GROUP':
status = 3
continue
# status handler
if status == 2:
m = re.match('^([\w_\.]+) +([\da-fA-Fx]+) +([\da-fA-Fx]+)$', line)
if m != None:
sections.append(m.groups(0))
if status == 2:
m = re.match("^([\da-fA-Fx]+) +[_]+gPcd_BinaryPatch_([\w_\d]+)$", line)
if m != None:
bpcds.append((m.groups(0)[1], int(m.groups(0)[0], 16) , int(sections[-1][1], 16), sections[-1][0]))
if status == 2:
m = re.match('^([\w_\.]+) +([\da-fA-Fx]+) +([\da-fA-Fx]+)$', line)
if m != None:
sections.append(m.groups(0))
if status == 2:
m = re.match("^([\da-fA-Fx]+) +[_]+gPcd_BinaryPatch_([\w_\d]+)$", line)
if m != None:
bpcds.append((m.groups(0)[1], int(m.groups(0)[0], 16) , int(sections[-1][1], 16), sections[-1][0]))
# get section information from efi file
efisecs = PeImageClass(efifilepath).SectionHeaderList
@@ -102,104 +102,104 @@ def _parseForGCC(lines, efifilepath):
if pcd[1] >= efisec[1] and pcd[1] < efisec[1]+efisec[3]:
#assert efisec[0].strip() == pcd[3].strip() and efisec[1] + redirection == pcd[2], "There are some differences between map file and efi file"
pcds.append([pcd[0], efisec[2] + pcd[1] - efisec[1] - redirection, efisec[0]])
return pcds
def _parseGeneral(lines, efifilepath):
""" For MSFT, ICC, EBC
@param lines line array for map file
@return a list which element hold (PcdName, Offset, SectionName)
"""
status = 0 #0 - beginning of file; 1 - PE section definition; 2 - symbol table
secs = [] # key = section name
bPcds = []
for line in lines:
line = line.strip()
if re.match("^Start[' ']+Length[' ']+Name[' ']+Class", line):
status = 1
continue
if re.match("^Address[' ']+Publics by Value[' ']+Rva\+Base", line):
status = 2
continue
if re.match("^entry point at", line):
status = 3
continue
if status == 1 and len(line) != 0:
m = secRe.match(line)
assert m != None, "Fail to parse the section in map file , line is %s" % line
sec_no, sec_start, sec_length, sec_name, sec_class = m.groups(0)
secs.append([int(sec_no, 16), int(sec_start, 16), int(sec_length, 16), sec_name, sec_class])
if status == 2 and len(line) != 0:
m = symRe.match(line)
assert m != None, "Fail to parse the symbol in map file, line is %s" % line
sec_no, sym_offset, sym_name, vir_addr = m.groups(0)
sec_no = int(sec_no, 16)
sym_offset = int(sym_offset, 16)
vir_addr = int(vir_addr, 16)
m2 = re.match('^[_]+gPcd_BinaryPatch_([\w]+)', sym_name)
if m2 != None:
# fond a binary pcd entry in map file
for sec in secs:
if sec[0] == sec_no and (sym_offset >= sec[1] and sym_offset < sec[1] + sec[2]):
bPcds.append([m2.groups(0)[0], sec[3], sym_offset, vir_addr, sec_no])
if len(bPcds) == 0: return None
# get section information from efi file
efisecs = PeImageClass(efifilepath).SectionHeaderList
if efisecs == None or len(efisecs) == 0:
return None
pcds = []
for pcd in bPcds:
index = 0
for efisec in efisecs:
index = index + 1
if pcd[1].strip() == efisec[0].strip():
pcds.append([pcd[0], efisec[2] + pcd[2], efisec[0]])
elif pcd[4] == index:
pcds.append([pcd[0], efisec[2] + pcd[2], efisec[0]])
return pcds
def generatePcdTable(list, pcdpath):
try:
f = open(pcdpath, 'w')
except:
pass
f.write('PCD Name Offset Section Name\r\n')
for pcditem in list:
f.write('%-30s 0x%-08X %-6s\r\n' % (pcditem[0], pcditem[1], pcditem[2]))
f.close()
#print 'Success to generate Binary Patch PCD table at %s!' % pcdpath
if __name__ == '__main__':
UsageString = "%prog -m <MapFile> -e <EfiFile> -o <OutFile>"
AdditionalNotes = "\nPCD table is generated in file name with .BinaryPcdTable.txt postfix"
parser = optparse.OptionParser(description=__copyright__, version=__version__, usage=UsageString)
parser.add_option('-m', '--mapfile', action='store', dest='mapfile',
help='Absolute path of module map file.')
parser.add_option('-e', '--efifile', action='store', dest='efifile',
help='Absolute path of EFI binary file.')
parser.add_option('-o', '--outputfile', action='store', dest='outfile',
help='Absolute path of output file to store the got patchable PCD table.')
(options, args) = parser.parse_args()
if options.mapfile == None or options.efifile == None:
print parser.get_usage()
elif os.path.exists(options.mapfile) and os.path.exists(options.efifile):
list = parsePcdInfoFromMapFile(options.mapfile, options.efifile)
if list != None:
if options.outfile != None:
generatePcdTable(list, options.outfile)
else:
generatePcdTable(list, options.mapfile.replace('.map', '.BinaryPcdTable.txt'))
else:
print 'Fail to generate Patch PCD Table based on map file and efi file'
else:
print 'Fail to generate Patch PCD Table for fail to find map file or efi file!'
return pcds
def _parseGeneral(lines, efifilepath):
""" For MSFT, ICC, EBC
@param lines line array for map file
@return a list which element hold (PcdName, Offset, SectionName)
"""
status = 0 #0 - beginning of file; 1 - PE section definition; 2 - symbol table
secs = [] # key = section name
bPcds = []
for line in lines:
line = line.strip()
if re.match("^Start[' ']+Length[' ']+Name[' ']+Class", line):
status = 1
continue
if re.match("^Address[' ']+Publics by Value[' ']+Rva\+Base", line):
status = 2
continue
if re.match("^entry point at", line):
status = 3
continue
if status == 1 and len(line) != 0:
m = secRe.match(line)
assert m != None, "Fail to parse the section in map file , line is %s" % line
sec_no, sec_start, sec_length, sec_name, sec_class = m.groups(0)
secs.append([int(sec_no, 16), int(sec_start, 16), int(sec_length, 16), sec_name, sec_class])
if status == 2 and len(line) != 0:
m = symRe.match(line)
assert m != None, "Fail to parse the symbol in map file, line is %s" % line
sec_no, sym_offset, sym_name, vir_addr = m.groups(0)
sec_no = int(sec_no, 16)
sym_offset = int(sym_offset, 16)
vir_addr = int(vir_addr, 16)
m2 = re.match('^[_]+gPcd_BinaryPatch_([\w]+)', sym_name)
if m2 != None:
# fond a binary pcd entry in map file
for sec in secs:
if sec[0] == sec_no and (sym_offset >= sec[1] and sym_offset < sec[1] + sec[2]):
bPcds.append([m2.groups(0)[0], sec[3], sym_offset, vir_addr, sec_no])
if len(bPcds) == 0: return None
# get section information from efi file
efisecs = PeImageClass(efifilepath).SectionHeaderList
if efisecs == None or len(efisecs) == 0:
return None
pcds = []
for pcd in bPcds:
index = 0
for efisec in efisecs:
index = index + 1
if pcd[1].strip() == efisec[0].strip():
pcds.append([pcd[0], efisec[2] + pcd[2], efisec[0]])
elif pcd[4] == index:
pcds.append([pcd[0], efisec[2] + pcd[2], efisec[0]])
return pcds
def generatePcdTable(list, pcdpath):
try:
f = open(pcdpath, 'w')
except:
pass
f.write('PCD Name Offset Section Name\r\n')
for pcditem in list:
f.write('%-30s 0x%-08X %-6s\r\n' % (pcditem[0], pcditem[1], pcditem[2]))
f.close()
#print 'Success to generate Binary Patch PCD table at %s!' % pcdpath
if __name__ == '__main__':
UsageString = "%prog -m <MapFile> -e <EfiFile> -o <OutFile>"
AdditionalNotes = "\nPCD table is generated in file name with .BinaryPcdTable.txt postfix"
parser = optparse.OptionParser(description=__copyright__, version=__version__, usage=UsageString)
parser.add_option('-m', '--mapfile', action='store', dest='mapfile',
help='Absolute path of module map file.')
parser.add_option('-e', '--efifile', action='store', dest='efifile',
help='Absolute path of EFI binary file.')
parser.add_option('-o', '--outputfile', action='store', dest='outfile',
help='Absolute path of output file to store the got patchable PCD table.')
(options, args) = parser.parse_args()
if options.mapfile == None or options.efifile == None:
print parser.get_usage()
elif os.path.exists(options.mapfile) and os.path.exists(options.efifile):
list = parsePcdInfoFromMapFile(options.mapfile, options.efifile)
if list != None:
if options.outfile != None:
generatePcdTable(list, options.outfile)
else:
generatePcdTable(list, options.mapfile.replace('.map', '.BinaryPcdTable.txt'))
else:
print 'Fail to generate Patch PCD Table based on map file and efi file'
else:
print 'Fail to generate Patch PCD Table for fail to find map file or efi file!'

View File

@@ -1,290 +1,290 @@
## @file
# Patch value into the binary file.
#
# Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
# 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.
#
##
# Import Modules
#
import os
import sys
import re
from optparse import OptionParser
from optparse import make_option
from Common.BuildToolError import *
import Common.EdkLogger as EdkLogger
from Common.BuildVersion import gBUILD_VERSION
import array
# Version and Copyright
__version_number__ = ("0.10" + " " + gBUILD_VERSION)
__version__ = "%prog Version " + __version_number__
__copyright__ = "Copyright (c) 2010, Intel Corporation. All rights reserved."
## PatchBinaryFile method
#
# This method mainly patches the data into binary file.
#
# @param FileName File path of the binary file
# @param ValueOffset Offset value
# @param TypeName DataType Name
# @param Value Value String
# @param MaxSize MaxSize value
#
# @retval 0 File is updated successfully.
# @retval not 0 File is updated failed.
#
def PatchBinaryFile(FileName, ValueOffset, TypeName, ValueString, MaxSize=0):
#
# Length of Binary File
#
FileHandle = open (FileName, 'rb')
FileHandle.seek (0, 2)
FileLength = FileHandle.tell()
FileHandle.close()
#
# Unify string to upper string
#
TypeName = TypeName.upper()
#
# Get PCD value data length
#
ValueLength = 0
if TypeName == 'BOOLEAN':
ValueLength = 1
elif TypeName == 'UINT8':
ValueLength = 1
elif TypeName == 'UINT16':
ValueLength = 2
elif TypeName == 'UINT32':
ValueLength = 4
elif TypeName == 'UINT64':
ValueLength = 8
elif TypeName == 'VOID*':
if MaxSize == 0:
return OPTION_MISSING, "PcdMaxSize is not specified for VOID* type PCD."
ValueLength = int(MaxSize)
else:
return PARAMETER_INVALID, "PCD type %s is not valid." %(CommandOptions.PcdTypeName)
#
# Check PcdValue is in the input binary file.
#
if ValueOffset + ValueLength > FileLength:
return PARAMETER_INVALID, "PcdOffset + PcdMaxSize(DataType) is larger than the input file size."
#
# Read binary file into array
#
FileHandle = open (FileName, 'rb')
ByteArray = array.array('B')
ByteArray.fromfile(FileHandle, FileLength)
FileHandle.close()
OrigByteList = ByteArray.tolist()
ByteList = ByteArray.tolist()
#
# Clear the data in file
#
for Index in range(ValueLength):
ByteList[ValueOffset + Index] = 0
#
# Patch value into offset
#
SavedStr = ValueString
ValueString = ValueString.upper()
ValueNumber = 0
if TypeName == 'BOOLEAN':
#
# Get PCD value for BOOLEAN data type
#
try:
if ValueString == 'TRUE':
ValueNumber = 1
elif ValueString == 'FALSE':
ValueNumber = 0
elif ValueString.startswith('0X'):
ValueNumber = int (ValueString, 16)
else:
ValueNumber = int (ValueString)
if ValueNumber != 0:
ValueNumber = 1
except:
return PARAMETER_INVALID, "PCD Value %s is not valid dec or hex string." %(ValueString)
#
# Set PCD value into binary data
#
ByteList[ValueOffset] = ValueNumber
elif TypeName in ['UINT8', 'UINT16', 'UINT32', 'UINT64']:
#
# Get PCD value for UINT* data type
#
try:
if ValueString.startswith('0X'):
ValueNumber = int (ValueString, 16)
else:
ValueNumber = int (ValueString)
except:
return PARAMETER_INVALID, "PCD Value %s is not valid dec or hex string." %(ValueString)
#
# Set PCD value into binary data
#
for Index in range(ValueLength):
ByteList[ValueOffset + Index] = ValueNumber % 0x100
ValueNumber = ValueNumber / 0x100
elif TypeName == 'VOID*':
ValueString = SavedStr
if ValueString.startswith('L"'):
#
# Patch Unicode String
#
Index = 0
for ByteString in ValueString[2:-1]:
#
# Reserve zero as unicode tail
#
if Index + 2 >= ValueLength:
break
#
# Set string value one by one
#
ByteList[ValueOffset + Index] = ord(ByteString)
Index = Index + 2
elif ValueString.startswith("{") and ValueString.endswith("}"):
#
# Patch {0x1, 0x2, ...} byte by byte
#
ValueList = ValueString[1 : len(ValueString) - 1].split(', ')
Index = 0
try:
for ByteString in ValueList:
if ByteString.upper().startswith('0X'):
ByteValue = int(ByteString, 16)
else:
ByteValue = int(ByteString)
ByteList[ValueOffset + Index] = ByteValue % 0x100
Index = Index + 1
if Index >= ValueLength:
break
except:
return PARAMETER_INVALID, "PCD Value %s is not valid dec or hex string array." %(ValueString)
else:
#
# Patch ascii string
#
Index = 0
for ByteString in ValueString[1:-1]:
#
# Reserve zero as string tail
#
if Index + 1 >= ValueLength:
break
#
# Set string value one by one
#
ByteList[ValueOffset + Index] = ord(ByteString)
Index = Index + 1
#
# Update new data into input file.
#
if ByteList != OrigByteList:
ByteArray = array.array('B')
ByteArray.fromlist(ByteList)
FileHandle = open (FileName, 'wb')
ByteArray.tofile(FileHandle)
FileHandle.close()
return 0, "Patch Value into File %s successfully." %(FileName)
## Parse command line options
#
# Using standard Python module optparse to parse command line option of this tool.
#
# @retval Options A optparse.Values object containing the parsed options
# @retval InputFile Path of file to be trimmed
#
def Options():
OptionList = [
make_option("-f", "--offset", dest="PcdOffset", action="store", type="int",
help="Start offset to the image is used to store PCD value."),
make_option("-u", "--value", dest="PcdValue", action="store",
help="PCD value will be updated into the image."),
make_option("-t", "--type", dest="PcdTypeName", action="store",
help="The name of PCD data type may be one of VOID*,BOOLEAN, UINT8, UINT16, UINT32, UINT64."),
make_option("-s", "--maxsize", dest="PcdMaxSize", action="store", type="int",
help="Max size of data buffer is taken by PCD value.It must be set when PCD type is VOID*."),
make_option("-v", "--verbose", dest="LogLevel", action="store_const", const=EdkLogger.VERBOSE,
help="Run verbosely"),
make_option("-d", "--debug", dest="LogLevel", type="int",
help="Run with debug information"),
make_option("-q", "--quiet", dest="LogLevel", action="store_const", const=EdkLogger.QUIET,
help="Run quietly"),
make_option("-?", action="help", help="show this help message and exit"),
]
# use clearer usage to override default usage message
UsageString = "%prog -f Offset -u Value -t Type [-s MaxSize] <input_file>"
Parser = OptionParser(description=__copyright__, version=__version__, option_list=OptionList, usage=UsageString)
Parser.set_defaults(LogLevel=EdkLogger.INFO)
Options, Args = Parser.parse_args()
# error check
if len(Args) == 0:
EdkLogger.error("PatchPcdValue", PARAMETER_INVALID, ExtraData=Parser.get_usage())
InputFile = Args[len(Args) - 1]
return Options, InputFile
## Entrance method
#
# This method mainly dispatch specific methods per the command line options.
# If no error found, return zero value so the caller of this tool can know
# if it's executed successfully or not.
#
# @retval 0 Tool was successful
# @retval 1 Tool failed
#
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 == None or CommandOptions.PcdValue == None or CommandOptions.PcdTypeName == None:
EdkLogger.error("PatchPcdValue", OPTION_MISSING, ExtraData="PcdOffset or PcdValue of PcdTypeName is not specified.")
return 1
if CommandOptions.PcdTypeName.upper() not in ["BOOLEAN", "UINT8", "UINT16", "UINT32", "UINT64", "VOID*"]:
EdkLogger.error("PatchPcdValue", PARAMETER_INVALID, ExtraData="PCD type %s is not valid." %(CommandOptions.PcdTypeName))
return 1
if CommandOptions.PcdTypeName.upper() == "VOID*" and CommandOptions.PcdMaxSize == 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
if __name__ == '__main__':
r = Main()
sys.exit(r)
## @file
# Patch value into the binary file.
#
# Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
# 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.
#
##
# Import Modules
#
import os
import sys
import re
from optparse import OptionParser
from optparse import make_option
from Common.BuildToolError import *
import Common.EdkLogger as EdkLogger
from Common.BuildVersion import gBUILD_VERSION
import array
# Version and Copyright
__version_number__ = ("0.10" + " " + gBUILD_VERSION)
__version__ = "%prog Version " + __version_number__
__copyright__ = "Copyright (c) 2010, Intel Corporation. All rights reserved."
## PatchBinaryFile method
#
# This method mainly patches the data into binary file.
#
# @param FileName File path of the binary file
# @param ValueOffset Offset value
# @param TypeName DataType Name
# @param Value Value String
# @param MaxSize MaxSize value
#
# @retval 0 File is updated successfully.
# @retval not 0 File is updated failed.
#
def PatchBinaryFile(FileName, ValueOffset, TypeName, ValueString, MaxSize=0):
#
# Length of Binary File
#
FileHandle = open (FileName, 'rb')
FileHandle.seek (0, 2)
FileLength = FileHandle.tell()
FileHandle.close()
#
# Unify string to upper string
#
TypeName = TypeName.upper()
#
# Get PCD value data length
#
ValueLength = 0
if TypeName == 'BOOLEAN':
ValueLength = 1
elif TypeName == 'UINT8':
ValueLength = 1
elif TypeName == 'UINT16':
ValueLength = 2
elif TypeName == 'UINT32':
ValueLength = 4
elif TypeName == 'UINT64':
ValueLength = 8
elif TypeName == 'VOID*':
if MaxSize == 0:
return OPTION_MISSING, "PcdMaxSize is not specified for VOID* type PCD."
ValueLength = int(MaxSize)
else:
return PARAMETER_INVALID, "PCD type %s is not valid." %(CommandOptions.PcdTypeName)
#
# Check PcdValue is in the input binary file.
#
if ValueOffset + ValueLength > FileLength:
return PARAMETER_INVALID, "PcdOffset + PcdMaxSize(DataType) is larger than the input file size."
#
# Read binary file into array
#
FileHandle = open (FileName, 'rb')
ByteArray = array.array('B')
ByteArray.fromfile(FileHandle, FileLength)
FileHandle.close()
OrigByteList = ByteArray.tolist()
ByteList = ByteArray.tolist()
#
# Clear the data in file
#
for Index in range(ValueLength):
ByteList[ValueOffset + Index] = 0
#
# Patch value into offset
#
SavedStr = ValueString
ValueString = ValueString.upper()
ValueNumber = 0
if TypeName == 'BOOLEAN':
#
# Get PCD value for BOOLEAN data type
#
try:
if ValueString == 'TRUE':
ValueNumber = 1
elif ValueString == 'FALSE':
ValueNumber = 0
elif ValueString.startswith('0X'):
ValueNumber = int (ValueString, 16)
else:
ValueNumber = int (ValueString)
if ValueNumber != 0:
ValueNumber = 1
except:
return PARAMETER_INVALID, "PCD Value %s is not valid dec or hex string." %(ValueString)
#
# Set PCD value into binary data
#
ByteList[ValueOffset] = ValueNumber
elif TypeName in ['UINT8', 'UINT16', 'UINT32', 'UINT64']:
#
# Get PCD value for UINT* data type
#
try:
if ValueString.startswith('0X'):
ValueNumber = int (ValueString, 16)
else:
ValueNumber = int (ValueString)
except:
return PARAMETER_INVALID, "PCD Value %s is not valid dec or hex string." %(ValueString)
#
# Set PCD value into binary data
#
for Index in range(ValueLength):
ByteList[ValueOffset + Index] = ValueNumber % 0x100
ValueNumber = ValueNumber / 0x100
elif TypeName == 'VOID*':
ValueString = SavedStr
if ValueString.startswith('L"'):
#
# Patch Unicode String
#
Index = 0
for ByteString in ValueString[2:-1]:
#
# Reserve zero as unicode tail
#
if Index + 2 >= ValueLength:
break
#
# Set string value one by one
#
ByteList[ValueOffset + Index] = ord(ByteString)
Index = Index + 2
elif ValueString.startswith("{") and ValueString.endswith("}"):
#
# Patch {0x1, 0x2, ...} byte by byte
#
ValueList = ValueString[1 : len(ValueString) - 1].split(', ')
Index = 0
try:
for ByteString in ValueList:
if ByteString.upper().startswith('0X'):
ByteValue = int(ByteString, 16)
else:
ByteValue = int(ByteString)
ByteList[ValueOffset + Index] = ByteValue % 0x100
Index = Index + 1
if Index >= ValueLength:
break
except:
return PARAMETER_INVALID, "PCD Value %s is not valid dec or hex string array." %(ValueString)
else:
#
# Patch ascii string
#
Index = 0
for ByteString in ValueString[1:-1]:
#
# Reserve zero as string tail
#
if Index + 1 >= ValueLength:
break
#
# Set string value one by one
#
ByteList[ValueOffset + Index] = ord(ByteString)
Index = Index + 1
#
# Update new data into input file.
#
if ByteList != OrigByteList:
ByteArray = array.array('B')
ByteArray.fromlist(ByteList)
FileHandle = open (FileName, 'wb')
ByteArray.tofile(FileHandle)
FileHandle.close()
return 0, "Patch Value into File %s successfully." %(FileName)
## Parse command line options
#
# Using standard Python module optparse to parse command line option of this tool.
#
# @retval Options A optparse.Values object containing the parsed options
# @retval InputFile Path of file to be trimmed
#
def Options():
OptionList = [
make_option("-f", "--offset", dest="PcdOffset", action="store", type="int",
help="Start offset to the image is used to store PCD value."),
make_option("-u", "--value", dest="PcdValue", action="store",
help="PCD value will be updated into the image."),
make_option("-t", "--type", dest="PcdTypeName", action="store",
help="The name of PCD data type may be one of VOID*,BOOLEAN, UINT8, UINT16, UINT32, UINT64."),
make_option("-s", "--maxsize", dest="PcdMaxSize", action="store", type="int",
help="Max size of data buffer is taken by PCD value.It must be set when PCD type is VOID*."),
make_option("-v", "--verbose", dest="LogLevel", action="store_const", const=EdkLogger.VERBOSE,
help="Run verbosely"),
make_option("-d", "--debug", dest="LogLevel", type="int",
help="Run with debug information"),
make_option("-q", "--quiet", dest="LogLevel", action="store_const", const=EdkLogger.QUIET,
help="Run quietly"),
make_option("-?", action="help", help="show this help message and exit"),
]
# use clearer usage to override default usage message
UsageString = "%prog -f Offset -u Value -t Type [-s MaxSize] <input_file>"
Parser = OptionParser(description=__copyright__, version=__version__, option_list=OptionList, usage=UsageString)
Parser.set_defaults(LogLevel=EdkLogger.INFO)
Options, Args = Parser.parse_args()
# error check
if len(Args) == 0:
EdkLogger.error("PatchPcdValue", PARAMETER_INVALID, ExtraData=Parser.get_usage())
InputFile = Args[len(Args) - 1]
return Options, InputFile
## Entrance method
#
# This method mainly dispatch specific methods per the command line options.
# If no error found, return zero value so the caller of this tool can know
# if it's executed successfully or not.
#
# @retval 0 Tool was successful
# @retval 1 Tool failed
#
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 == None or CommandOptions.PcdValue == None or CommandOptions.PcdTypeName == None:
EdkLogger.error("PatchPcdValue", OPTION_MISSING, ExtraData="PcdOffset or PcdValue of PcdTypeName is not specified.")
return 1
if CommandOptions.PcdTypeName.upper() not in ["BOOLEAN", "UINT8", "UINT16", "UINT32", "UINT64", "VOID*"]:
EdkLogger.error("PatchPcdValue", PARAMETER_INVALID, ExtraData="PCD type %s is not valid." %(CommandOptions.PcdTypeName))
return 1
if CommandOptions.PcdTypeName.upper() == "VOID*" and CommandOptions.PcdMaxSize == 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
if __name__ == '__main__':
r = Main()
sys.exit(r)

File diff suppressed because it is too large Load Diff

View File

@@ -17,4 +17,4 @@
Build version information
'''
gBUILD_VERSION = "Build 2640"
gBUILD_VERSION = "Build 2649"

View File

@@ -1,20 +1,20 @@
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Core init file
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Core init file
'''

View File

@@ -1,20 +1,20 @@
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
GenMetaFile
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
GenMetaFile
'''

View File

@@ -93,7 +93,7 @@ class _ExprBase:
## IsCurrentOp
#
# @param OpList: option list
# @param OpList: option list
#
def IsCurrentOp(self, OpList):
self.SkipWhitespace()

View File

@@ -1,99 +1,99 @@
## @file
# This file is used to define common static strings and global data used by UPT
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
'''
GlobalData
'''
#
# The workspace directory
#
gWORKSPACE = '.'
#
# INF module directory
#
gINF_MODULE_DIR = "."
gINF_MODULE_NAME = ''
#
# the directory to holds upt related files
#
gUPT_DIR = r"Conf/upt/"
#
# Log file for invalid meta-data files during force removing
#
gINVALID_MODULE_FILE = gUPT_DIR + r"Invalid_Modules.log"
#
# File name for content zip file in the distribution
#
gCONTENT_FILE = "dist.content"
#
# File name for XML file in the distibution
#
gDESC_FILE = 'dist.pkg'
#
# Case Insensitive flag
#
gCASE_INSENSITIVE = ''
#
# All Files dictionary
#
gALL_FILES = {}
#
# Database instance
#
gDB = None
#
# list for files that are found in module level but not in INF files,
# items are (File, ModulePath), all these should be relative to $(WORKSPACE)
#
gMISS_FILE_IN_MODLIST = []
#
# Global Current Line
#
gINF_CURRENT_LINE = None
#
# Global pkg list
#
gWSPKG_LIST = []
#
# Flag used to take WARN as ERROR.
# By default, only ERROR message will break the tools execution.
#
gWARNING_AS_ERROR = False
#
# Used to specify the temp directory to hold the unpacked distribution files
#
gUNPACK_DIR = None
#
# Flag used to mark whether the INF file is Binary INF or not.
#
gIS_BINARY_INF = False
#
# Used by Library instance parser
# {FilePath: FileObj}
#
## @file
# This file is used to define common static strings and global data used by UPT
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
'''
GlobalData
'''
#
# The workspace directory
#
gWORKSPACE = '.'
#
# INF module directory
#
gINF_MODULE_DIR = "."
gINF_MODULE_NAME = ''
#
# the directory to holds upt related files
#
gUPT_DIR = r"Conf/upt/"
#
# Log file for invalid meta-data files during force removing
#
gINVALID_MODULE_FILE = gUPT_DIR + r"Invalid_Modules.log"
#
# File name for content zip file in the distribution
#
gCONTENT_FILE = "dist.content"
#
# File name for XML file in the distibution
#
gDESC_FILE = 'dist.pkg'
#
# Case Insensitive flag
#
gCASE_INSENSITIVE = ''
#
# All Files dictionary
#
gALL_FILES = {}
#
# Database instance
#
gDB = None
#
# list for files that are found in module level but not in INF files,
# items are (File, ModulePath), all these should be relative to $(WORKSPACE)
#
gMISS_FILE_IN_MODLIST = []
#
# Global Current Line
#
gINF_CURRENT_LINE = None
#
# Global pkg list
#
gWSPKG_LIST = []
#
# Flag used to take WARN as ERROR.
# By default, only ERROR message will break the tools execution.
#
gWARNING_AS_ERROR = False
#
# Used to specify the temp directory to hold the unpacked distribution files
#
gUNPACK_DIR = None
#
# Flag used to mark whether the INF file is Binary INF or not.
#
gIS_BINARY_INF = False
#
# Used by Library instance parser
# {FilePath: FileObj}
#
gLIBINSTANCEDICT = {}

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +1,20 @@
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Xml
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Xml
'''

View File

@@ -1,20 +1,20 @@
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Library
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Library
'''

View File

@@ -1,325 +1,325 @@
## @file
# This file implements the log mechanism for Python tools.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Logger
'''
## Import modules
from sys import argv
from sys import stdout
from sys import stderr
import os.path
from os import remove
from logging import getLogger
from logging import Formatter
from logging import StreamHandler
from logging import FileHandler
from traceback import extract_stack
from Logger.ToolError import FatalError
from Logger.ToolError import WARNING_AS_ERROR
from Logger.ToolError import gERROR_MESSAGE
from Logger.ToolError import UNKNOWN_ERROR
from Library import GlobalData
#
# Log level constants
#
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 = 20
WARN = 30
QUIET = 40
QUIET_1 = 41
ERROR = 50
SILENT = 60
IS_RAISE_ERROR = True
SUPRESS_ERROR = False
#
# Tool name
#
_TOOL_NAME = os.path.basename(argv[0])
#
# For validation purpose
#
_LOG_LEVELS = [DEBUG_0, DEBUG_1, DEBUG_2, DEBUG_3, DEBUG_4, DEBUG_5, DEBUG_6, \
DEBUG_7, DEBUG_8, DEBUG_9, VERBOSE, WARN, INFO, ERROR, QUIET, \
QUIET_1, SILENT]
#
# For DEBUG level (All DEBUG_0~9 are applicable)
#
_DEBUG_LOGGER = getLogger("tool_debug")
_DEBUG_FORMATTER = Formatter("[%(asctime)s.%(msecs)d]: %(message)s", \
datefmt="%H:%M:%S")
#
# For VERBOSE, INFO, WARN level
#
_INFO_LOGGER = getLogger("tool_info")
_INFO_FORMATTER = Formatter("%(message)s")
#
# For ERROR level
#
_ERROR_LOGGER = getLogger("tool_error")
_ERROR_FORMATTER = Formatter("%(message)s")
#
# String templates for ERROR/WARN/DEBUG log message
#
_ERROR_MESSAGE_TEMPLATE = \
('\n\n%(tool)s...\n%(file)s(%(line)s): error %(errorcode)04X: %(msg)s\n\t%(extra)s')
__ERROR_MESSAGE_TEMPLATE_WITHOUT_FILE = \
'\n\n%(tool)s...\n : error %(errorcode)04X: %(msg)s\n\t%(extra)s'
_WARNING_MESSAGE_TEMPLATE = '%(tool)s...\n%(file)s(%(line)s): warning: %(msg)s'
_WARNING_MESSAGE_TEMPLATE_WITHOUT_FILE = '%(tool)s: : warning: %(msg)s'
_DEBUG_MESSAGE_TEMPLATE = '%(file)s(%(line)s): debug: \n %(msg)s'
#
# Log INFO message
#
#Info = _INFO_LOGGER.info
def Info(msg, *args, **kwargs):
_INFO_LOGGER.info(msg, *args, **kwargs)
#
# Log information which should be always put out
#
def Quiet(msg, *args, **kwargs):
_ERROR_LOGGER.error(msg, *args, **kwargs)
## Log debug message
#
# @param Level DEBUG level (DEBUG0~9)
# @param Message Debug information
# @param ExtraData More information associated with "Message"
#
def Debug(Level, Message, ExtraData=None):
if _DEBUG_LOGGER.level > Level:
return
if Level > DEBUG_9:
return
#
# Find out the caller method information
#
CallerStack = extract_stack()[-2]
TemplateDict = {
"file" : CallerStack[0],
"line" : CallerStack[1],
"msg" : Message,
}
if ExtraData != None:
LogText = _DEBUG_MESSAGE_TEMPLATE % TemplateDict + "\n %s" % ExtraData
else:
LogText = _DEBUG_MESSAGE_TEMPLATE % TemplateDict
_DEBUG_LOGGER.log(Level, LogText)
## Log verbose message
#
# @param Message Verbose information
#
def Verbose(Message):
return _INFO_LOGGER.log(VERBOSE, Message)
## Log warning message
#
# Warning messages are those which might be wrong but won't fail the tool.
#
# @param ToolName The name of the tool. If not given, the name of caller
# method will be used.
# @param Message Warning information
# @param File The name of file which caused the warning.
# @param Line The line number in the "File" which caused the warning.
# @param ExtraData More information associated with "Message"
#
def Warn(ToolName, Message, File=None, Line=None, ExtraData=None):
if _INFO_LOGGER.level > WARN:
return
#
# if no tool name given, use caller's source file name as tool name
#
if ToolName == None or ToolName == "":
ToolName = os.path.basename(extract_stack()[-2][0])
if Line == None:
Line = "..."
else:
Line = "%d" % Line
TemplateDict = {
"tool" : ToolName,
"file" : File,
"line" : Line,
"msg" : Message,
}
if File != None:
LogText = _WARNING_MESSAGE_TEMPLATE % TemplateDict
else:
LogText = _WARNING_MESSAGE_TEMPLATE_WITHOUT_FILE % TemplateDict
if ExtraData != None:
LogText += "\n %s" % ExtraData
_INFO_LOGGER.log(WARN, LogText)
#
# Raise an execption if indicated
#
if GlobalData.gWARNING_AS_ERROR == True:
raise FatalError(WARNING_AS_ERROR)
## Log ERROR message
#
# Once an error messages is logged, the tool's execution will be broken by
# raising an execption. If you don't want to break the execution later, you
# can give "RaiseError" with "False" value.
#
# @param ToolName The name of the tool. If not given, the name of caller
# method will be used.
# @param ErrorCode The error code
# @param Message Warning information
# @param File The name of file which caused the error.
# @param Line The line number in the "File" which caused the warning.
# @param ExtraData More information associated with "Message"
# @param RaiseError Raise an exception to break the tool's executuion if
# it's True. This is the default behavior.
#
def Error(ToolName, ErrorCode, Message=None, File=None, Line=None, \
ExtraData=None, RaiseError=IS_RAISE_ERROR):
if ToolName:
pass
if Line == None:
Line = "..."
else:
Line = "%d" % Line
if Message == None:
if ErrorCode in gERROR_MESSAGE:
Message = gERROR_MESSAGE[ErrorCode]
else:
Message = gERROR_MESSAGE[UNKNOWN_ERROR]
if ExtraData == None:
ExtraData = ""
TemplateDict = {
"tool" : _TOOL_NAME,
"file" : File,
"line" : Line,
"errorcode" : ErrorCode,
"msg" : Message,
"extra" : ExtraData
}
if File != None:
LogText = _ERROR_MESSAGE_TEMPLATE % TemplateDict
else:
LogText = __ERROR_MESSAGE_TEMPLATE_WITHOUT_FILE % TemplateDict
if not SUPRESS_ERROR:
_ERROR_LOGGER.log(ERROR, LogText)
if RaiseError:
raise FatalError(ErrorCode)
## Initialize log system
#
def Initialize():
#
# Since we use different format to log different levels of message into
# different place (stdout or stderr), we have to use different "Logger"
# objects to do this.
#
# For DEBUG level (All DEBUG_0~9 are applicable)
_DEBUG_LOGGER.setLevel(INFO)
_DebugChannel = StreamHandler(stdout)
_DebugChannel.setFormatter(_DEBUG_FORMATTER)
_DEBUG_LOGGER.addHandler(_DebugChannel)
#
# For VERBOSE, INFO, WARN level
#
_INFO_LOGGER.setLevel(INFO)
_InfoChannel = StreamHandler(stdout)
_InfoChannel.setFormatter(_INFO_FORMATTER)
_INFO_LOGGER.addHandler(_InfoChannel)
#
# For ERROR level
#
_ERROR_LOGGER.setLevel(INFO)
_ErrorCh = StreamHandler(stderr)
_ErrorCh.setFormatter(_ERROR_FORMATTER)
_ERROR_LOGGER.addHandler(_ErrorCh)
## Set log level
#
# @param Level One of log level in _LogLevel
#
def SetLevel(Level):
if Level not in _LOG_LEVELS:
Info("Not supported log level (%d). Use default level instead." % \
Level)
Level = INFO
_DEBUG_LOGGER.setLevel(Level)
_INFO_LOGGER.setLevel(Level)
_ERROR_LOGGER.setLevel(Level)
## Get current log level
#
def GetLevel():
return _INFO_LOGGER.getEffectiveLevel()
## Raise up warning as error
#
def SetWarningAsError():
GlobalData.gWARNING_AS_ERROR = True
## Specify a file to store the log message as well as put on console
#
# @param LogFile The file path used to store the log message
#
def SetLogFile(LogFile):
if os.path.exists(LogFile):
remove(LogFile)
_Ch = FileHandler(LogFile)
_Ch.setFormatter(_DEBUG_FORMATTER)
_DEBUG_LOGGER.addHandler(_Ch)
_Ch = FileHandler(LogFile)
_Ch.setFormatter(_INFO_FORMATTER)
_INFO_LOGGER.addHandler(_Ch)
_Ch = FileHandler(LogFile)
_Ch.setFormatter(_ERROR_FORMATTER)
_ERROR_LOGGER.addHandler(_Ch)
## @file
# This file implements the log mechanism for Python tools.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Logger
'''
## Import modules
from sys import argv
from sys import stdout
from sys import stderr
import os.path
from os import remove
from logging import getLogger
from logging import Formatter
from logging import StreamHandler
from logging import FileHandler
from traceback import extract_stack
from Logger.ToolError import FatalError
from Logger.ToolError import WARNING_AS_ERROR
from Logger.ToolError import gERROR_MESSAGE
from Logger.ToolError import UNKNOWN_ERROR
from Library import GlobalData
#
# Log level constants
#
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 = 20
WARN = 30
QUIET = 40
QUIET_1 = 41
ERROR = 50
SILENT = 60
IS_RAISE_ERROR = True
SUPRESS_ERROR = False
#
# Tool name
#
_TOOL_NAME = os.path.basename(argv[0])
#
# For validation purpose
#
_LOG_LEVELS = [DEBUG_0, DEBUG_1, DEBUG_2, DEBUG_3, DEBUG_4, DEBUG_5, DEBUG_6, \
DEBUG_7, DEBUG_8, DEBUG_9, VERBOSE, WARN, INFO, ERROR, QUIET, \
QUIET_1, SILENT]
#
# For DEBUG level (All DEBUG_0~9 are applicable)
#
_DEBUG_LOGGER = getLogger("tool_debug")
_DEBUG_FORMATTER = Formatter("[%(asctime)s.%(msecs)d]: %(message)s", \
datefmt="%H:%M:%S")
#
# For VERBOSE, INFO, WARN level
#
_INFO_LOGGER = getLogger("tool_info")
_INFO_FORMATTER = Formatter("%(message)s")
#
# For ERROR level
#
_ERROR_LOGGER = getLogger("tool_error")
_ERROR_FORMATTER = Formatter("%(message)s")
#
# String templates for ERROR/WARN/DEBUG log message
#
_ERROR_MESSAGE_TEMPLATE = \
('\n\n%(tool)s...\n%(file)s(%(line)s): error %(errorcode)04X: %(msg)s\n\t%(extra)s')
__ERROR_MESSAGE_TEMPLATE_WITHOUT_FILE = \
'\n\n%(tool)s...\n : error %(errorcode)04X: %(msg)s\n\t%(extra)s'
_WARNING_MESSAGE_TEMPLATE = '%(tool)s...\n%(file)s(%(line)s): warning: %(msg)s'
_WARNING_MESSAGE_TEMPLATE_WITHOUT_FILE = '%(tool)s: : warning: %(msg)s'
_DEBUG_MESSAGE_TEMPLATE = '%(file)s(%(line)s): debug: \n %(msg)s'
#
# Log INFO message
#
#Info = _INFO_LOGGER.info
def Info(msg, *args, **kwargs):
_INFO_LOGGER.info(msg, *args, **kwargs)
#
# Log information which should be always put out
#
def Quiet(msg, *args, **kwargs):
_ERROR_LOGGER.error(msg, *args, **kwargs)
## Log debug message
#
# @param Level DEBUG level (DEBUG0~9)
# @param Message Debug information
# @param ExtraData More information associated with "Message"
#
def Debug(Level, Message, ExtraData=None):
if _DEBUG_LOGGER.level > Level:
return
if Level > DEBUG_9:
return
#
# Find out the caller method information
#
CallerStack = extract_stack()[-2]
TemplateDict = {
"file" : CallerStack[0],
"line" : CallerStack[1],
"msg" : Message,
}
if ExtraData != None:
LogText = _DEBUG_MESSAGE_TEMPLATE % TemplateDict + "\n %s" % ExtraData
else:
LogText = _DEBUG_MESSAGE_TEMPLATE % TemplateDict
_DEBUG_LOGGER.log(Level, LogText)
## Log verbose message
#
# @param Message Verbose information
#
def Verbose(Message):
return _INFO_LOGGER.log(VERBOSE, Message)
## Log warning message
#
# Warning messages are those which might be wrong but won't fail the tool.
#
# @param ToolName The name of the tool. If not given, the name of caller
# method will be used.
# @param Message Warning information
# @param File The name of file which caused the warning.
# @param Line The line number in the "File" which caused the warning.
# @param ExtraData More information associated with "Message"
#
def Warn(ToolName, Message, File=None, Line=None, ExtraData=None):
if _INFO_LOGGER.level > WARN:
return
#
# if no tool name given, use caller's source file name as tool name
#
if ToolName == None or ToolName == "":
ToolName = os.path.basename(extract_stack()[-2][0])
if Line == None:
Line = "..."
else:
Line = "%d" % Line
TemplateDict = {
"tool" : ToolName,
"file" : File,
"line" : Line,
"msg" : Message,
}
if File != None:
LogText = _WARNING_MESSAGE_TEMPLATE % TemplateDict
else:
LogText = _WARNING_MESSAGE_TEMPLATE_WITHOUT_FILE % TemplateDict
if ExtraData != None:
LogText += "\n %s" % ExtraData
_INFO_LOGGER.log(WARN, LogText)
#
# Raise an execption if indicated
#
if GlobalData.gWARNING_AS_ERROR == True:
raise FatalError(WARNING_AS_ERROR)
## Log ERROR message
#
# Once an error messages is logged, the tool's execution will be broken by
# raising an execption. If you don't want to break the execution later, you
# can give "RaiseError" with "False" value.
#
# @param ToolName The name of the tool. If not given, the name of caller
# method will be used.
# @param ErrorCode The error code
# @param Message Warning information
# @param File The name of file which caused the error.
# @param Line The line number in the "File" which caused the warning.
# @param ExtraData More information associated with "Message"
# @param RaiseError Raise an exception to break the tool's executuion if
# it's True. This is the default behavior.
#
def Error(ToolName, ErrorCode, Message=None, File=None, Line=None, \
ExtraData=None, RaiseError=IS_RAISE_ERROR):
if ToolName:
pass
if Line == None:
Line = "..."
else:
Line = "%d" % Line
if Message == None:
if ErrorCode in gERROR_MESSAGE:
Message = gERROR_MESSAGE[ErrorCode]
else:
Message = gERROR_MESSAGE[UNKNOWN_ERROR]
if ExtraData == None:
ExtraData = ""
TemplateDict = {
"tool" : _TOOL_NAME,
"file" : File,
"line" : Line,
"errorcode" : ErrorCode,
"msg" : Message,
"extra" : ExtraData
}
if File != None:
LogText = _ERROR_MESSAGE_TEMPLATE % TemplateDict
else:
LogText = __ERROR_MESSAGE_TEMPLATE_WITHOUT_FILE % TemplateDict
if not SUPRESS_ERROR:
_ERROR_LOGGER.log(ERROR, LogText)
if RaiseError:
raise FatalError(ErrorCode)
## Initialize log system
#
def Initialize():
#
# Since we use different format to log different levels of message into
# different place (stdout or stderr), we have to use different "Logger"
# objects to do this.
#
# For DEBUG level (All DEBUG_0~9 are applicable)
_DEBUG_LOGGER.setLevel(INFO)
_DebugChannel = StreamHandler(stdout)
_DebugChannel.setFormatter(_DEBUG_FORMATTER)
_DEBUG_LOGGER.addHandler(_DebugChannel)
#
# For VERBOSE, INFO, WARN level
#
_INFO_LOGGER.setLevel(INFO)
_InfoChannel = StreamHandler(stdout)
_InfoChannel.setFormatter(_INFO_FORMATTER)
_INFO_LOGGER.addHandler(_InfoChannel)
#
# For ERROR level
#
_ERROR_LOGGER.setLevel(INFO)
_ErrorCh = StreamHandler(stderr)
_ErrorCh.setFormatter(_ERROR_FORMATTER)
_ERROR_LOGGER.addHandler(_ErrorCh)
## Set log level
#
# @param Level One of log level in _LogLevel
#
def SetLevel(Level):
if Level not in _LOG_LEVELS:
Info("Not supported log level (%d). Use default level instead." % \
Level)
Level = INFO
_DEBUG_LOGGER.setLevel(Level)
_INFO_LOGGER.setLevel(Level)
_ERROR_LOGGER.setLevel(Level)
## Get current log level
#
def GetLevel():
return _INFO_LOGGER.getEffectiveLevel()
## Raise up warning as error
#
def SetWarningAsError():
GlobalData.gWARNING_AS_ERROR = True
## Specify a file to store the log message as well as put on console
#
# @param LogFile The file path used to store the log message
#
def SetLogFile(LogFile):
if os.path.exists(LogFile):
remove(LogFile)
_Ch = FileHandler(LogFile)
_Ch.setFormatter(_DEBUG_FORMATTER)
_DEBUG_LOGGER.addHandler(_Ch)
_Ch = FileHandler(LogFile)
_Ch.setFormatter(_INFO_FORMATTER)
_INFO_LOGGER.addHandler(_Ch)
_Ch = FileHandler(LogFile)
_Ch.setFormatter(_ERROR_FORMATTER)
_ERROR_LOGGER.addHandler(_Ch)

View File

@@ -1,177 +1,177 @@
## @file
# Standardized Error Hanlding infrastructures.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
ToolError
'''
import Logger.StringTable as ST
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_NOT_FOUND = 14
FILE_TYPE_MISMATCH = 15
FILE_CASE_MISMATCH = 16
FILE_DUPLICATED = 17
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_RETRIEVE_FAILURE = 0x5005
ATTRIBUTE_UNKNOWN_ERROR = 0x5FFF
ATTRIBUTE_RETRIEVE_FAILURE = 0x5F00
IO_NOT_READY = 0x6000
IO_BUSY = 0x6001
IO_TIMEOUT = 0x6002
IO_UNKNOWN_ERROR = 0x6FFF
COMMAND_FAILURE = 0x7000
CODE_ERROR = 0xC0DE
AUTOGEN_ERROR = 0xF000
PARSER_ERROR = 0xF001
BUILD_ERROR = 0xF002
GENFDS_ERROR = 0xF003
ECC_ERROR = 0xF004
EOT_ERROR = 0xF005
DDC_ERROR = 0xF009
WARNING_AS_ERROR = 0xF006
MIGRATION_ERROR = 0xF010
EDK1_INF_ERROR = 0xF011
ABORT_ERROR = 0xFFFE
UNKNOWN_ERROR = 0xFFFF
UPT_ALREADY_INSTALLED_ERROR = 0xD000
UPT_ENVIRON_MISSING_ERROR = 0xD001
UPT_REPKG_ERROR = 0xD002
UPT_ALREADY_RUNNING_ERROR = 0xD003
UPT_MUL_DEC_ERROR = 0xD004
UPT_DB_UPDATE_ERROR = 0xD005
UPT_INI_PARSE_ERROR = 0xE000
## Error message of each error code
#
gERROR_MESSAGE = {
FILE_NOT_FOUND : ST.ERR_FILE_NOT_FOUND,
FILE_OPEN_FAILURE : ST.ERR_FILE_OPEN_FAILURE,
FILE_WRITE_FAILURE : ST.ERR_FILE_WRITE_FAILURE,
FILE_PARSE_FAILURE : ST.ERR_FILE_PARSE_FAILURE,
FILE_READ_FAILURE : ST.ERR_FILE_READ_FAILURE,
FILE_CREATE_FAILURE : ST.ERR_FILE_CREATE_FAILURE,
FILE_CHECKSUM_FAILURE : ST.ERR_FILE_CHECKSUM_FAILURE,
FILE_COMPRESS_FAILURE : ST.ERR_FILE_COMPRESS_FAILURE,
FILE_DECOMPRESS_FAILURE : ST.ERR_FILE_DECOMPRESS_FAILURE,
FILE_MOVE_FAILURE : ST.ERR_FILE_MOVE_FAILURE,
FILE_DELETE_FAILURE : ST.ERR_FILE_DELETE_FAILURE,
FILE_COPY_FAILURE : ST.ERR_FILE_COPY_FAILURE,
FILE_POSITIONING_FAILURE: ST.ERR_FILE_POSITIONING_FAILURE,
FILE_ALREADY_EXIST : ST.ERR_FILE_ALREADY_EXIST,
FILE_TYPE_MISMATCH : ST.ERR_FILE_TYPE_MISMATCH ,
FILE_CASE_MISMATCH : ST.ERR_FILE_CASE_MISMATCH,
FILE_DUPLICATED : ST.ERR_FILE_DUPLICATED,
FILE_UNKNOWN_ERROR : ST.ERR_FILE_UNKNOWN_ERROR,
OPTION_UNKNOWN : ST.ERR_OPTION_UNKNOWN,
OPTION_MISSING : ST.ERR_OPTION_MISSING,
OPTION_CONFLICT : ST.ERR_OPTION_CONFLICT,
OPTION_VALUE_INVALID : ST.ERR_OPTION_VALUE_INVALID,
OPTION_DEPRECATED : ST.ERR_OPTION_DEPRECATED,
OPTION_NOT_SUPPORTED : ST.ERR_OPTION_NOT_SUPPORTED,
OPTION_UNKNOWN_ERROR : ST.ERR_OPTION_UNKNOWN_ERROR,
PARAMETER_INVALID : ST.ERR_PARAMETER_INVALID,
PARAMETER_MISSING : ST.ERR_PARAMETER_MISSING,
PARAMETER_UNKNOWN_ERROR : ST.ERR_PARAMETER_UNKNOWN_ERROR,
FORMAT_INVALID : ST.ERR_FORMAT_INVALID,
FORMAT_NOT_SUPPORTED : ST.ERR_FORMAT_NOT_SUPPORTED,
FORMAT_UNKNOWN : ST.ERR_FORMAT_UNKNOWN,
FORMAT_UNKNOWN_ERROR : ST.ERR_FORMAT_UNKNOWN_ERROR,
RESOURCE_NOT_AVAILABLE : ST.ERR_RESOURCE_NOT_AVAILABLE,
RESOURCE_ALLOCATE_FAILURE : ST.ERR_RESOURCE_ALLOCATE_FAILURE,
RESOURCE_FULL : ST.ERR_RESOURCE_FULL,
RESOURCE_OVERFLOW : ST.ERR_RESOURCE_OVERFLOW,
RESOURCE_UNDERRUN : ST.ERR_RESOURCE_UNDERRUN,
RESOURCE_UNKNOWN_ERROR : ST.ERR_RESOURCE_UNKNOWN_ERROR,
ATTRIBUTE_NOT_AVAILABLE : ST.ERR_ATTRIBUTE_NOT_AVAILABLE,
ATTRIBUTE_RETRIEVE_FAILURE : ST.ERR_ATTRIBUTE_RETRIEVE_FAILURE,
ATTRIBUTE_SET_FAILURE : ST.ERR_ATTRIBUTE_SET_FAILURE,
ATTRIBUTE_UPDATE_FAILURE: ST.ERR_ATTRIBUTE_UPDATE_FAILURE,
ATTRIBUTE_ACCESS_DENIED : ST.ERR_ATTRIBUTE_ACCESS_DENIED,
ATTRIBUTE_UNKNOWN_ERROR : ST.ERR_ATTRIBUTE_UNKNOWN_ERROR,
COMMAND_FAILURE : ST.ERR_COMMAND_FAILURE,
IO_NOT_READY : ST.ERR_IO_NOT_READY,
IO_BUSY : ST.ERR_IO_BUSY,
IO_TIMEOUT : ST.ERR_IO_TIMEOUT,
IO_UNKNOWN_ERROR : ST.ERR_IO_UNKNOWN_ERROR,
UNKNOWN_ERROR : ST.ERR_UNKNOWN_ERROR,
UPT_ALREADY_INSTALLED_ERROR : ST.ERR_UPT_ALREADY_INSTALLED_ERROR,
UPT_ENVIRON_MISSING_ERROR : ST.ERR_UPT_ENVIRON_MISSING_ERROR,
UPT_REPKG_ERROR : ST.ERR_UPT_REPKG_ERROR,
UPT_ALREADY_RUNNING_ERROR : ST.ERR_UPT_ALREADY_RUNNING_ERROR,
UPT_MUL_DEC_ERROR : ST.ERR_MUL_DEC_ERROR,
UPT_INI_PARSE_ERROR : ST.ERR_UPT_INI_PARSE_ERROR,
}
## Exception indicating a fatal error
#
class FatalError(Exception):
pass
## @file
# Standardized Error Hanlding infrastructures.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
ToolError
'''
import Logger.StringTable as ST
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_NOT_FOUND = 14
FILE_TYPE_MISMATCH = 15
FILE_CASE_MISMATCH = 16
FILE_DUPLICATED = 17
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_RETRIEVE_FAILURE = 0x5005
ATTRIBUTE_UNKNOWN_ERROR = 0x5FFF
ATTRIBUTE_RETRIEVE_FAILURE = 0x5F00
IO_NOT_READY = 0x6000
IO_BUSY = 0x6001
IO_TIMEOUT = 0x6002
IO_UNKNOWN_ERROR = 0x6FFF
COMMAND_FAILURE = 0x7000
CODE_ERROR = 0xC0DE
AUTOGEN_ERROR = 0xF000
PARSER_ERROR = 0xF001
BUILD_ERROR = 0xF002
GENFDS_ERROR = 0xF003
ECC_ERROR = 0xF004
EOT_ERROR = 0xF005
DDC_ERROR = 0xF009
WARNING_AS_ERROR = 0xF006
MIGRATION_ERROR = 0xF010
EDK1_INF_ERROR = 0xF011
ABORT_ERROR = 0xFFFE
UNKNOWN_ERROR = 0xFFFF
UPT_ALREADY_INSTALLED_ERROR = 0xD000
UPT_ENVIRON_MISSING_ERROR = 0xD001
UPT_REPKG_ERROR = 0xD002
UPT_ALREADY_RUNNING_ERROR = 0xD003
UPT_MUL_DEC_ERROR = 0xD004
UPT_DB_UPDATE_ERROR = 0xD005
UPT_INI_PARSE_ERROR = 0xE000
## Error message of each error code
#
gERROR_MESSAGE = {
FILE_NOT_FOUND : ST.ERR_FILE_NOT_FOUND,
FILE_OPEN_FAILURE : ST.ERR_FILE_OPEN_FAILURE,
FILE_WRITE_FAILURE : ST.ERR_FILE_WRITE_FAILURE,
FILE_PARSE_FAILURE : ST.ERR_FILE_PARSE_FAILURE,
FILE_READ_FAILURE : ST.ERR_FILE_READ_FAILURE,
FILE_CREATE_FAILURE : ST.ERR_FILE_CREATE_FAILURE,
FILE_CHECKSUM_FAILURE : ST.ERR_FILE_CHECKSUM_FAILURE,
FILE_COMPRESS_FAILURE : ST.ERR_FILE_COMPRESS_FAILURE,
FILE_DECOMPRESS_FAILURE : ST.ERR_FILE_DECOMPRESS_FAILURE,
FILE_MOVE_FAILURE : ST.ERR_FILE_MOVE_FAILURE,
FILE_DELETE_FAILURE : ST.ERR_FILE_DELETE_FAILURE,
FILE_COPY_FAILURE : ST.ERR_FILE_COPY_FAILURE,
FILE_POSITIONING_FAILURE: ST.ERR_FILE_POSITIONING_FAILURE,
FILE_ALREADY_EXIST : ST.ERR_FILE_ALREADY_EXIST,
FILE_TYPE_MISMATCH : ST.ERR_FILE_TYPE_MISMATCH ,
FILE_CASE_MISMATCH : ST.ERR_FILE_CASE_MISMATCH,
FILE_DUPLICATED : ST.ERR_FILE_DUPLICATED,
FILE_UNKNOWN_ERROR : ST.ERR_FILE_UNKNOWN_ERROR,
OPTION_UNKNOWN : ST.ERR_OPTION_UNKNOWN,
OPTION_MISSING : ST.ERR_OPTION_MISSING,
OPTION_CONFLICT : ST.ERR_OPTION_CONFLICT,
OPTION_VALUE_INVALID : ST.ERR_OPTION_VALUE_INVALID,
OPTION_DEPRECATED : ST.ERR_OPTION_DEPRECATED,
OPTION_NOT_SUPPORTED : ST.ERR_OPTION_NOT_SUPPORTED,
OPTION_UNKNOWN_ERROR : ST.ERR_OPTION_UNKNOWN_ERROR,
PARAMETER_INVALID : ST.ERR_PARAMETER_INVALID,
PARAMETER_MISSING : ST.ERR_PARAMETER_MISSING,
PARAMETER_UNKNOWN_ERROR : ST.ERR_PARAMETER_UNKNOWN_ERROR,
FORMAT_INVALID : ST.ERR_FORMAT_INVALID,
FORMAT_NOT_SUPPORTED : ST.ERR_FORMAT_NOT_SUPPORTED,
FORMAT_UNKNOWN : ST.ERR_FORMAT_UNKNOWN,
FORMAT_UNKNOWN_ERROR : ST.ERR_FORMAT_UNKNOWN_ERROR,
RESOURCE_NOT_AVAILABLE : ST.ERR_RESOURCE_NOT_AVAILABLE,
RESOURCE_ALLOCATE_FAILURE : ST.ERR_RESOURCE_ALLOCATE_FAILURE,
RESOURCE_FULL : ST.ERR_RESOURCE_FULL,
RESOURCE_OVERFLOW : ST.ERR_RESOURCE_OVERFLOW,
RESOURCE_UNDERRUN : ST.ERR_RESOURCE_UNDERRUN,
RESOURCE_UNKNOWN_ERROR : ST.ERR_RESOURCE_UNKNOWN_ERROR,
ATTRIBUTE_NOT_AVAILABLE : ST.ERR_ATTRIBUTE_NOT_AVAILABLE,
ATTRIBUTE_RETRIEVE_FAILURE : ST.ERR_ATTRIBUTE_RETRIEVE_FAILURE,
ATTRIBUTE_SET_FAILURE : ST.ERR_ATTRIBUTE_SET_FAILURE,
ATTRIBUTE_UPDATE_FAILURE: ST.ERR_ATTRIBUTE_UPDATE_FAILURE,
ATTRIBUTE_ACCESS_DENIED : ST.ERR_ATTRIBUTE_ACCESS_DENIED,
ATTRIBUTE_UNKNOWN_ERROR : ST.ERR_ATTRIBUTE_UNKNOWN_ERROR,
COMMAND_FAILURE : ST.ERR_COMMAND_FAILURE,
IO_NOT_READY : ST.ERR_IO_NOT_READY,
IO_BUSY : ST.ERR_IO_BUSY,
IO_TIMEOUT : ST.ERR_IO_TIMEOUT,
IO_UNKNOWN_ERROR : ST.ERR_IO_UNKNOWN_ERROR,
UNKNOWN_ERROR : ST.ERR_UNKNOWN_ERROR,
UPT_ALREADY_INSTALLED_ERROR : ST.ERR_UPT_ALREADY_INSTALLED_ERROR,
UPT_ENVIRON_MISSING_ERROR : ST.ERR_UPT_ENVIRON_MISSING_ERROR,
UPT_REPKG_ERROR : ST.ERR_UPT_REPKG_ERROR,
UPT_ALREADY_RUNNING_ERROR : ST.ERR_UPT_ALREADY_RUNNING_ERROR,
UPT_MUL_DEC_ERROR : ST.ERR_MUL_DEC_ERROR,
UPT_INI_PARSE_ERROR : ST.ERR_UPT_INI_PARSE_ERROR,
}
## Exception indicating a fatal error
#
class FatalError(Exception):
pass

View File

@@ -1,20 +1,20 @@
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Xml
## @file
# Python 'Library' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# 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.
#
'''
Xml
'''

File diff suppressed because it is too large Load Diff

View File

@@ -1811,7 +1811,7 @@ class InfBuildData(ModuleBuildClassObject):
else:
Tool = ToolList[0]
ToolChain = "*_*_*_%s_FLAGS" % Tool
ToolChainFamily = ''
ToolChainFamily = 'MSFT' # Edk.x only support MSFT tool chain
#ignore not replaced macros in value
ValueList = GetSplitList(' ' + Value, '/D')
Dummy = ValueList[0]

View File

@@ -1,19 +1,19 @@
#
# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
#
# 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.
import sys
import locale
if sys.platform == "darwin":
DefaultLocal = locale.getdefaultlocale()[1]
if DefaultLocal is None:
DefaultLocal = 'UTF8'
sys.setdefaultencoding(DefaultLocal)
#
# Copyright (c) 2009 - 2010, Apple Inc. All rights reserved.<BR>
#
# 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.
import sys
import locale
if sys.platform == "darwin":
DefaultLocal = locale.getdefaultlocale()[1]
if DefaultLocal is None:
DefaultLocal = 'UTF8'
sys.setdefaultencoding(DefaultLocal)