Sync BaseTools Trunk (version r2518) to EDKII main trunk.

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


git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@13178 6f19259b-4bc3-4df7-8a09-765794883524
This commit is contained in:
lgao4
2012-04-10 07:18:20 +00:00
parent 09e4dbeb5c
commit 64b2609fcf
109 changed files with 1572 additions and 10912 deletions

View File

@@ -1,7 +1,7 @@
## @file
# GNU Make makefile for C tools build.
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2007 - 2012, 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
@@ -22,10 +22,7 @@ ifndef ARCH
ifeq ($(uname_m),x86_64)
ARCH=X64
endif
ifeq ($(uname_m),i386)
ARCH=IA32
endif
ifeq ($(uname_m),i686)
ifeq ($(patsubst i%86,IA32,$(uname_m)),IA32)
ARCH=IA32
endif
ifndef ARCH

View File

@@ -14,4 +14,4 @@
**/
#define __BUILD_VERSION "Build 2474"
#define __BUILD_VERSION "Build 2518"

View File

@@ -3,7 +3,7 @@
IFR is primarily consumed by the EFI presentation engine, and produced by EFI
internal application and drivers as well as all add-in card option-ROM drivers
Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2006 - 2012, 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
@@ -613,7 +613,7 @@ typedef union {
#define EFI_IFR_INCONSISTENT_IF_OP 0x11
#define EFI_IFR_EQ_ID_VAL_OP 0x12
#define EFI_IFR_EQ_ID_ID_OP 0x13
#define EFI_IFR_EQ_ID_LIST_OP 0x14
#define EFI_IFR_EQ_ID_VAL_LIST_OP 0x14
#define EFI_IFR_AND_OP 0x15
#define EFI_IFR_OR_OP 0x16
#define EFI_IFR_NOT_OP 0x17

View File

@@ -1,7 +1,7 @@
## @file
# Windows makefile for 'LzmaCompress' module build.
#
# Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2009 - 2012, 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
@@ -24,7 +24,8 @@ OBJECTS = \
$(SDK_C)/LzmaDec.o \
$(SDK_C)/LzmaEnc.o \
$(SDK_C)/7zFile.o \
$(SDK_C)/7zStream.o
$(SDK_C)/7zStream.o \
$(SDK_C)/Bra86.o
include $(MAKEROOT)/Makefiles/app.makefile

View File

@@ -5,7 +5,7 @@
LzmaUtil.c -- Test application for LZMA compression
2008-11-23 : Igor Pavlov : Public domain
Copyright (c) 2006 - 2009, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2006 - 2012, 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
@@ -27,8 +27,17 @@
#include "Sdk/C/7zVersion.h"
#include "Sdk/C/LzmaDec.h"
#include "Sdk/C/LzmaEnc.h"
#include "Sdk/C/Bra.h"
#include "CommonLib.h"
#define LZMA_HEADER_SIZE (LZMA_PROPS_SIZE + 8)
typedef enum {
NoConverter,
X86Converter,
MaxConverter
} CONVERTER_TYPE;
const char *kCantReadMessage = "Can not read input file";
const char *kCantWriteMessage = "Can not write output file";
const char *kCantAllocateMessage = "Can not allocate memory";
@@ -39,12 +48,13 @@ static void SzFree(void *p, void *address) { p = p; MyFree(address); }
static ISzAlloc g_Alloc = { SzAlloc, SzFree };
static Bool mQuietMode = False;
static CONVERTER_TYPE mConType = NoConverter;
#define UTILITY_NAME "LzmaCompress"
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
#define UTILITY_MINOR_VERSION 2
#define INTEL_COPYRIGHT \
"Copyright (c) 2009, Intel Corporation. All rights reserved."
"Copyright (c) 2009-2012, Intel Corporation. All rights reserved."
void PrintHelp(char *buffer)
{
strcat(buffer,
@@ -54,6 +64,7 @@ void PrintHelp(char *buffer)
" -e: encode file\n"
" -d: decode file\n"
" -o FileName, --output FileName: specify the output filename\n"
" --f86: enable converter for x86 code\n"
" -v, --verbose: increase output messages\n"
" -q, --quiet: reduce output messages\n"
" --debug [0-9]: set debug level\n"
@@ -86,121 +97,151 @@ void PrintVersion(char *buffer)
sprintf (buffer, "%s Version %d.%d %s ", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION, __BUILD_VERSION);
}
#define IN_BUF_SIZE (1 << 16)
#define OUT_BUF_SIZE (1 << 16)
static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inStream,
UInt64 unpackSize)
static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize)
{
int thereIsSize = (unpackSize != (UInt64)(Int64)-1);
Byte inBuf[IN_BUF_SIZE];
Byte outBuf[OUT_BUF_SIZE];
size_t inPos = 0, inSize = 0, outPos = 0;
LzmaDec_Init(state);
for (;;)
SRes res;
size_t inSize = (size_t)fileSize;
Byte *inBuffer = 0;
Byte *outBuffer = 0;
Byte *filteredStream = 0;
size_t outSize;
CLzmaEncProps props;
LzmaEncProps_Init(&props);
LzmaEncProps_Normalize(&props);
if (inSize != 0) {
inBuffer = (Byte *)MyAlloc(inSize);
if (inBuffer == 0)
return SZ_ERROR_MEM;
} else {
return SZ_ERROR_INPUT_EOF;
}
if (SeqInStream_Read(inStream, inBuffer, inSize) != SZ_OK) {
res = SZ_ERROR_READ;
goto Done;
}
// we allocate 105% of original size + 64KB for output buffer
outSize = (size_t)fileSize / 20 * 21 + (1 << 16);
outBuffer = (Byte *)MyAlloc(outSize);
if (outBuffer == 0) {
res = SZ_ERROR_MEM;
goto Done;
}
{
if (inPos == inSize)
{
inSize = IN_BUF_SIZE;
RINOK(inStream->Read(inStream, inBuf, &inSize));
inPos = 0;
int i;
for (i = 0; i < 8; i++)
outBuffer[i + LZMA_PROPS_SIZE] = (Byte)(fileSize >> (8 * i));
}
if (mConType != NoConverter)
{
filteredStream = (Byte *)MyAlloc(inSize);
if (filteredStream == 0) {
res = SZ_ERROR_MEM;
goto Done;
}
{
SRes res;
SizeT inProcessed = inSize - inPos;
SizeT outProcessed = OUT_BUF_SIZE - outPos;
ELzmaFinishMode finishMode = LZMA_FINISH_ANY;
ELzmaStatus status;
if (thereIsSize && outProcessed > unpackSize)
memcpy(filteredStream, inBuffer, inSize);
if (mConType == X86Converter) {
{
outProcessed = (SizeT)unpackSize;
finishMode = LZMA_FINISH_END;
}
res = LzmaDec_DecodeToBuf(state, outBuf + outPos, &outProcessed,
inBuf + inPos, &inProcessed, finishMode, &status);
inPos += inProcessed;
outPos += outProcessed;
unpackSize -= outProcessed;
if (outStream)
if (outStream->Write(outStream, outBuf, outPos) != outPos)
return SZ_ERROR_WRITE;
outPos = 0;
if (res != SZ_OK || (thereIsSize && unpackSize == 0))
return res;
if (inProcessed == 0 && outProcessed == 0)
{
if (thereIsSize || status != LZMA_STATUS_FINISHED_WITH_MARK)
return SZ_ERROR_DATA;
return res;
UInt32 x86State;
x86_Convert_Init(x86State);
x86_Convert(filteredStream, (SizeT) inSize, 0, &x86State, 1);
}
}
}
}
static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream)
{
UInt64 unpackSize;
int i;
SRes res = 0;
{
size_t outSizeProcessed = outSize - LZMA_HEADER_SIZE;
size_t outPropsSize = LZMA_PROPS_SIZE;
res = LzmaEncode(outBuffer + LZMA_HEADER_SIZE, &outSizeProcessed,
mConType != NoConverter ? filteredStream : inBuffer, inSize,
&props, outBuffer, &outPropsSize, 0,
NULL, &g_Alloc, &g_Alloc);
if (res != SZ_OK)
goto Done;
CLzmaDec state;
outSize = LZMA_HEADER_SIZE + outSizeProcessed;
}
/* header: 5 bytes of LZMA properties and 8 bytes of uncompressed size */
unsigned char header[LZMA_PROPS_SIZE + 8];
if (outStream->Write(outStream, outBuffer, outSize) != outSize)
res = SZ_ERROR_WRITE;
/* Read and parse header */
Done:
MyFree(outBuffer);
MyFree(inBuffer);
MyFree(filteredStream);
RINOK(SeqInStream_Read(inStream, header, sizeof(header)));
unpackSize = 0;
for (i = 0; i < 8; i++)
unpackSize += (UInt64)header[LZMA_PROPS_SIZE + i] << (i * 8);
LzmaDec_Construct(&state);
RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc));
res = Decode2(&state, outStream, inStream, unpackSize);
LzmaDec_Free(&state, &g_Alloc);
return res;
}
static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize, char *rs)
static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize)
{
CLzmaEncHandle enc;
SRes res;
CLzmaEncProps props;
size_t inSize = (size_t)fileSize;
Byte *inBuffer = 0;
Byte *outBuffer = 0;
size_t outSize = 0;
size_t inSizePure;
ELzmaStatus status;
UInt64 outSize64 = 0;
rs = rs;
int i;
enc = LzmaEnc_Create(&g_Alloc);
if (enc == 0)
if (inSize < LZMA_HEADER_SIZE)
return SZ_ERROR_INPUT_EOF;
inBuffer = (Byte *)MyAlloc(inSize);
if (inBuffer == 0)
return SZ_ERROR_MEM;
LzmaEncProps_Init(&props);
res = LzmaEnc_SetProps(enc, &props);
if (res == SZ_OK)
{
Byte header[LZMA_PROPS_SIZE + 8];
size_t headerSize = LZMA_PROPS_SIZE;
int i;
res = LzmaEnc_WriteProperties(enc, header, &headerSize);
for (i = 0; i < 8; i++)
header[headerSize++] = (Byte)(fileSize >> (8 * i));
if (outStream->Write(outStream, header, headerSize) != headerSize)
res = SZ_ERROR_WRITE;
else
{
if (res == SZ_OK)
res = LzmaEnc_Encode(enc, outStream, inStream, NULL, &g_Alloc, &g_Alloc);
}
if (SeqInStream_Read(inStream, inBuffer, inSize) != SZ_OK) {
res = SZ_ERROR_READ;
goto Done;
}
LzmaEnc_Destroy(enc, &g_Alloc, &g_Alloc);
for (i = 0; i < 8; i++)
outSize64 += ((UInt64)inBuffer[LZMA_PROPS_SIZE + i]) << (i * 8);
outSize = (size_t)outSize64;
if (outSize != 0) {
outBuffer = (Byte *)MyAlloc(outSize);
if (outBuffer == 0) {
res = SZ_ERROR_MEM;
goto Done;
}
} else {
res = SZ_OK;
goto Done;
}
inSizePure = inSize - LZMA_HEADER_SIZE;
res = LzmaDecode(outBuffer, &outSize, inBuffer + LZMA_HEADER_SIZE, &inSizePure,
inBuffer, LZMA_PROPS_SIZE, LZMA_FINISH_END, &status, &g_Alloc);
if (res != SZ_OK)
goto Done;
if (mConType == X86Converter)
{
UInt32 x86State;
x86_Convert_Init(x86State);
x86_Convert(outBuffer, (SizeT) outSize, 0, &x86State, 0);
}
if (outStream->Write(outStream, outBuffer, outSize) != outSize)
res = SZ_ERROR_WRITE;
Done:
MyFree(outBuffer);
MyFree(inBuffer);
return res;
}
@@ -214,6 +255,7 @@ int main2(int numArgs, const char *args[], char *rs)
const char *inputFile = NULL;
const char *outputFile = "file.tmp";
int param;
UInt64 fileSize;
FileSeqInStream_CreateVTable(&inStream);
File_Construct(&inStream.file);
@@ -231,6 +273,8 @@ int main2(int numArgs, const char *args[], char *rs)
if (strcmp(args[param], "-e") == 0 || strcmp(args[param], "-d") == 0) {
encodeMode = (args[param][1] == 'e');
modeWasSet = True;
} else if (strcmp(args[param], "--f86") == 0) {
mConType = X86Converter;
} else if (strcmp(args[param], "-o") == 0 ||
strcmp(args[param], "--output") == 0) {
if (numArgs < (param + 2)) {
@@ -292,21 +336,21 @@ int main2(int numArgs, const char *args[], char *rs)
if (OutFile_Open(&outStream.file, outputFile) != 0)
return PrintError(rs, "Can not open output file");
File_GetLength(&inStream.file, &fileSize);
if (encodeMode)
{
UInt64 fileSize;
File_GetLength(&inStream.file, &fileSize);
if (!mQuietMode) {
printf("Encoding\n");
}
res = Encode(&outStream.s, &inStream.s, fileSize, rs);
res = Encode(&outStream.s, &inStream.s, fileSize);
}
else
{
if (!mQuietMode) {
printf("Decoding\n");
}
res = Decode(&outStream.s, &inStream.s);
res = Decode(&outStream.s, &inStream.s, fileSize);
}
File_Close(&outStream.file);

View File

@@ -0,0 +1,31 @@
@REM
@REM This script will exec LzmaCompress tool with --f86 option that enables converter for x86 code.
@REM
@REM Copyright (c) 2012, Intel Corporation. All rights reserved.<BR>
@REM This program and the accompanying materials
@REM are licensed and made available under the terms and conditions of the BSD License
@REM which accompanies this distribution. The full text of the license may be found at
@REM http://opensource.org/licenses/bsd-license.php
@REM
@REM THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
@REM WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@REM
@echo off
@setlocal
:Begin
if "%1"=="" goto End
if "%1"=="-e" (
set FLAG=--f86
)
if "%1"=="-d" (
set FLAG=--f86
)
set ARGS=%ARGS% %1
shift
goto Begin
:End
LzmaCompress %ARGS% %FLAG%
@echo on

View File

@@ -1,7 +1,7 @@
## @file
# Windows makefile for 'LzmaCompress' module build.
#
# Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2009 - 2012, 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
@@ -25,7 +25,17 @@ OBJECTS = \
$(SDK_C)\LzmaDec.obj \
$(SDK_C)\LzmaEnc.obj \
$(SDK_C)\7zFile.obj \
$(SDK_C)\7zStream.obj
$(SDK_C)\7zStream.obj \
$(SDK_C)\Bra86.obj
!INCLUDE ..\Makefiles\ms.app
all: $(BIN_PATH)\LzmaF86Compress.bat
$(BIN_PATH)\LzmaF86Compress.bat: LzmaF86Compress.bat
copy LzmaF86Compress.bat $(BIN_PATH)\LzmaF86Compress.bat /Y
cleanall: localCleanall
localCleanall:
del /f /q $(BIN_PATH)\LzmaF86Compress.bat > nul

View File

@@ -0,0 +1,60 @@
/* Bra.h -- Branch converters for executables
2008-10-04 : Igor Pavlov : Public domain */
#ifndef __BRA_H
#define __BRA_H
#include "Types.h"
/*
These functions convert relative addresses to absolute addresses
in CALL instructions to increase the compression ratio.
In:
data - data buffer
size - size of data
ip - current virtual Instruction Pinter (IP) value
state - state variable for x86 converter
encoding - 0 (for decoding), 1 (for encoding)
Out:
state - state variable for x86 converter
Returns:
The number of processed bytes. If you call these functions with multiple calls,
you must start next call with first byte after block of processed bytes.
Type Endian Alignment LookAhead
x86 little 1 4
ARMT little 2 2
ARM little 4 0
PPC big 4 0
SPARC big 4 0
IA64 little 16 0
size must be >= Alignment + LookAhead, if it's not last block.
If (size < Alignment + LookAhead), converter returns 0.
Example:
UInt32 ip = 0;
for ()
{
; size must be >= Alignment + LookAhead, if it's not last block
SizeT processed = Convert(data, size, ip, 1);
data += processed;
size -= processed;
ip += processed;
}
*/
#define x86_Convert_Init(state) { state = 0; }
SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding);
SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding);
#endif

View File

@@ -0,0 +1,85 @@
/* Bra86.c -- Converter for x86 code (BCJ)
2008-10-04 : Igor Pavlov : Public domain */
#include "Bra.h"
#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF)
const Byte kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0};
const Byte kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3};
SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding)
{
SizeT bufferPos = 0, prevPosT;
UInt32 prevMask = *state & 0x7;
if (size < 5)
return 0;
ip += 5;
prevPosT = (SizeT)0 - 1;
for (;;)
{
Byte *p = data + bufferPos;
Byte *limit = data + size - 4;
for (; p < limit; p++)
if ((*p & 0xFE) == 0xE8)
break;
bufferPos = (SizeT)(p - data);
if (p >= limit)
break;
prevPosT = bufferPos - prevPosT;
if (prevPosT > 3)
prevMask = 0;
else
{
prevMask = (prevMask << ((int)prevPosT - 1)) & 0x7;
if (prevMask != 0)
{
Byte b = p[4 - kMaskToBitNumber[prevMask]];
if (!kMaskToAllowedStatus[prevMask] || Test86MSByte(b))
{
prevPosT = bufferPos;
prevMask = ((prevMask << 1) & 0x7) | 1;
bufferPos++;
continue;
}
}
}
prevPosT = bufferPos;
if (Test86MSByte(p[4]))
{
UInt32 src = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]);
UInt32 dest;
for (;;)
{
Byte b;
int index;
if (encoding)
dest = (ip + (UInt32)bufferPos) + src;
else
dest = src - (ip + (UInt32)bufferPos);
if (prevMask == 0)
break;
index = kMaskToBitNumber[prevMask] * 8;
b = (Byte)(dest >> (24 - index));
if (!Test86MSByte(b))
break;
src = dest ^ ((1 << (32 - index)) - 1);
}
p[4] = (Byte)(~(((dest >> 24) & 1) - 1));
p[3] = (Byte)(dest >> 16);
p[2] = (Byte)(dest >> 8);
p[1] = (Byte)dest;
bufferPos += 5;
}
else
{
prevMask = ((prevMask << 1) & 0x7) | 1;
bufferPos++;
}
}
prevPosT = bufferPos - prevPosT;
*state = ((prevPosT > 3) ? 0 : ((prevMask << ((int)prevPosT - 1)) & 0x7));
return bufferPos;
}

View File

@@ -1,7 +1,7 @@
## @file
# Windows makefile for C tools build.
#
# Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2009 - 2012, 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
@@ -59,6 +59,7 @@ install: $(LIB_PATH) $(BIN_PATH)
@echo ######################
@-xcopy $(LIB_PATH)\*.lib $(SYS_LIB_PATH) /I /D /E /F /Y > NUL 2>&1
@-xcopy $(BIN_PATH)\*.exe $(SYS_BIN_PATH) /I /D /E /F /Y > NUL 2>&1
@-xcopy $(BIN_PATH)\*.bat $(SYS_BIN_PATH) /I /D /E /F /Y > NUL 2>&1
.PHONY: clean
clean:

View File

@@ -2,7 +2,7 @@
The definition of CFormPkg's member function
Copyright (c) 2004 - 2010, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2004 - 2012, 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
@@ -963,7 +963,7 @@ CIfrRecordInfoDB::CheckIdOpCode (
switch (OpCode) {
case EFI_IFR_EQ_ID_VAL_OP:
case EFI_IFR_EQ_ID_ID_OP:
case EFI_IFR_EQ_ID_LIST_OP:
case EFI_IFR_EQ_ID_VAL_LIST_OP:
case EFI_IFR_QUESTION_REF1_OP:
return TRUE;
default:

View File

@@ -2,7 +2,7 @@
The definition of CFormPkg's member function
Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2004 - 2012, 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
@@ -1885,8 +1885,8 @@ private:
public:
CIfrEqIdList (
IN UINT32 LineNo
) : CIfrObj (EFI_IFR_EQ_ID_LIST_OP, (CHAR8 **)&mEqIdVList, sizeof (EFI_IFR_EQ_ID_VAL_LIST), TRUE),
CIfrOpHeader (EFI_IFR_EQ_ID_LIST_OP, &mEqIdVList->Header) {
) : CIfrObj (EFI_IFR_EQ_ID_VAL_LIST_OP, (CHAR8 **)&mEqIdVList, sizeof (EFI_IFR_EQ_ID_VAL_LIST), TRUE),
CIfrOpHeader (EFI_IFR_EQ_ID_VAL_LIST_OP, &mEqIdVList->Header) {
SetLineNo (LineNo);
mEqIdVList->QuestionId = EFI_QUESTION_ID_INVALID;
mEqIdVList->ListLength = 0;

View File

@@ -2,7 +2,7 @@
Vfr common library functions.
Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2004 - 2012, 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
@@ -3067,6 +3067,83 @@ CVfrStringDB::SetStringFileName(IN CHAR8 *StringFileName)
mStringFileName[FileLen - 1] = '\0';
}
/**
Returns TRUE or FALSE whether SupportedLanguages contains the best matching language
from a set of supported languages.
@param[in] SupportedLanguages A pointer to a Null-terminated ASCII string that
contains a set of language codes.
@param[in] Language A variable that contains pointers to Null-terminated
ASCII strings that contain one language codes.
@retval FALSE The best matching language could not be found in SupportedLanguages.
@retval TRUE The best matching language could be found in SupportedLanguages.
**/
BOOLEAN
CVfrStringDB::GetBestLanguage (
IN CONST CHAR8 *SupportedLanguages,
IN CHAR8 *Language
)
{
UINTN CompareLength;
UINTN LanguageLength;
CONST CHAR8 *Supported;
if (SupportedLanguages == NULL || Language == NULL){
return FALSE;
}
//
// Determine the length of the first RFC 4646 language code in Language
//
for (LanguageLength = 0; Language[LanguageLength] != 0 && Language[LanguageLength] != ';'; LanguageLength++);
//
// Trim back the length of Language used until it is empty
//
while (LanguageLength > 0) {
//
// Loop through all language codes in SupportedLanguages
//
for (Supported = SupportedLanguages; *Supported != '\0'; Supported += CompareLength) {
//
// Skip ';' characters in Supported
//
for (; *Supported != '\0' && *Supported == ';'; Supported++);
//
// Determine the length of the next language code in Supported
//
for (CompareLength = 0; Supported[CompareLength] != 0 && Supported[CompareLength] != ';'; CompareLength++);
//
// If Language is longer than the Supported, then skip to the next language
//
if (LanguageLength > CompareLength) {
continue;
}
//
// See if the first LanguageLength characters in Supported match Language
//
if (strncmp (Supported, Language, LanguageLength) == 0) {
return TRUE;
}
}
//
// Trim Language from the right to the next '-' character
//
for (LanguageLength--; LanguageLength > 0 && Language[LanguageLength] != '-'; LanguageLength--);
}
//
// No matches were found
//
return FALSE;
}
CHAR8 *
CVfrStringDB::GetVarStoreNameFormStringId (
IN EFI_STRING_ID StringId
@@ -3122,17 +3199,18 @@ CVfrStringDB::GetVarStoreNameFormStringId (
}
//
// Search the language, only search the "en-US".
// Search the language, get best language base on RFC 4647 matching algorithm.
//
Current = StringPtr;
while (strcmp (PkgHeader->Language, "en-US") != 0) {
while (!GetBestLanguage ("en", PkgHeader->Language)) {
Current += PkgHeader->Header.Length;
PkgHeader = (EFI_HII_STRING_PACKAGE_HDR *) Current;
//
// If can't find "en-US" string package, just return the first string package.
// If can't find string package base on language, just return the first string package.
//
if (Current - StringPtr >= Length) {
Current = StringPtr;
PkgHeader = (EFI_HII_STRING_PACKAGE_HDR *) StringPtr;
break;
}
}

View File

@@ -2,7 +2,7 @@
Vfr common library functions.
Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
Copyright (c) 2004 - 2012, 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
@@ -438,6 +438,11 @@ private:
UINT32 GetUnicodeStringTextSize (
IN UINT8 *StringSrc
);
BOOLEAN GetBestLanguage (
IN CONST CHAR8 *SupportedLanguages,
IN CHAR8 *Language
);
public:
CVfrStringDB ();

View File

@@ -46,6 +46,9 @@ gMakeTypeMap = {"MSFT":"nmake", "GCC":"gmake"}
## Build rule configuration file
gBuildRuleFile = 'Conf/build_rule.txt'
## Build rule default version
AutoGenReqBuildRuleVerNum = "0.1"
## default file name for AutoGen
gAutoGenCodeFileName = "AutoGen.c"
gAutoGenHeaderFileName = "AutoGen.h"
@@ -288,8 +291,25 @@ class WorkspaceAutoGen(AutoGen):
# apply SKU and inject PCDs from Flash Definition file
for Arch in self.ArchList:
Platform = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]
DecPcds = set()
PGen = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)
Pkgs = PGen.PackageList
for Pkg in Pkgs:
for Pcd in Pkg.Pcds.keys():
DecPcds.add((Pcd[0], Pcd[1]))
Platform.IsPlatformPcdDeclared(DecPcds)
Platform.SkuName = self.SkuId
for Name, Guid in PcdSet:
if (Name, Guid) not in DecPcds:
EdkLogger.error(
'build',
PARSER_ERROR,
"PCD (%s.%s) used in FDF is not declared in DEC files." % (Guid, Name),
File = self.FdfProfile.PcdFileLineDict[Name, Guid][0],
Line = self.FdfProfile.PcdFileLineDict[Name, Guid][1]
)
Platform.AddPcd(Name, Guid, PcdSet[Name, Guid])
Pa = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)
@@ -334,11 +354,14 @@ class WorkspaceAutoGen(AutoGen):
#
InfFoundFlag = False
for Pa in self.AutoGenObjectList:
if InfFoundFlag:
break
for Module in Pa.ModuleAutoGenList:
if path.normpath(Module.MetaFile.File) == path.normpath(FfsFile.InfFileName):
InfFoundFlag = True
if not Module.Guid.upper() in _GuidDict.keys():
_GuidDict[Module.Guid.upper()] = FfsFile
break
else:
EdkLogger.error("build",
FORMAT_INVALID,
@@ -1230,6 +1253,15 @@ class PlatformAutoGen(AutoGen):
if BuildRuleFile in [None, '']:
BuildRuleFile = gBuildRuleFile
self._BuildRule = BuildRule(BuildRuleFile)
if self._BuildRule._FileVersion == "":
self._BuildRule._FileVersion = AutoGenReqBuildRuleVerNum
else:
if self._BuildRule._FileVersion < AutoGenReqBuildRuleVerNum :
# If Build Rule's version is less than the version number required by the tools, halting the build.
EdkLogger.error("build", AUTOGEN_ERROR,
ExtraData="The version number [%s] of build_rule.txt is less than the version number required by the AutoGen.(the minimum required version number is [%s])"\
% (self._BuildRule._FileVersion, AutoGenReqBuildRuleVerNum))
return self._BuildRule
## Summarize the packages used by modules in this platform

View File

@@ -354,6 +354,7 @@ class BuildRule:
self._FamilyList = []
self._TotalToolChainFamilySet = set()
self._RuleObjectList = [] # FileBuildRule object list
self._FileVersion = ""
self.Parse()
@@ -368,7 +369,11 @@ class BuildRule:
# Clean up the line and replace path separator with native one
Line = self.RuleContent[Index].strip().replace(self._PATH_SEP, os.path.sep)
self.RuleContent[Index] = Line
# find the build_rule_version
if Line and Line[0] == "#" and Line.find(TAB_BUILD_RULE_VERSION) <> -1:
if Line.find("=") <> -1 and Line.find("=") < (len(Line)-1) and (Line[(Line.find("=") + 1):]).split():
self._FileVersion = (Line[(Line.find("=") + 1):]).split()[0]
# skip empty or comment line
if Line == "" or Line[0] == "#":
continue

View File

@@ -1,7 +1,7 @@
## @file
# Routines for generating AutoGen.h and AutoGen.c
#
# Copyright (c) 2007 - 2011, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2007 - 2012, 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
@@ -103,17 +103,17 @@ typedef struct {
} SKU_HEAD;
typedef struct {
UINT32 StringIndex; // Offset in String Table in units of UINT32.
UINT32 DefaultValueOffset; // Offset of the Default Value
UINT16 GuidTableIndex; // Offset in Guid Table in units of GUID.
UINT16 StringIndex; // Offset in String Table in units of UINT16.
UINT16 Offset; // Offset in Variable
UINT16 DefaultValueOffset; // Offset of the Default Value
} VARIABLE_HEAD;
typedef struct {
UINT32 Offset;
} VPD_HEAD;
typedef UINT16 STRING_HEAD;
typedef UINT32 STRING_HEAD;
typedef UINT16 SIZE_INFO;
@@ -1346,13 +1346,13 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform, Phase):
VariableHeadGuidIndex = GuidList.index(VariableGuid)
if "PCD_TYPE_STRING" in Pcd.TokenTypeList:
VariableHeadValueList.append('%dU, %dU, %sU, offsetof(%s_PCD_DATABASE, Init.%s_%s)' %
(VariableHeadGuidIndex, VariableHeadStringIndex, Sku.VariableOffset,
Phase, CName, TokenSpaceGuid))
VariableHeadValueList.append('%dU, offsetof(%s_PCD_DATABASE, Init.%s_%s), %dU, %sU' %
(VariableHeadStringIndex, Phase, CName, TokenSpaceGuid,
VariableHeadGuidIndex, Sku.VariableOffset))
else:
VariableHeadValueList.append('%dU, %dU, %sU, offsetof(%s_PCD_DATABASE, Init.%s_%s_VariableDefault_%s)' %
(VariableHeadGuidIndex, VariableHeadStringIndex, Sku.VariableOffset,
Phase, CName, TokenSpaceGuid, SkuIdIndex))
VariableHeadValueList.append('%dU, offsetof(%s_PCD_DATABASE, Init.%s_%s_VariableDefault_%s), %dU, %sU' %
(VariableHeadStringIndex, Phase, CName, TokenSpaceGuid, SkuIdIndex,
VariableHeadGuidIndex, Sku.VariableOffset))
Dict['VARDEF_CNAME_'+Pcd.DatumType].append(CName)
Dict['VARDEF_GUID_'+Pcd.DatumType].append(TokenSpaceGuid)
Dict['VARDEF_SKUID_'+Pcd.DatumType].append(SkuIdIndex)

View File

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

View File

@@ -29,6 +29,7 @@ TAB_OPTION_START = '<'
TAB_OPTION_END = '>'
TAB_SLASH = '\\'
TAB_BACK_SLASH = '/'
TAB_LINE_BREAK = '\n'
TAB_EDK_SOURCE = '$(EDK_SOURCE)'
TAB_EFI_SOURCE = '$(EFI_SOURCE)'
@@ -421,3 +422,11 @@ TAB_DEPENDENCY_EXPRESSION_FILE = "DEPENDENCY-EXPRESSION-FILE"
TAB_UNKNOWN_FILE = "UNKNOWN-TYPE-FILE"
TAB_DEFAULT_BINARY_FILE = "_BINARY_FILE_"
# used by BRG
TAB_BRG_PCD = 'PCD'
TAB_BRG_LIBRARY = 'Library'
#
# Build Rule File Version Definition
#
TAB_BUILD_RULE_VERSION = "build_rule_version"

View File

@@ -36,6 +36,7 @@ ERR_STRING_CMP = 'Unicode string and general string cannot be compared:
ERR_ARRAY_TOKEN = 'Bad C array or C format GUID token: [%s].'
ERR_ARRAY_ELE = 'This must be HEX value for NList or Array: [%s].'
ERR_EMPTY_EXPR = 'Empty expression is not allowed.'
ERR_IN_OPERAND = 'Macro after IN operator can only be: $(FAMILY), $(ARCH), $(TOOL_CHAIN_TAG) and $(TARGET).'
## SplitString
# Split string to list according double quote
@@ -88,22 +89,29 @@ def ReplaceExprMacro(String, Macros, ExceptionList = None):
# If an undefined macro name appears in the constant-expression of
# !if or !elif, it is replaced by the integer constant 0.
RetStr += '0'
elif not InQuote and ExceptionList and Macro in ExceptionList:
elif not InQuote:
Tklst = RetStr.split()
if Tklst and Tklst[-1] in ['IN', 'in'] and ExceptionList and Macro not in ExceptionList:
raise BadExpression(ERR_IN_OPERAND)
# Make sure the macro in exception list is encapsulated by double quote
# For example: DEFINE ARCH = IA32 X64
# $(ARCH) is replaced with "IA32 X64"
RetStr += '"' + Macros[Macro] + '"'
else:
if Macros[Macro].strip() != "":
if ExceptionList and Macro in ExceptionList:
RetStr += '"' + Macros[Macro] + '"'
elif Macros[Macro].strip():
RetStr += Macros[Macro]
else:
RetStr += '""'
else:
RetStr += Macros[Macro]
RetStr += String[MacroEndPos+1:]
String = RetStr
MacroStartPos = String.find('$(')
StrList[i] = RetStr
return ''.join(StrList)
SupportedInMacroList = ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY']
class ValueExpression(object):
# Logical operator mapping
LogicalOperators = {
@@ -213,7 +221,7 @@ class ValueExpression(object):
self._Expr = ReplaceExprMacro(Expression.strip(),
SymbolTable,
['TARGET', 'TOOL_CHAIN_TAG', 'ARCH'])
SupportedInMacroList)
if not self._Expr.strip():
raise BadExpression(ERR_EMPTY_EXPR)
@@ -457,7 +465,9 @@ class ValueExpression(object):
# PCD token
if self.PcdPattern.match(self._Token):
if self._Token not in self._Symb:
raise BadExpression(ERR_PCD_RESOLVE % self._Token)
Ex = BadExpression(ERR_PCD_RESOLVE % self._Token)
Ex.Pcd = self._Token
raise Ex
self._Token = ValueExpression(self._Symb[self._Token], self._Symb)(True)
if type(self._Token) != type(''):
self._LiteralToken = hex(self._Token)

View File

@@ -26,6 +26,10 @@ 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 = {}

View File

@@ -319,7 +319,7 @@ def NormPath(Path, Defines={}):
#
# @retval Path Formatted path
#
def CleanString(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False):
def CleanString(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False, BuildOption=False):
#
# remove whitespace
#
@@ -343,7 +343,7 @@ def CleanString(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyle
Line = Line[0: Index]
break
if CommentInString:
if CommentInString and BuildOption:
Line = Line.replace('"', '')
ChIndex = Line.find('#')
while ChIndex >= 0:

View File

@@ -28,6 +28,7 @@ from Common.String import NormPath
from Common.BuildVersion import gBUILD_VERSION
from Common import BuildToolError
from Common.Misc import PathClass
from Common.Misc import DirCache
from MetaFileWorkspace.MetaFileParser import DscParser
from MetaFileWorkspace.MetaFileParser import DecParser
from MetaFileWorkspace.MetaFileParser import InfParser
@@ -106,6 +107,11 @@ class Ecc(object):
EccGlobalData.gDb = Database.Database(Database.DATABASE_PATH)
EccGlobalData.gDb.InitDatabase(self.IsInit)
#
# Get files real name in workspace dir
#
GlobalData.gAllFiles = DirCache(GlobalData.gWorkspace)
# Build ECC database
self.BuildDatabase()
@@ -137,13 +143,13 @@ class Ecc(object):
EccGlobalData.gDb.TblReport.Create()
# Build database
if self.IsInit:
if self.ScanSourceCode:
EdkLogger.quiet("Building database for source code ...")
c.CollectSourceCodeDataIntoDB(EccGlobalData.gTarget)
if self.IsInit:
if self.ScanMetaData:
EdkLogger.quiet("Building database for source code done!")
EdkLogger.quiet("Building database for Meta Data File ...")
self.BuildMetaDataFileDatabase()
if self.ScanSourceCode:
EdkLogger.quiet("Building database for Meta Data File Done!")
c.CollectSourceCodeDataIntoDB(EccGlobalData.gTarget)
EccGlobalData.gIdentifierTableList = GetTableList((MODEL_FILE_C, MODEL_FILE_H), 'Identifier', EccGlobalData.gDb)
EccGlobalData.gCFileList = GetFileList(MODEL_FILE_C, EccGlobalData.gDb)

View File

@@ -96,7 +96,10 @@ class Table(object):
#
def Drop(self):
SqlCommand = """drop table IF EXISTS %s""" % self.Table
self.Cur.execute(SqlCommand)
try:
self.Cur.execute(SqlCommand)
except sqlite3.Error, e:
print "An error occurred when Drop a table:", e.args[0]
## Get count
#

View File

@@ -1162,8 +1162,9 @@ class DscParser(MetaFileParser):
self._IdMapping[Id] = self._LastItem
RecordList = self._Table.GetAll()
self._Table.Drop()
self._RawTable.Drop()
self._Table.Drop()
for Record in RecordList:
EccGlobalData.gDb.TblDsc.Insert(Record[1],Record[2],Record[3],Record[4],Record[5],Record[6],Record[7],Record[8],Record[9],Record[10],Record[11],Record[12],Record[13],Record[14])
GlobalData.gPlatformDefines.update(self._FileLocalMacros)

View File

@@ -1,15 +0,0 @@
## @file
# Python 'Fdb' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# 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.
#

View File

@@ -1,15 +0,0 @@
## @file
# Python 'FixFlash' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# 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.
#

View File

@@ -77,6 +77,7 @@ SEPERATOR_TUPLE = ('=', '|', ',', '{', '}')
RegionSizePattern = re.compile("\s*(?P<base>(?:0x|0X)?[a-fA-F0-9]+)\s*\|\s*(?P<size>(?:0x|0X)?[a-fA-F0-9]+)\s*")
RegionSizeGuidPattern = re.compile("\s*(?P<base>\w+\.\w+)\s*\|\s*(?P<size>\w+\.\w+)\s*")
ShortcutPcdPattern = re.compile("\s*\w+\s*=\s*(?P<value>(?:0x|0X)?[a-fA-F0-9]+)\s*\|\s*(?P<name>\w+\.\w+)\s*")
IncludeFileList = []
@@ -679,7 +680,7 @@ class FdfParser:
PreIndex = 0
StartPos = CurLine.find('$(', PreIndex)
EndPos = CurLine.find(')', StartPos+2)
while StartPos != -1 and EndPos != -1 and not (self.__Token == '!ifdef' or self.__Token == '!ifndef'):
while StartPos != -1 and EndPos != -1 and self.__Token not in ['!ifdef', '!ifndef', '!if', '!elseif']:
MacroName = CurLine[StartPos+2 : EndPos]
MacorValue = self.__GetMacroValue(MacroName)
if MacorValue != None:
@@ -711,6 +712,8 @@ class FdfParser:
self.__SetMacroValue(Macro, Value)
self.__WipeOffArea.append(((DefineLine, DefineOffset), (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - 1)))
elif self.__Token == 'SET':
SetLine = self.CurrentLineNumber - 1
SetOffset = self.CurrentOffsetWithinLine - len('SET')
PcdPair = self.__GetNextPcdName()
PcdName = "%s.%s" % (PcdPair[1], PcdPair[0])
if not self.__IsToken( "="):
@@ -720,6 +723,12 @@ class FdfParser:
Value = self.__EvaluateConditional(Value, self.CurrentLineNumber, 'eval', True)
self.__PcdDict[PcdName] = Value
self.Profile.PcdDict[PcdPair] = Value
FileLineTuple = GetRealFileLine(self.FileName, self.CurrentLineNumber)
self.Profile.PcdFileLineDict[PcdPair] = FileLineTuple
self.__WipeOffArea.append(((SetLine, SetOffset), (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - 1)))
elif self.__Token in ('!ifdef', '!ifndef', '!if'):
IfStartPos = (self.CurrentLineNumber - 1, self.CurrentOffsetWithinLine - len(self.__Token))
IfList.append([IfStartPos, None, None])
@@ -773,6 +782,11 @@ class FdfParser:
if self.CurrentLineNumber <= RegionLayoutLine:
# Don't try the same line twice
continue
SetPcd = ShortcutPcdPattern.match(self.Profile.FileLinesList[self.CurrentLineNumber - 1])
if SetPcd:
self.__PcdDict[SetPcd.group('name')] = SetPcd.group('value')
RegionLayoutLine = self.CurrentLineNumber
continue
RegionSize = RegionSizePattern.match(self.Profile.FileLinesList[self.CurrentLineNumber - 1])
if not RegionSize:
RegionLayoutLine = self.CurrentLineNumber
@@ -793,6 +807,7 @@ class FdfParser:
MacroDict = {}
# PCD macro
MacroDict.update(GlobalData.gPlatformPcds)
MacroDict.update(self.__PcdDict)
# Lowest priority
@@ -838,7 +853,19 @@ class FdfParser:
Line=Line)
return Excpt.result
except Exception, Excpt:
raise Warning("Invalid expression", *FileLineTuple)
if hasattr(Excpt, 'Pcd'):
if Excpt.Pcd in GlobalData.gPlatformOtherPcds:
Info = GlobalData.gPlatformOtherPcds[Excpt.Pcd]
raise Warning("Cannot use this PCD (%s) in an expression as"
" it must be defined in a [PcdsFixedAtBuild] or [PcdsFeatureFlag] section"
" of the DSC file (%s), and it is currently defined in this section:"
" %s, line #: %d." % (Excpt.Pcd, GlobalData.gPlatformOtherPcds['DSCFILE'], Info[0], Info[1]),
*FileLineTuple)
else:
raise Warning("PCD (%s) is not defined in DSC file (%s)" % (Excpt.Pcd, GlobalData.gPlatformOtherPcds['DSCFILE']),
*FileLineTuple)
else:
raise Warning(str(Excpt), *FileLineTuple)
else:
if Expression.startswith('$(') and Expression[-1] == ')':
Expression = Expression[2:-1]
@@ -2287,6 +2314,10 @@ class FdfParser:
if not self.__GetNextToken():
raise Warning("expected INF file path", self.FileName, self.CurrentLineNumber)
ffsInf.InfFileName = self.__Token
ffsInf.CurrentLineNum = self.CurrentLineNumber
ffsInf.CurrentLineContent = self.__CurrentLine()
if ffsInf.InfFileName.replace('$(WORKSPACE)', '').find('$') == -1:
#do case sensitive check for file path
ErrorCode, ErrorInfo = PathClass(NormPath(ffsInf.InfFileName), GenFdsGlobalVariable.WorkSpaceDir).Validate()
@@ -2306,9 +2337,6 @@ class FdfParser:
else:
raise Warning("Unknown reloc strip flag '%s'" % self.__Token, self.FileName, self.CurrentLineNumber)
ffsInf.CurrentLineNum = self.CurrentLineNumber
ffsInf.CurrentLineContent = self.__CurrentLine()
if ForCapsule:
capsuleFfs = CapsuleData.CapsuleFfs()
capsuleFfs.Ffs = ffsInf
@@ -2419,9 +2447,6 @@ class FdfParser:
FfsFileObj.NameGuid = self.__Token
FfsFileObj.CurrentLineNum = self.CurrentLineNumber
FfsFileObj.CurrentLineContent = self.__CurrentLine()
self.__GetFilePart( FfsFileObj, MacroDict.copy())
if ForCapsule:
@@ -2511,6 +2536,8 @@ class FdfParser:
self.__UndoToken()
self.__GetSectionData( FfsFileObj, MacroDict)
else:
FfsFileObj.CurrentLineNum = self.CurrentLineNumber
FfsFileObj.CurrentLineContent = self.__CurrentLine()
FfsFileObj.FileName = self.__Token
if FfsFileObj.FileName.replace('$(WORKSPACE)', '').find('$') == -1:
#

View File

@@ -64,6 +64,7 @@ class Ffs(FDClassObject):
'COMPAT16' : '.com16',
'RAW' : '.raw',
'FREEFORM_SUBTYPE_GUID': '.guid',
'SUBTYPE_GUID' : '.guid',
'FV_IMAGE' : 'fv.sec',
'COMPRESS' : '.com',
'GUIDED' : '.guided',

View File

@@ -314,7 +314,7 @@ def myOptionParser():
Parser.add_option("-r", "--rom_image", dest="uiFdName", help="Build the image using the [FD] section named by FdUiName.")
Parser.add_option("-i", "--FvImage", dest="uiFvName", help="Build the FV image using the [FV] section named by UiFvName")
Parser.add_option("-C", "--CapsuleImage", dest="uiCapName", help="Build the Capsule image using the [Capsule] section named by UiCapName")
Parser.add_option("-b", "--buildtarget", type="choice", choices=['DEBUG','RELEASE', 'NOOPT'], dest="BuildTarget", help="Build TARGET is one of list: DEBUG, RELEASE, NOOPT.",
Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Set the build TARGET, overrides target.txt TARGET setting.",
action="callback", callback=SingleCheckCallback)
Parser.add_option("-t", "--tagname", type="string", dest="ToolChain", help="Using the tools: TOOL_CHAIN_TAG name to build the platform.",
action="callback", callback=SingleCheckCallback)
@@ -516,10 +516,13 @@ class GenFds :
for ModuleFile in PlatformDataBase.Modules:
Module = BuildDb.BuildObject[ModuleFile, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
GuidXRefFile.write("%s %s\n" % (Module.Guid, Module.BaseName))
SaveFileOnChange(GuidXRefFileName, GuidXRefFile.getvalue(), False)
if GuidXRefFile.getvalue():
SaveFileOnChange(GuidXRefFileName, GuidXRefFile.getvalue(), False)
GenFdsGlobalVariable.InfLogger("\nGUID cross reference file can be found at %s" % GuidXRefFileName)
elif os.path.exists(GuidXRefFileName):
os.remove(GuidXRefFileName)
GuidXRefFile.close()
GenFdsGlobalVariable.InfLogger("\nGUID cross reference file can be found at %s" % GuidXRefFileName)
##Define GenFd as static function
GenFd = staticmethod(GenFd)
GetFvBlockSize = staticmethod(GetFvBlockSize)

View File

@@ -1,7 +1,7 @@
## @file
# Global variables for GenFds
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2007 - 2012, 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
@@ -581,7 +581,7 @@ class GenFdsGlobalVariable:
sys.stdout.write('\n')
try:
PopenObject = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr= subprocess.PIPE)
PopenObject = subprocess.Popen(' '.join(cmd), stdout=subprocess.PIPE, stderr= subprocess.PIPE, shell=True)
except Exception, X:
EdkLogger.error("GenFds", COMMAND_FAILURE, ExtraData="%s: %s" % (str(X), cmd[0]))
(out, error) = PopenObject.communicate()

View File

@@ -21,7 +21,7 @@ MODULES=encodings.cp437,encodings.gbk,encodings.utf_16,encodings.utf_8,encodings
BIN_DIR=$(EDK_TOOLS_PATH)\Bin\Win32
APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe $(BIN_DIR)\Trim.exe $(BIN_DIR)\MigrationMsa2Inf.exe $(BIN_DIR)\Fpd2Dsc.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\spd2dec.exe $(BIN_DIR)\GenDepex.exe $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe
APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe $(BIN_DIR)\Trim.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\GenDepex.exe $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe
COMMON_PYTHON=$(BASE_TOOLS_PATH)\Source\Python\Common\BuildToolError.py \
$(BASE_TOOLS_PATH)\Source\Python\Common\Database.py \
@@ -77,15 +77,6 @@ $(BIN_DIR)\GenFds.exe: $(BASE_TOOLS_PATH)\Source\Python\GenFds\GenFds.py $(COMMO
$(BIN_DIR)\Trim.exe: $(BASE_TOOLS_PATH)\Source\Python\Trim\Trim.py $(COMMON_PYTHON)
@pushd . & @cd Trim & @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR) Trim.py & @popd
$(BIN_DIR)\MigrationMsa2Inf.exe: $(BASE_TOOLS_PATH)\Source\Python\MigrationMsa2Inf\MigrationMsa2Inf.py $(COMMON_PYTHON)
@pushd . & @cd MigrationMsa2Inf & @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR) MigrationMsa2Inf.py & @popd
$(BIN_DIR)\Fpd2Dsc.exe: $(BASE_TOOLS_PATH)\Source\Python\Fpd2Dsc\Fpd2Dsc.py $(COMMON_PYTHON)
@pushd . & @cd Fpd2Dsc & @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR) Fpd2Dsc.py & @popd
$(BIN_DIR)\spd2dec.exe: $(BASE_TOOLS_PATH)\Source\Python\spd2dec\Spd2Dec.py $(COMMON_PYTHON)
@pushd . & @cd Spd2Dec & @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR) Spd2Dec.py & @popd
$(BIN_DIR)\GenDepex.exe: $(BASE_TOOLS_PATH)\Source\Python\AutoGen\GenDepex.py $(COMMON_PYTHON)
@pushd . & @cd AutoGen & @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR) GenDepex.py & @popd

View File

@@ -1,369 +0,0 @@
#!/usr/bin/env python
#
#
# 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 re, os, glob
from Common.XmlRoutines import *
#"ModuleType"=>(PackageGuid, headerFileName) List
HeaderFiles = {}
GuidList = []
GuidMap = {}
HeaderFileContents = {}
gTest = {}
GuidMacro2CName = {}
GuidAliasList = []
def collectIncludeFolder(pkgDirName, guidType, pkgName):
includeFolder = os.path.join(pkgDirName, "Include", guidType)
if os.path.exists(includeFolder) and os.path.isdir(includeFolder):
for headerFileName in os.listdir(includeFolder):
if headerFileName[-2:] == ".h":
headerFile = open(os.path.join(includeFolder, headerFileName))
HeaderFileContents[(guidType, headerFileName, pkgName)] = headerFile.read()
headerFile.close()
GuidMacroReg = re.compile(r"\b(?!EFI_GUID\b)[A-Z0-9_]+_GUID\b")
GuidCNameReg = re.compile(r"\bg\w+Guid\b")
GuidAliasReg = re.compile(r"#define\s+([A-Z0-9_]+_GUID)\s+([A-Z0-9_]+_GUID)\b")
def collectPackageInfo(spdFileName):
pkgDirName = os.path.dirname(spdFileName)
spd = XmlParseFile(spdFileName)
pkgName = XmlElement(spd, "/PackageSurfaceArea/SpdHeader/PackageName")
pkgGuid = XmlElement(spd, "/PackageSurfaceArea/SpdHeader/GuidValue")
for IncludePkgHeader in XmlList(spd, "/PackageSurfaceArea/PackageHeaders/IncludePkgHeader"):
moduleType = XmlAttribute(IncludePkgHeader, "ModuleType")
headerFilePath = XmlElementData(IncludePkgHeader)
headerFilePath = re.sub("Include/", "", headerFilePath, 1)
headerTuple = HeaderFiles.get(moduleType, [])
headerTuple.append((pkgGuid, headerFilePath))
HeaderFiles[moduleType] = headerTuple
guidTypes = ["Guid", "Protocol", "Ppi"]
for guidType in guidTypes:
for guidEntry in XmlList(spd, "/PackageSurfaceArea/" + guidType + "Declarations/Entry"):
guidCName = XmlElement(guidEntry, "Entry/C_Name")
GuidList.append(guidCName)
collectIncludeFolder(pkgDirName, guidType, pkgName)
for DecFile in glob.glob(os.path.join(pkgDirName, "*.dec")):
fileContents = open(DecFile).read()
for GuidCNameMatch in GuidCNameReg.finditer(fileContents):
GuidCName = GuidCNameMatch.group(0)
if GuidCName not in GuidList:
GuidList.append(GuidCName)
def AddGuidMacro2GuidCName(GuidMacros, GuidCNames):
for GuidMacro in GuidMacros:
GuessGuidCName = "g" + GuidMacro.lower().title().replace("_", "")
if GuessGuidCName in GuidCNames:
GuidMacro2CName[GuidMacro] = GuessGuidCName
elif len(GuidCNames) == 1:
GuidMacro2CName[GuidMacro] = GuidCNames[0]
else:
for GuidCName in GuidCNames:
if GuidCName.lower() == GuessGuidCName.lower():
GuidMacro2CName[GuidMacro] = GuidCName
break
else:
pass
#print "No matching GuidMacro %s" % GuidMacro
def TranslateGuid(GuidMacroMatch):
GuidMacro = GuidMacroMatch.group(0)
return GuidMacro2CName.get(GuidMacro, GuidMacro)
DepexReg = re.compile(r"DEPENDENCY_START(.*?)DEPENDENCY_END", re.DOTALL)
def TranslateDpxSection(fileContents):
DepexMatch = DepexReg.search(fileContents)
if not DepexMatch:
return "", []
fileContents = DepexMatch.group(1)
fileContents = re.sub(r"\s+", " ", fileContents).strip()
fileContents = GuidMacroReg.sub(TranslateGuid, fileContents)
return fileContents, GuidMacroReg.findall(fileContents)
def InitializeAutoGen(workspace, db):
for spdFile in XmlList(db, "/FrameworkDatabase/PackageList/Filename"):
spdFileName = XmlElementData(spdFile)
collectPackageInfo(os.path.join(workspace, spdFileName))
BlockCommentReg = re.compile(r"/\*.*?\*/", re.DOTALL)
LineCommentReg = re.compile(r"//.*")
GuidReg = re.compile(r"\b(" + '|'.join(GuidList) + r")\b")
for headerFile in HeaderFileContents:
Contents = HeaderFileContents[headerFile]
Contents = BlockCommentReg.sub("", Contents)
Contents = LineCommentReg.sub("", Contents)
FoundGuids = GuidReg.findall(Contents)
for FoundGuid in FoundGuids:
GuidMap[FoundGuid] = "%s/%s" % (headerFile[0], headerFile[1])
#print "%-40s %s/%s" % (FoundGuid, headerFile[0], headerFile[1])
GuidMacros = GuidMacroReg.findall(Contents)
GuidCNames = GuidCNameReg.findall(Contents)
for GuidAliasMatch in GuidAliasReg.finditer(Contents):
Name1, Name2 = GuidAliasMatch.group(1), GuidAliasMatch.group(2)
GuidAliasList.append((Name1, Name2))
AddGuidMacro2GuidCName(GuidMacros, GuidCNames)
def AddSystemIncludeStatement(moduleType, PackageList):
IncludeStatement = "\n"
headerList = HeaderFiles.get(moduleType, [])
for pkgGuid in PackageList:
for pkgTuple in headerList:
if pkgTuple[0] == pkgGuid:
IncludeStatement += "#include <%s>\n" % pkgTuple[1]
return IncludeStatement
def AddLibraryClassStatement(LibraryClassList):
IncludeStatement = "\n"
for LibraryClass in LibraryClassList:
IncludeStatement += "#include <Library/%s.h>\n" % LibraryClass
return IncludeStatement
def AddGuidStatement(GuidList):
IncludeStatement = "\n"
GuidIncludeSet = {}
for Guid in GuidList:
if Guid in GuidMap:
GuidIncludeSet[GuidMap[Guid]] = 1
else:
print "GUID CName: %s cannot be found in any public header file" % Guid
for GuidInclude in GuidIncludeSet:
IncludeStatement += "#include <%s>\n" % GuidInclude
return IncludeStatement
DriverBindingMap = {
"gEfiDriverBindingProtocolGuid" : "EFI_DRIVER_BINDING_PROTOCOL",
"gEfiComponentNameProtocolGuid" : "EFI_COMPONENT_NAME_PROTOCOL",
"gEfiDriverConfigurationProtocolGuid" : "EFI_DRIVER_CONFIGURATION_PROTOCOL",
"gEfiDriverDiagnosticProtocolGuid" : "EFI_DRIVER_CONFIGURATION_PROTOCOL"
}
def AddDriverBindingProtocolStatement(AutoGenDriverModel):
InstallStatement = "\n"
DBindingHandle = "ImageHandle"
GlobalDeclaration = "\n"
for DriverModelItem in AutoGenDriverModel:
if DriverModelItem[1] == "NULL" and DriverModelItem[2] == "NULL" and DriverModelItem[3] == "NULL":
InstallStatement += " Status = EfiLibInstallDriverBinding (\n"
InstallStatement += " ImageHandle,\n"
InstallStatement += " SystemTable,\n"
InstallStatement += " %s,\n" % DriverModelItem[0]
InstallStatement += " %s\n" % DBindingHandle
InstallStatement += " );\n"
else:
InstallStatement += " Status = EfiLibInstallAllDriverProtocols (\n"
InstallStatement += " ImageHandle,\n"
InstallStatement += " SystemTable,\n"
InstallStatement += " %s,\n" % DriverModelItem[0]
InstallStatement += " %s,\n" % DBindingHandle
InstallStatement += " %s,\n" % DriverModelItem[1]
InstallStatement += " %s,\n" % DriverModelItem[2]
InstallStatement += " %s\n" % DriverModelItem[3]
InstallStatement += " );\n"
InstallStatement += " ASSERT_EFI_ERROR (Status);\n\n"
GlobalDeclaration += "extern EFI_DRIVER_BINDING_PROTOCOL %s;\n" % DriverModelItem[0][1:]
if (DriverModelItem[1] != "NULL"):
GlobalDeclaration += "extern EFI_COMPONENT_NAME_PROTOCOL %s;\n" % DriverModelItem[1][1:]
if (DriverModelItem[2] != "NULL"):
GlobalDeclaration += "extern EFI_DRIVER_CONFIGURATION_PROTOCOL %s;\n" % DriverModelItem[2][1:]
if (DriverModelItem[3] != "NULL"):
GlobalDeclaration += "extern EFI_DRIVER_CONFIGURATION_PROTOCOL %s;\n" % DriverModelItem[3][1:]
DBindingHandle = "NULL"
return (InstallStatement, "", "", GlobalDeclaration)
EventDeclarationTemplate = """
//
// Declaration for callback Event.
//
VOID
EFIAPI
%s (
IN EFI_EVENT Event,
IN VOID *Context
);
"""
def AddBootServiceEventStatement(EventList):
FinalEvent = ""
if len(EventList) > 1:
print "Current prototype does not support multi boot service event"
else:
FinalEvent = EventList[0]
CreateStatement = "\n"
CreateStatement += " Status = gBS->CreateEvent (\n"
CreateStatement += " EVT_SIGNAL_EXIT_BOOT_SERVICES,\n"
CreateStatement += " EFI_TPL_NOTIFY,\n"
CreateStatement += " " + FinalEvent + ",\n"
CreateStatement += " NULL,\n"
CreateStatement += " &mExitBootServicesEvent\n"
CreateStatement += " );\n"
CreateStatement += " ASSERT_EFI_ERROR (Status);\n"
GlobalDefinition = "\n"
GlobalDefinition += "STATIC EFI_EVENT mExitBootServicesEvent = NULL;\n"
GlobalDeclaration = EventDeclarationTemplate % FinalEvent
DestroyStatement = "\n"
DestroyStatement += " Status = gBS->CloseEvent (mExitBootServicesEvent);\n"
DestroyStatement += " ASSERT_EFI_ERROR (Status);\n"
return (CreateStatement, "", GlobalDefinition, GlobalDeclaration)
def AddVirtualAddressEventStatement(EventList):
FinalEvent = ""
if len(EventList) > 1:
print "Current prototype does not support multi virtual address change event"
else:
FinalEvent = EventList[0]
CreateStatement = "\n"
CreateStatement += " Status = gBS->CreateEvent (\n"
CreateStatement += " EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE,\n"
CreateStatement += " TPL_NOTIFY,\n"
CreateStatement += " " + FinalEvent + ",\n"
CreateStatement += " NULL,\n"
CreateStatement += " &mVirtualAddressChangedEvent\n"
CreateStatement += " );\n"
CreateStatement += " ASSERT_EFI_ERROR (Status);\n"
GlobalDefinition = "\n"
GlobalDefinition += "STATIC EFI_EVENT mVirtualAddressChangedEvent = NULL;\n"
GlobalDeclaration = EventDeclarationTemplate % FinalEvent
DestroyStatement = "\n"
DestroyStatement += " Status = gBS->CloseEvent (mVirtualAddressChangedEvent);\n"
DestroyStatement += " ASSERT_EFI_ERROR (Status);\n"
return (CreateStatement, "", GlobalDefinition, GlobalDeclaration)
EntryPointDeclarationTemplate = """
//
// Declaration for original Entry Point.
//
EFI_STATUS
EFIAPI
%s (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
);
"""
EntryPointHeader = r"""
/**
The user Entry Point for module %s. The user code starts with this function.
@param[in] ImageHandle The firmware allocated handle for the EFI image.
@param[in] SystemTable A pointer to the EFI System Table.
@retval EFI_SUCCESS The entry point is executed successfully.
@retval other Some error occurs when executing this entry point.
**/
"""
def AddNewEntryPointContentsStatement (moduleName, EntryPoint, InstallStatement = ""):
if EntryPoint != "Initialize%s" % moduleName:
NewEntryPoint = "Initialize%s" % moduleName
else:
NewEntryPoint = "NewInitialize%s" % moduleName
EntryPointContents = EntryPointHeader % moduleName
EntryPointContents += "EFI_STATUS\n"
EntryPointContents += "EFIAPI\n"
EntryPointContents += NewEntryPoint + "(\n"
EntryPointContents += " IN EFI_HANDLE ImageHandle,\n"
EntryPointContents += " IN EFI_SYSTEM_TABLE *SystemTable\n"
EntryPointContents += " )\n"
EntryPointContents += "{\n"
EntryPointContents += " EFI_STATUS Status;\n"
EntryPointContents += InstallStatement + "\n"
GlobalDeclaration = ""
if EntryPoint != "":
EntryPointContents += " //\n // Call the original Entry Point\n //\n"
EntryPointContents += " Status = %s (ImageHandle, SystemTable);\n\n" % EntryPoint
GlobalDeclaration += EntryPointDeclarationTemplate % EntryPoint
EntryPointContents += " return Status;\n"
EntryPointContents += "}\n"
return (NewEntryPoint, EntryPointContents, GlobalDeclaration)
reFileHeader = re.compile(r"^\s*/\*.*?\*/\s*", re.DOTALL)
reNext = re.compile(r"#ifndef\s*(\w+)\s*#define\s*\1\s*")
def AddCommonInclusionStatement(fileContents, includeStatement):
if includeStatement in fileContents:
return fileContents
insertPos = 0
matchFileHeader = reFileHeader.search(fileContents)
if matchFileHeader:
insertPos = matchFileHeader.end()
matchFileHeader = reNext.search(fileContents, insertPos)
if matchFileHeader:
insertPos = matchFileHeader.end()
includeStatement = "\n%s\n\n" % includeStatement
fileContents = fileContents[0:insertPos] + includeStatement + fileContents[insertPos:]
return fileContents
# This acts like the main() function for the script, unless it is 'import'ed into another
# script.
if __name__ == '__main__':
pass

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +0,0 @@
## @file
# Python 'MigrationMsa2Inf' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# 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.
#

View File

@@ -1,15 +0,0 @@
## @file
# Python 'MkBOM' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# 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.
#

View File

@@ -17,4 +17,4 @@
Build version information
'''
gBUILD_VERSION = "Build 2474"
gBUILD_VERSION = "Build 2518"

View File

@@ -340,6 +340,7 @@ class MetaFileParser(object):
## [BuildOptions] section parser
@ParseMacro
def _BuildOptionParser(self):
self._CurrentLine = CleanString(self._CurrentLine, BuildOption=True)
TokenList = GetSplitValueList(self._CurrentLine, TAB_EQUAL_SPLIT, 1)
TokenList2 = GetSplitValueList(TokenList[0], ':', 1)
if len(TokenList2) == 2:
@@ -913,6 +914,9 @@ class DscParser(MetaFileParser):
ExtraData=self._CurrentLine)
ItemType = self.DataType[DirectiveName]
Scope = [['COMMON', 'COMMON']]
if ItemType == MODEL_META_DATA_INCLUDE:
Scope = self._Scope
if ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF:
# Remove all directives between !if and !endif, including themselves
while self._DirectiveStack:
@@ -945,21 +949,22 @@ class DscParser(MetaFileParser):
# Model, Value1, Value2, Value3, Arch, ModuleType, BelongsToItem=-1, BelongsToFile=-1,
# LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1
#
self._LastItem = self._Store(
ItemType,
self._ValueList[0],
self._ValueList[1],
self._ValueList[2],
'COMMON',
'COMMON',
self._Owner[-1],
self._From,
self._LineIndex+1,
-1,
self._LineIndex+1,
-1,
0
)
for Arch, ModuleType in Scope:
self._LastItem = self._Store(
ItemType,
self._ValueList[0],
self._ValueList[1],
self._ValueList[2],
Arch,
ModuleType,
self._Owner[-1],
self._From,
self._LineIndex+1,
-1,
self._LineIndex+1,
-1,
0
)
## [defines] section parser
@ParseMacro
@@ -1065,6 +1070,7 @@ class DscParser(MetaFileParser):
## [BuildOptions] section parser
@ParseMacro
def _BuildOptionParser(self):
self._CurrentLine = CleanString(self._CurrentLine, BuildOption=True)
TokenList = GetSplitValueList(self._CurrentLine, TAB_EQUAL_SPLIT, 1)
TokenList2 = GetSplitValueList(TokenList[0], ':', 1)
if len(TokenList2) == 2:
@@ -1154,6 +1160,21 @@ class DscParser(MetaFileParser):
self._ContentIndex += 1
self._Scope = [[S1, S2]]
#
# For !include directive, handle it specially,
# merge arch and module type in case of duplicate items
#
while self._ItemType == MODEL_META_DATA_INCLUDE:
if self._ContentIndex >= len(self._Content):
break
Record = self._Content[self._ContentIndex]
if LineStart == Record[9] and LineEnd == Record[11]:
if [Record[5], Record[6]] not in self._Scope:
self._Scope.append([Record[5], Record[6]])
self._ContentIndex += 1
else:
break
self._LineIndex = LineStart - 1
self._ValueList = [V1, V2, V3]
@@ -1164,9 +1185,23 @@ class DscParser(MetaFileParser):
# Only catch expression evaluation error here. We need to report
# the precise number of line on which the error occurred
#
EdkLogger.error('Parser', FORMAT_INVALID, "Invalid expression: %s" % str(Excpt),
File=self._FileWithError, ExtraData=' '.join(self._ValueList),
Line=self._LineIndex+1)
if hasattr(Excpt, 'Pcd'):
if Excpt.Pcd in GlobalData.gPlatformOtherPcds:
Info = GlobalData.gPlatformOtherPcds[Excpt.Pcd]
EdkLogger.error('Parser', FORMAT_INVALID, "Cannot use this PCD (%s) in an expression as"
" it must be defined in a [PcdsFixedAtBuild] or [PcdsFeatureFlag] section"
" of the DSC file, and it is currently defined in this section:"
" %s, line #: %d." % (Excpt.Pcd, Info[0], Info[1]),
File=self._FileWithError, ExtraData=' '.join(self._ValueList),
Line=self._LineIndex+1)
else:
EdkLogger.error('Parser', FORMAT_INVALID, "PCD (%s) is not defined in DSC file" % Excpt.Pcd,
File=self._FileWithError, ExtraData=' '.join(self._ValueList),
Line=self._LineIndex+1)
else:
EdkLogger.error('Parser', FORMAT_INVALID, "Invalid expression: %s" % str(Excpt),
File=self._FileWithError, ExtraData=' '.join(self._ValueList),
Line=self._LineIndex+1)
except MacroException, Excpt:
EdkLogger.error('Parser', FORMAT_INVALID, str(Excpt),
File=self._FileWithError, ExtraData=' '.join(self._ValueList),
@@ -1225,6 +1260,20 @@ class DscParser(MetaFileParser):
Name = TokenSpaceGuid + '.' + PcdName
self._Symbols[Name] = Value
Content = open(str(self.MetaFile), 'r').readlines()
GlobalData.gPlatformOtherPcds['DSCFILE'] = str(self.MetaFile)
for PcdType in (MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_HII,
MODEL_PCD_DYNAMIC_VPD, MODEL_PCD_DYNAMIC_EX_DEFAULT, MODEL_PCD_DYNAMIC_EX_HII,
MODEL_PCD_DYNAMIC_EX_VPD):
Records = self._RawTable.Query(PcdType, BelongsToItem=-1.0)
for TokenSpaceGuid,PcdName,Value,Dummy2,Dummy3,ID,Line in Records:
Name = TokenSpaceGuid + '.' + PcdName
if Name not in GlobalData.gPlatformOtherPcds:
PcdLine = Line
while not Content[Line - 1].lstrip().startswith(TAB_SECTION_START):
Line -= 1
GlobalData.gPlatformOtherPcds[Name] = (CleanString(Content[Line - 1]), PcdLine, PcdType)
def __ProcessDefine(self):
if not self._Enabled:
return
@@ -1386,7 +1435,8 @@ class DscParser(MetaFileParser):
try:
ValueList[0] = ValueExpression(PcdValue, self._Macros)(True)
except WrnExpression, Value:
ValueList[0] = Value.result
ValueList[0] = Value.result
PcdValue = ValueList[0]
else:
#
# Int*/Boolean VPD PCD
@@ -1412,8 +1462,10 @@ class DscParser(MetaFileParser):
if ValueList[-1] == 'True':
ValueList[-1] = '1'
if ValueList[-1] == 'False':
ValueList[-1] = '0'
ValueList[-1] = '0'
PcdValue = ValueList[-1]
if PcdValue and self._ItemType in [MODEL_PCD_FEATURE_FLAG, MODEL_PCD_FIXED_AT_BUILD]:
GlobalData.gPlatformPcds[TAB_SPLIT.join(self._ValueList[0:2])] = PcdValue
self._ValueList[2] = '|'.join(ValueList)
def __ProcessComponent(self):

View File

@@ -50,11 +50,13 @@ class MetaFileTable(Table):
def IsIntegrity(self):
try:
TimeStamp = self.MetaFile.TimeStamp
Result = self.Cur.execute("select ID from %s where ID<0" % (self.Table)).fetchall()
if not Result:
# update the timestamp in database
self._FileIndexTable.SetFileTimeStamp(self.IdBase, TimeStamp)
return False
TimeStamp = self.MetaFile.TimeStamp
if TimeStamp != self._FileIndexTable.GetFileTimeStamp(self.IdBase):
# update the timestamp in database
self._FileIndexTable.SetFileTimeStamp(self.IdBase, TimeStamp)

View File

@@ -262,7 +262,7 @@ class DscBuildData(PlatformBuildClassObject):
if self._Header == None:
self._GetHeaderInfo()
if self._Guid == None:
EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No FILE_GUID", File=self.MetaFile)
EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No PLATFORM_GUID", File=self.MetaFile)
return self._Guid
## Retrieve platform version
@@ -271,7 +271,7 @@ class DscBuildData(PlatformBuildClassObject):
if self._Header == None:
self._GetHeaderInfo()
if self._Version == None:
self._Version = ''
EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No PLATFORM_VERSION", File=self.MetaFile)
return self._Version
## Retrieve platform description file version
@@ -280,7 +280,7 @@ class DscBuildData(PlatformBuildClassObject):
if self._Header == None:
self._GetHeaderInfo()
if self._DscSpecification == None:
self._DscSpecification = ''
EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No DSC_SPECIFICATION", File=self.MetaFile)
return self._DscSpecification
## Retrieve OUTPUT_DIRECTORY
@@ -298,7 +298,7 @@ class DscBuildData(PlatformBuildClassObject):
if self._Header == None:
self._GetHeaderInfo()
if self._SupArchList == None:
self._SupArchList = ARCH_LIST
EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No SUPPORTED_ARCHITECTURES", File=self.MetaFile)
return self._SupArchList
## Retrieve BUILD_TARGETS
@@ -307,7 +307,7 @@ class DscBuildData(PlatformBuildClassObject):
if self._Header == None:
self._GetHeaderInfo()
if self._BuildTargets == None:
self._BuildTargets = ['DEBUG', 'RELEASE', 'NOOPT']
EdkLogger.error('build', ATTRIBUTE_NOT_AVAILABLE, "No BUILD_TARGETS", File=self.MetaFile)
return self._BuildTargets
## Retrieve SKUID_IDENTIFIER
@@ -463,7 +463,8 @@ class DscBuildData(PlatformBuildClassObject):
EdkLogger.error('build', ErrorCode, File=self.MetaFile, Line=LineNo,
ExtraData=ErrorInfo)
# Check duplication
if ModuleFile in self._Modules:
# If arch is COMMON, no duplicate module is checked since all modules in all component sections are selected
if self._Arch != 'COMMON' and ModuleFile in self._Modules:
EdkLogger.error('build', FILE_DUPLICATED, File=self.MetaFile, ExtraData=str(ModuleFile), Line=LineNo)
Module = ModuleBuildClassObject()
@@ -841,6 +842,17 @@ class DscBuildData(PlatformBuildClassObject):
self.Pcds[Name, Guid] = PcdClassObject(Name, Guid, '', '', '', '', '', {}, False, None)
self.Pcds[Name, Guid].DefaultValue = Value
def IsPlatformPcdDeclared(self, DecPcds):
for PcdType in (MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_FEATURE_FLAG,
MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_VPD,
MODEL_PCD_DYNAMIC_EX_DEFAULT, MODEL_PCD_DYNAMIC_EX_HII, MODEL_PCD_DYNAMIC_EX_VPD):
RecordList = self._RawData[PcdType, self._Arch]
for TokenSpaceGuid, PcdCName, Setting, Arch, SkuName, Dummy3, Dummy4 in RecordList:
if (PcdCName, TokenSpaceGuid) not in DecPcds:
EdkLogger.error('build', PARSER_ERROR,
"Pcd (%s.%s) defined in DSC is not declared in DEC files." % (TokenSpaceGuid, PcdCName),
File=self.MetaFile, Line=Dummy4)
_Macros = property(_GetMacros)
Arch = property(_GetArch, _SetArch)
Platform = property(_GetPlatformName)

View File

@@ -33,7 +33,12 @@ from Common.Misc import GuidStructureStringToGuidString
from Common.InfClassObject import gComponentType2ModuleType
from Common.BuildToolError import FILE_WRITE_FAILURE
from Common.BuildToolError import CODE_ERROR
from Common.DataType import TAB_LINE_BREAK
from Common.DataType import TAB_DEPEX
from Common.DataType import TAB_SLASH
from Common.DataType import TAB_SPACE_SPLIT
from Common.DataType import TAB_BRG_PCD
from Common.DataType import TAB_BRG_LIBRARY
## Pattern to extract contents in EDK DXS files
gDxsDependencyPattern = re.compile(r"DEPENDENCY_START(.+)DEPENDENCY_END", re.DOTALL)
@@ -63,15 +68,19 @@ gIncludePattern2 = re.compile(r"#include\s+EFI_([A-Z_]+)\s*[(]\s*(\w+)\s*[)]")
## Pattern to find the entry point for EDK module using EDKII Glue library
gGlueLibEntryPoint = re.compile(r"__EDKII_GLUE_MODULE_ENTRY_POINT__\s*=\s*(\w+)")
## Tags for MaxLength of line in report
gLineMaxLength = 120
## Tags for section start, end and separator
gSectionStart = ">" + "=" * 118 + "<"
gSectionEnd = "<" + "=" * 118 + ">" + "\n"
gSectionSep = "=" * 120
gSectionStart = ">" + "=" * (gLineMaxLength-2) + "<"
gSectionEnd = "<" + "=" * (gLineMaxLength-2) + ">" + "\n"
gSectionSep = "=" * gLineMaxLength
## Tags for subsection start, end and separator
gSubSectionStart = ">" + "-" * 118 + "<"
gSubSectionEnd = "<" + "-" * 118 + ">"
gSubSectionSep = "-" * 120
gSubSectionStart = ">" + "-" * (gLineMaxLength-2) + "<"
gSubSectionEnd = "<" + "-" * (gLineMaxLength-2) + ">"
gSubSectionSep = "-" * gLineMaxLength
## The look up table to map PCD type to pair of report display type and DEC type
gPcdTypeMap = {
@@ -166,6 +175,37 @@ def FindIncludeFiles(Source, IncludePathList, IncludeFiles):
IncludeFiles[FullFileName.lower().replace("\\", "/")] = FullFileName
break
## Split each lines in file
#
# This method is used to split the lines in file to make the length of each line
# less than MaxLength.
#
# @param Content The content of file
# @param MaxLength The Max Length of the line
#
def FileLinesSplit(Content=None, MaxLength=None):
ContentList = Content.split(TAB_LINE_BREAK)
NewContent = ''
NewContentList = []
for Line in ContentList:
while len(Line.rstrip()) > MaxLength:
LineSpaceIndex = Line.rfind(TAB_SPACE_SPLIT, 0, MaxLength)
LineSlashIndex = Line.rfind(TAB_SLASH, 0, MaxLength)
LineBreakIndex = MaxLength
if LineSpaceIndex > LineSlashIndex:
LineBreakIndex = LineSpaceIndex
elif LineSlashIndex > LineSpaceIndex:
LineBreakIndex = LineSlashIndex
NewContentList.append(Line[:LineBreakIndex])
Line = Line[LineBreakIndex:]
if Line:
NewContentList.append(Line)
for NewLine in NewContentList:
NewContent += NewLine + TAB_LINE_BREAK
return NewContent
##
# Parse binary dependency expression section
#
@@ -263,7 +303,7 @@ class LibraryReport(object):
#
def GenerateReport(self, File):
FileWrite(File, gSubSectionStart)
FileWrite(File, "Library")
FileWrite(File, TAB_BRG_LIBRARY)
if len(self.LibraryList) > 0:
FileWrite(File, gSubSectionSep)
for LibraryItem in self.LibraryList:
@@ -355,8 +395,10 @@ class DepexReport(object):
#
def GenerateReport(self, File, GlobalDepexParser):
if not self.Depex:
FileWrite(File, gSubSectionStart)
FileWrite(File, TAB_DEPEX)
FileWrite(File, gSubSectionEnd)
return
FileWrite(File, gSubSectionStart)
if os.path.isfile(self._DepexFileName):
try:
@@ -685,7 +727,7 @@ class PcdReport(object):
# For module PCD sub-section
#
FileWrite(File, gSubSectionStart)
FileWrite(File, "PCD")
FileWrite(File, TAB_BRG_PCD)
FileWrite(File, gSubSectionSep)
for Key in self.AllPcds:
@@ -1511,7 +1553,8 @@ class BuildReport(object):
File = StringIO('')
for (Wa, MaList) in self.ReportList:
PlatformReport(Wa, MaList, self.ReportType).GenerateReport(File, BuildDuration, self.ReportType)
SaveFileOnChange(self.ReportFile, File.getvalue(), False)
Content = FileLinesSplit(File.getvalue(), gLineMaxLength)
SaveFileOnChange(self.ReportFile, Content, True)
EdkLogger.quiet("Build report can be found at %s" % os.path.abspath(self.ReportFile))
except IOError:
EdkLogger.error(None, FILE_WRITE_FAILURE, ExtraData=self.ReportFile)

View File

@@ -59,6 +59,9 @@ gBuildConfiguration = "Conf/target.txt"
gBuildCacheDir = "Conf/.cache"
gToolsDefinition = "Conf/tools_def.txt"
TemporaryTablePattern = re.compile(r'^_\d+_\d+_[a-fA-F0-9]+$')
TmpTableDict = {}
## Check environment PATH variable to make sure the specified tool is found
#
# If the tool is found in the PATH, then True is returned
@@ -1448,6 +1451,14 @@ class Build():
if BuildTask.HasError():
EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule)
#
# Save temp tables to a TmpTableDict.
#
for Key in Wa.BuildDatabase._CACHE_:
if Wa.BuildDatabase._CACHE_[Key]._RawData and Wa.BuildDatabase._CACHE_[Key]._RawData._Table and Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Table:
if TemporaryTablePattern.match(Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Table):
TmpTableDict[Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Table] = Wa.BuildDatabase._CACHE_[Key]._RawData._Table.Cur
#
#
# All modules have been put in build tasks queue. Tell task scheduler
# to exit if all tasks are completed
@@ -1651,8 +1662,8 @@ def MyOptionParser():
help="Build the platform specified by the DSC file name argument, overriding target.txt's ACTIVE_PLATFORM definition.")
Parser.add_option("-m", "--module", action="callback", type="string", dest="ModuleFile", callback=SingleCheckCallback,
help="Build the module specified by the INF file name argument.")
Parser.add_option("-b", "--buildtarget", action="append", type="choice", choices=['DEBUG','RELEASE','NOOPT'], dest="BuildTarget",
help="BuildTarget is one of list: DEBUG, RELEASE, NOOPT, which overrides target.txt's TARGET definition. To specify more TARGET, please repeat this option.")
Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Using the TARGET to build the platform, overriding target.txt's TARGET definition.",
action="append")
Parser.add_option("-t", "--tagname", action="append", type="string", dest="ToolChain",
help="Using the Tool Chain Tagname to build the platform, overriding target.txt's TOOL_CHAIN_TAG definition.")
Parser.add_option("-x", "--sku-id", action="callback", type="string", dest="SkuId", callback=SingleCheckCallback,
@@ -1809,7 +1820,12 @@ def Main():
EdkLogger.error("build", OPTION_VALUE_INVALID, "UNI flag must be one of -c or -s")
MyBuild = Build(Target, Workspace, Option)
GlobalData.gCommandLineDefines['ARCH'] = ' '.join(MyBuild.ArchList)
MyBuild.Launch()
# Drop temp tables to avoid database locked.
for TmpTableName in TmpTableDict:
SqlCommand = """drop table IF EXISTS %s""" % TmpTableName
TmpTableDict[TmpTableName].execute(SqlCommand)
#MyBuild.DumpBuildData()
except FatalError, X:
if MyBuild != None:

View File

@@ -1,327 +0,0 @@
## @file
# Collects the Guid Information in current workspace.
#
# 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 os
import fnmatch
from Common.EdkIIWorkspace import EdkIIWorkspace
from Common.MigrationUtilities import *
## A class for EdkII work space to resolve Guids
#
# This class inherits from EdkIIWorkspace and collects the Guids information
# in current workspace. The Guids information is important to translate the
# package Guids and recommended library instances Guids to relative file path
# (to workspace directory) in MSA files.
#
class EdkIIWorkspaceGuidsInfo(EdkIIWorkspace):
## The classconstructor
#
# The constructor initialize workspace directory. It does not collect
# pakage and module Guids info at initialization; instead, it collects them
# on the fly.
#
# @param self The object pointer
#
def __init__(self):
# Initialize parent class.
EdkIIWorkspace.__init__(self)
# The internal map from Guid to FilePath.
self.__GuidToFilePath = {}
# The internal package directory list.
self.__PackageDirList = []
# The internal flag to indicate whether package Guids info has been initialized
# to avoid re-collection collected.
self.__PackageGuidInitialized = False
# The internal flag to indicate whether module Guids info has been initialized
# to avoid re-collection collected.
self.__ModuleGuidInitialized = False
## Add Guid, Version and FilePath to Guids database
#
# Add Guid, Version and FilePath to Guids database. It constructs a map
# table from Guid, Version to FilePath internally. If also detects possible
# Guid collision. For now, the version information is simply ignored and
# Guid value itself acts as master key.
#
# @param self The object pointer
# @param Guid The Guid Value
# @param Version The version information
# @param FilePath The Guid related file path
#
# @retval True The Guid value is successfully added to map table
# @retval False The Guid is an empty string or the map table
# already contains a same Guid
#
def __AddGuidToFilePath(self, Guid, Version, FilePath):
if Guid == "":
EdkLogger.info("Cannot find Guid in file %s" % FilePath)
return False
#Add the Guid value to map table to ensure case insensitive comparison.
OldFilePath = self.__GuidToFilePath.setdefault(Guid.lower(), FilePath)
if OldFilePath == FilePath:
EdkLogger.verbose("File %s has new Guid '%s'" % (FilePath, Guid))
return True
else:
EdkLogger.info("File %s has duplicate Guid with & %s" % (FilePath, OldFilePath))
return False
## Gets file information from a module description file
#
# Extracts Module Name, File Guid and Version number from INF, MSA and NMSA
# file. It supports to exact such information from text based INF file or
# XML based (N)MSA file.
#
# @param self The object pointer
# @param FileName The input module file name
#
# @retval True This module file represents a new module discovered
# in current workspace
# @retval False This module file is not regarded as a valid module
# The File Guid cannot be extracted or the another
# file with the same Guid already exists
#
def __GetModuleFileInfo(self, FileName):
if fnmatch.fnmatch(FileName, "*.inf"):
TagTuple = ("BASE_NAME", "FILE_GUID", "VERSION_STRING")
(Name, Guid, Version) = GetTextFileInfo(FileName, TagTuple)
else :
XmlTag1 = "ModuleSurfaceArea/MsaHeader/ModuleName"
XmlTag2 = "ModuleSurfaceArea/MsaHeader/GuidValue"
XmlTag3 = "ModuleSurfaceArea/MsaHeader/Version"
TagTuple = (XmlTag1, XmlTag2, XmlTag3)
(Name, Guid, Version) = GetXmlFileInfo(FileName, TagTuple)
return self.__AddGuidToFilePath(Guid, Version, FileName)
## Gets file information from a package description file
#
# Extracts Package Name, File Guid and Version number from INF, SPD and NSPD
# file. It supports to exact such information from text based DEC file or
# XML based (N)SPD file. EDK Compatibility Package is hardcoded to be
# ignored since no EDKII INF file depends on that package.
#
# @param self The object pointer
# @param FileName The input package file name
#
# @retval True This package file represents a new package
# discovered in current workspace
# @retval False This package is not regarded as a valid package
# The File Guid cannot be extracted or the another
# file with the same Guid already exists
#
def __GetPackageFileInfo(self, FileName):
if fnmatch.fnmatch(FileName, "*.dec"):
TagTuple = ("PACKAGE_NAME", "PACKAGE_GUID", "PACKAGE_VERSION")
(Name, Guid, Version) = GetTextFileInfo(FileName, TagTuple)
else:
XmlTag1 = "PackageSurfaceArea/SpdHeader/PackageName"
XmlTag2 = "PackageSurfaceArea/SpdHeader/GuidValue"
XmlTag3 = "PackageSurfaceArea/SpdHeader/Version"
TagTuple = (XmlTag1, XmlTag2, XmlTag3)
(Name, Guid, Version) = GetXmlFileInfo(FileName, TagTuple)
if Name == "EdkCompatibilityPkg":
# Do not scan EDK compatibitilty package to avoid Guid collision
# with those in EDK Glue Library.
EdkLogger.verbose("Bypass EDK Compatibility Pkg")
return False
return self.__AddGuidToFilePath(Guid, Version, FileName)
## Iterate on all package files listed in framework database file
#
# Yields all package description files listed in framework database files.
# The framework database file describes the packages current workspace
# includes.
#
# @param self The object pointer
#
def __FrameworkDatabasePackageFiles(self):
XmlFrameworkDb = XmlParseFile(self.WorkspaceFile)
XmlTag = "FrameworkDatabase/PackageList/Filename"
for PackageFile in XmlElementList(XmlFrameworkDb, XmlTag):
yield os.path.join(self.WorkspaceDir, PackageFile)
## Iterate on all package files in current workspace directory
#
# Yields all package description files listed in current workspace
# directory. This happens when no framework database file exists.
#
# @param self The object pointer
#
def __TraverseAllPackageFiles(self):
for Path, Dirs, Files in os.walk(self.WorkspaceDir):
# Ignore svn version control directory.
if ".svn" in Dirs:
Dirs.remove(".svn")
if "Build" in Dirs:
Dirs.remove("Build")
# Assume priority from high to low: DEC, NSPD, SPD.
PackageFiles = fnmatch.filter(Files, "*.dec")
if len(PackageFiles) == 0:
PackageFiles = fnmatch.filter(Files, "*.nspd")
if len(PackageFiles) == 0:
PackageFiles = fnmatch.filter(Files, "*.spd")
for File in PackageFiles:
# Assume no more package decription file in sub-directory.
del Dirs[:]
yield os.path.join(Path, File)
## Iterate on all module files in current package directory
#
# Yields all module description files listed in current package
# directory.
#
# @param self The object pointer
#
def __TraverseAllModuleFiles(self):
for PackageDir in self.__PackageDirList:
for Path, Dirs, Files in os.walk(PackageDir):
# Ignore svn version control directory.
if ".svn" in Dirs:
Dirs.remove(".svn")
# Assume priority from high to low: INF, NMSA, MSA.
ModuleFiles = fnmatch.filter(Files, "*.inf")
if len(ModuleFiles) == 0:
ModuleFiles = fnmatch.filter(Files, "*.nmsa")
if len(ModuleFiles) == 0:
ModuleFiles = fnmatch.filter(Files, "*.msa")
for File in ModuleFiles:
yield os.path.join(Path, File)
## Initialize package Guids info mapping table
#
# Collects all package guids map to package decription file path. This
# function is invokes on demand to avoid unnecessary directory scan.
#
# @param self The object pointer
#
def __InitializePackageGuidInfo(self):
if self.__PackageGuidInitialized:
return
EdkLogger.verbose("Start to collect Package Guids Info.")
WorkspaceFile = os.path.join("Conf", "FrameworkDatabase.db")
self.WorkspaceFile = os.path.join(self.WorkspaceDir, WorkspaceFile)
# Try to find the frameworkdatabase file to discover package lists
if os.path.exists(self.WorkspaceFile):
TraversePackage = self.__FrameworkDatabasePackageFiles
EdkLogger.verbose("Package list bases on: %s" % self.WorkspaceFile)
else:
TraversePackage = self.__TraverseAllPackageFiles
EdkLogger.verbose("Package list in: %s" % self.WorkspaceDir)
for FileName in TraversePackage():
if self.__GetPackageFileInfo(FileName):
PackageDir = os.path.dirname(FileName)
EdkLogger.verbose("Find new package directory %s" % PackageDir)
self.__PackageDirList.append(PackageDir)
self.__PackageGuidInitialized = True
## Initialize module Guids info mapping table
#
# Collects all module guids map to module decription file path. This
# function is invokes on demand to avoid unnecessary directory scan.
#
# @param self The object pointer
#
def __InitializeModuleGuidInfo(self):
if self.__ModuleGuidInitialized:
return
EdkLogger.verbose("Start to collect Module Guids Info")
self.__InitializePackageGuidInfo()
for FileName in self.__TraverseAllModuleFiles():
if self.__GetModuleFileInfo(FileName):
EdkLogger.verbose("Find new module %s" % FileName)
self.__ModuleGuidInitialized = True
## Get Package file path by Package Guid and Version
#
# Translates the Package Guid and Version to a file path relative
# to workspace directory. If no package in current workspace match the
# input Guid, an empty file path is returned. For now, the version
# value is simply ignored.
#
# @param self The object pointer
# @param Guid The Package Guid value to look for
# @param Version The Package Version value to look for
#
def ResolvePackageFilePath(self, Guid, Version = ""):
self.__InitializePackageGuidInfo()
EdkLogger.verbose("Resolve Package Guid '%s'" % Guid)
FileName = self.__GuidToFilePath.get(Guid.lower(), "")
if FileName == "":
EdkLogger.info("Cannot resolve Package Guid '%s'" % Guid)
else:
FileName = self.WorkspaceRelativePath(FileName)
FileName = os.path.splitext(FileName)[0] + ".dec"
FileName = FileName.replace("\\", "/")
return FileName
## Get Module file path by Module Guid and Version
#
# Translates the Module Guid and Version to a file path relative
# to workspace directory. If no module in current workspace match the
# input Guid, an empty file path is returned. For now, the version
# value is simply ignored.
#
# @param self The object pointer
# @param Guid The Module Guid value to look for
# @param Version The Module Version value to look for
#
def ResolveModuleFilePath(self, Guid, Version = ""):
self.__InitializeModuleGuidInfo()
EdkLogger.verbose("Resolve Module Guid '%s'" % Guid)
FileName = self.__GuidToFilePath.get(Guid.lower(), "")
if FileName == "":
EdkLogger.info("Cannot resolve Module Guid '%s'" % Guid)
else:
FileName = self.WorkspaceRelativePath(FileName)
FileName = os.path.splitext(FileName)[0] + ".inf"
FileName = FileName.replace("\\", "/")
return FileName
# A global class object of EdkIIWorkspaceGuidsInfo for external reference.
gEdkIIWorkspaceGuidsInfo = EdkIIWorkspaceGuidsInfo()
# This acts like the main() function for the script, unless it is 'import'ed
# into another script.
if __name__ == '__main__':
# Test the translation of package Guid.
# MdePkgGuid = "1E73767F-8F52-4603-AEB4-F29B510B6766"
# OldMdePkgGuid = "5e0e9358-46b6-4ae2-8218-4ab8b9bbdcec"
# print gEdkIIWorkspaceGuidsInfo.ResolveModuleFilePath(MdePkgGuid)
# print gEdkIIWorkspaceGuidsInfo.ResolveModuleFilePath(OldMdePkgGuid)
# Test the translation of module Guid.
# UefiLibGuid = "3a004ba5-efe0-4a61-9f1a-267a46ae5ba9"
# UefiDriverModelLibGuid = "52af22ae-9901-4484-8cdc-622dd5838b09"
# print gEdkIIWorkspaceGuidsInfo.ResolvePlatformFilePath(UefiLibGuid)
# print gEdkIIWorkspaceGuidsInfo.ResolvePlatformFilePath(UefiDriverModelLibGuid)
pass

File diff suppressed because it is too large Load Diff

View File

@@ -1,563 +0,0 @@
## @file
# Contains several utilitities shared by migration 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 os
import re
import EdkLogger
from optparse import OptionParser
from Common.BuildToolError import *
from XmlRoutines import *
from CommonDataClass.CommonClass import *
## Set all fields of CommonClass object.
#
# Set all attributes of CommonClass object from XML Dom object of XmlCommon.
#
# @param Common The destine CommonClass object.
# @param XmlCommon The source XML Dom object.
#
def SetCommon(Common, XmlCommon):
XmlTag = "Usage"
Common.Usage = XmlAttribute(XmlCommon, XmlTag).split()
XmlTag = "FeatureFlag"
Common.FeatureFlag = XmlAttribute(XmlCommon, XmlTag)
XmlTag = "SupArchList"
Common.SupArchList = XmlAttribute(XmlCommon, XmlTag).split()
XmlTag = XmlNodeName(XmlCommon) + "/" + "HelpText"
Common.HelpText = XmlElement(XmlCommon, XmlTag)
## Set some fields of CommonHeaderClass object.
#
# Set Name, Guid, FileName and FullPath fields of CommonHeaderClass object from
# XML Dom object of XmlCommonHeader, NameTag and FileName.
#
# @param CommonHeader The destine CommonClass object.
# @param XmlCommonHeader The source XML Dom object.
# @param NameTag The name tag in XML Dom object.
# @param FileName The file name of the XML file.
#
def SetIdentification(CommonHeader, XmlCommonHeader, NameTag, FileName):
XmlParentTag = XmlNodeName(XmlCommonHeader)
XmlTag = XmlParentTag + "/" + NameTag
CommonHeader.Name = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParentTag + "/" + "GuidValue"
CommonHeader.Guid = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParentTag + "/" + "Version"
CommonHeader.Version = XmlElement(XmlCommonHeader, XmlTag)
CommonHeader.FileName = os.path.basename(FileName)
CommonHeader.FullPath = os.path.abspath(FileName)
## Regular expression to match specification and value.
mReSpecification = re.compile(r"(?P<Specification>\w+)\s+(?P<Value>\w*)")
## Add specification to specification dictionary.
#
# Abstract specification name, value pair from Specification String and add them
# to specification dictionary.
#
# @param SpecificationDict The destine Specification dictionary.
# @param SpecificationString The source Specification String from which the
# specification name and value pair is abstracted.
#
def AddToSpecificationDict(SpecificationDict, SpecificationString):
"""Abstract specification name, value pair from Specification String"""
for SpecificationMatch in mReSpecification.finditer(SpecificationString):
Specification = SpecificationMatch.group("Specification")
Value = SpecificationMatch.group("Value")
SpecificationDict[Specification] = Value
## Set all fields of CommonHeaderClass object.
#
# Set all attributes of CommonHeaderClass object from XML Dom object of
# XmlCommonHeader, NameTag and FileName.
#
# @param CommonHeader The destine CommonClass object.
# @param XmlCommonHeader The source XML Dom object.
# @param NameTag The name tag in XML Dom object.
# @param FileName The file name of the XML file.
#
def SetCommonHeader(CommonHeader, XmlCommonHeader):
"""Set all attributes of CommonHeaderClass object from XmlCommonHeader"""
XmlParent = XmlNodeName(XmlCommonHeader)
XmlTag = XmlParent + "/" + "Abstract"
CommonHeader.Abstract = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParent + "/" + "Description"
CommonHeader.Description = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParent + "/" + "Copyright"
CommonHeader.Copyright = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParent + "/" + "License"
CommonHeader.License = XmlElement(XmlCommonHeader, XmlTag)
XmlTag = XmlParent + "/" + "Specification"
Specification = XmlElement(XmlCommonHeader, XmlTag)
AddToSpecificationDict(CommonHeader.Specification, Specification)
XmlTag = XmlParent + "/" + "ModuleType"
CommonHeader.ModuleType = XmlElement(XmlCommonHeader, XmlTag)
## Load a new Cloned Record class object.
#
# Read an input XML ClonedRecord DOM object and return an object of Cloned Record
# contained in the DOM object.
#
# @param XmlCloned A child XML DOM object in a Common XML DOM.
#
# @retvel ClonedRecord A new Cloned Record object created by XmlCloned.
#
def LoadClonedRecord(XmlCloned):
ClonedRecord = ClonedRecordClass()
XmlTag = "Id"
ClonedRecord.Id = int(XmlAttribute(XmlCloned, XmlTag))
XmlTag = "FarGuid"
ClonedRecord.FarGuid = XmlAttribute(XmlCloned, XmlTag)
XmlTag = "Cloned/PackageGuid"
ClonedRecord.PackageGuid = XmlElement(XmlCloned, XmlTag)
XmlTag = "Cloned/PackageVersion"
ClonedRecord.PackageVersion = XmlElement(XmlCloned, XmlTag)
XmlTag = "Cloned/ModuleGuid"
ClonedRecord.ModuleGuid = XmlElement(XmlCloned, XmlTag)
XmlTag = "Cloned/ModuleVersion"
ClonedRecord.ModuleVersion = XmlElement(XmlCloned, XmlTag)
return ClonedRecord
## Load a new Guid/Protocol/Ppi common class object.
#
# Read an input XML Guid/Protocol/Ppi DOM object and return an object of
# Guid/Protocol/Ppi contained in the DOM object.
#
# @param XmlGuidProtocolPpiCommon A child XML DOM object in a Common XML DOM.
#
# @retvel GuidProtocolPpiCommon A new GuidProtocolPpiCommon class object
# created by XmlGuidProtocolPpiCommon.
#
def LoadGuidProtocolPpiCommon(XmlGuidProtocolPpiCommon):
GuidProtocolPpiCommon = GuidProtocolPpiCommonClass()
XmlTag = "Name"
GuidProtocolPpiCommon.Name = XmlAttribute(XmlGuidProtocolPpiCommon, XmlTag)
XmlParent = XmlNodeName(XmlGuidProtocolPpiCommon)
if XmlParent == "Entry":
XmlTag = "%s/C_Name" % XmlParent
elif XmlParent == "GuidCNames":
XmlTag = "%s/GuidCName" % XmlParent
else:
XmlTag = "%s/%sCName" % (XmlParent, XmlParent)
GuidProtocolPpiCommon.CName = XmlElement(XmlGuidProtocolPpiCommon, XmlTag)
XmlTag = XmlParent + "/" + "GuidValue"
GuidProtocolPpiCommon.Guid = XmlElement(XmlGuidProtocolPpiCommon, XmlTag)
if XmlParent.endswith("Notify"):
GuidProtocolPpiCommon.Notify = True
XmlTag = "GuidTypeList"
GuidTypes = XmlAttribute(XmlGuidProtocolPpiCommon, XmlTag)
GuidProtocolPpiCommon.GuidTypeList = GuidTypes.split()
XmlTag = "SupModuleList"
SupModules = XmlAttribute(XmlGuidProtocolPpiCommon, XmlTag)
GuidProtocolPpiCommon.SupModuleList = SupModules.split()
SetCommon(GuidProtocolPpiCommon, XmlGuidProtocolPpiCommon)
return GuidProtocolPpiCommon
## Load a new Pcd class object.
#
# Read an input XML Pcd DOM object and return an object of Pcd
# contained in the DOM object.
#
# @param XmlPcd A child XML DOM object in a Common XML DOM.
#
# @retvel Pcd A new Pcd object created by XmlPcd.
#
def LoadPcd(XmlPcd):
"""Return a new PcdClass object equivalent to XmlPcd"""
Pcd = PcdClass()
XmlTag = "PcdEntry/C_Name"
Pcd.CName = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/Token"
Pcd.Token = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/TokenSpaceGuidCName"
Pcd.TokenSpaceGuidCName = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/DatumType"
Pcd.DatumType = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/MaxDatumSize"
Pcd.MaxDatumSize = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdEntry/DefaultValue"
Pcd.DefaultValue = XmlElement(XmlPcd, XmlTag)
XmlTag = "PcdItemType"
Pcd.ItemType = XmlAttribute(XmlPcd, XmlTag)
XmlTag = "PcdEntry/ValidUsage"
Pcd.ValidUsage = XmlElement(XmlPcd, XmlTag).split()
XmlTag = "SupModuleList"
Pcd.SupModuleList = XmlAttribute(XmlPcd, XmlTag).split()
SetCommon(Pcd, XmlPcd)
return Pcd
## Load a new LibraryClass class object.
#
# Read an input XML LibraryClass DOM object and return an object of LibraryClass
# contained in the DOM object.
#
# @param XmlLibraryClass A child XML DOM object in a Common XML DOM.
#
# @retvel LibraryClass A new LibraryClass object created by XmlLibraryClass.
#
def LoadLibraryClass(XmlLibraryClass):
LibraryClass = LibraryClassClass()
XmlTag = "LibraryClass/Keyword"
LibraryClass.LibraryClass = XmlElement(XmlLibraryClass, XmlTag)
if LibraryClass.LibraryClass == "":
XmlTag = "Name"
LibraryClass.LibraryClass = XmlAttribute(XmlLibraryClass, XmlTag)
XmlTag = "LibraryClass/IncludeHeader"
LibraryClass.IncludeHeader = XmlElement(XmlLibraryClass, XmlTag)
XmlTag = "RecommendedInstanceVersion"
RecommendedInstanceVersion = XmlAttribute(XmlLibraryClass, XmlTag)
LibraryClass.RecommendedInstanceVersion = RecommendedInstanceVersion
XmlTag = "RecommendedInstanceGuid"
RecommendedInstanceGuid = XmlAttribute(XmlLibraryClass, XmlTag)
LibraryClass.RecommendedInstanceGuid = RecommendedInstanceGuid
XmlTag = "SupModuleList"
SupModules = XmlAttribute(XmlLibraryClass, XmlTag)
LibraryClass.SupModuleList = SupModules.split()
SetCommon(LibraryClass, XmlLibraryClass)
return LibraryClass
## Load a new Build Option class object.
#
# Read an input XML BuildOption DOM object and return an object of Build Option
# contained in the DOM object.
#
# @param XmlBuildOption A child XML DOM object in a Common XML DOM.
#
# @retvel BuildOption A new Build Option object created by XmlBuildOption.
#
def LoadBuildOption(XmlBuildOption):
"""Return a new BuildOptionClass object equivalent to XmlBuildOption"""
BuildOption = BuildOptionClass()
BuildOption.Option = XmlElementData(XmlBuildOption)
XmlTag = "BuildTargets"
BuildOption.BuildTargetList = XmlAttribute(XmlBuildOption, XmlTag).split()
XmlTag = "ToolChainFamily"
BuildOption.ToolChainFamily = XmlAttribute(XmlBuildOption, XmlTag)
XmlTag = "TagName"
BuildOption.TagName = XmlAttribute(XmlBuildOption, XmlTag)
XmlTag = "ToolCode"
BuildOption.ToolCode = XmlAttribute(XmlBuildOption, XmlTag)
XmlTag = "SupArchList"
BuildOption.SupArchList = XmlAttribute(XmlBuildOption, XmlTag).split()
return BuildOption
## Load a new User Extensions class object.
#
# Read an input XML UserExtensions DOM object and return an object of User
# Extensions contained in the DOM object.
#
# @param XmlUserExtensions A child XML DOM object in a Common XML DOM.
#
# @retvel UserExtensions A new User Extensions object created by
# XmlUserExtensions.
#
def LoadUserExtensions(XmlUserExtensions):
UserExtensions = UserExtensionsClass()
XmlTag = "UserId"
UserExtensions.UserID = XmlAttribute(XmlUserExtensions, XmlTag)
XmlTag = "Identifier"
UserExtensions.Identifier = XmlAttribute(XmlUserExtensions, XmlTag)
UserExtensions.Content = XmlElementData(XmlUserExtensions)
return UserExtensions
## Store content to a text file object.
#
# Write some text file content to a text file object. The contents may echo
# in screen in a verbose way.
#
# @param TextFile The text file object.
# @param Content The string object to be written to a text file.
#
def StoreTextFile(TextFile, Content):
EdkLogger.verbose(Content)
TextFile.write(Content)
## Add item to a section.
#
# Add an Item with specific CPU architecture to section dictionary.
# The possible duplication is ensured to be removed.
#
# @param Section Section dictionary indexed by CPU architecture.
# @param Arch CPU architecture: Ia32, X64, Ipf, Ebc or Common.
# @param Item The Item to be added to section dictionary.
#
def AddToSection(Section, Arch, Item):
SectionArch = Section.get(Arch, [])
if Item not in SectionArch:
SectionArch.append(Item)
Section[Arch] = SectionArch
## Get section contents.
#
# Return the content of section named SectionName.
# the contents is based on Methods and ObjectLists.
#
# @param SectionName The name of the section.
# @param Method A function returning a string item of an object.
# @param ObjectList The list of object.
#
# @retval Section The string content of a section.
#
def GetSection(SectionName, Method, ObjectList):
SupportedArches = ["common", "Ia32", "X64", "Ipf", "Ebc"]
SectionDict = {}
for Object in ObjectList:
Item = Method(Object)
if Item == "":
continue
Item = " %s" % Item
Arches = Object.SupArchList
if len(Arches) == 0:
AddToSection(SectionDict, "common", Item)
else:
for Arch in SupportedArches:
if Arch.upper() in Arches:
AddToSection(SectionDict, Arch, Item)
Section = ""
for Arch in SupportedArches:
SectionArch = "\n".join(SectionDict.get(Arch, []))
if SectionArch != "":
Section += "[%s.%s]\n%s\n" % (SectionName, Arch, SectionArch)
Section += "\n"
if Section != "":
Section += "\n"
return Section
## Store file header to a text file.
#
# Write standard file header to a text file. The content includes copyright,
# abstract, description and license extracted from CommonHeader class object.
#
# @param TextFile The text file object.
# @param CommonHeader The source CommonHeader class object.
#
def StoreHeader(TextFile, CommonHeader):
CopyRight = CommonHeader.Copyright
Abstract = CommonHeader.Abstract
Description = CommonHeader.Description
License = CommonHeader.License
Header = "#/** @file\n#\n"
Header += "# " + Abstract + "\n#\n"
Header += "# " + Description.strip().replace("\n", "\n# ") + "\n"
Header += "# " + CopyRight + "\n#\n"
Header += "# " + License.replace("\n", "\n# ").replace(" ", " ")
Header += "\n#\n#**/\n\n"
StoreTextFile(TextFile, Header)
## Store file header to a text file.
#
# Write Defines section to a text file. DefinesTupleList determines the content.
#
# @param TextFile The text file object.
# @param DefinesTupleList The list of (Tag, Value) to be added as one item.
#
def StoreDefinesSection(TextFile, DefinesTupleList):
Section = "[Defines]\n"
for DefineItem in DefinesTupleList:
Section += " %-30s = %s\n" % DefineItem
Section += "\n\n"
StoreTextFile(TextFile, Section)
## Add item to PCD dictionary.
#
# Add an PcdClass object to PCD dictionary. The key is generated from
# PcdItemType.
#
# @param PcdDict PCD dictionary indexed by Pcd Item Type.
# @param Arch CPU architecture: Ia32, X64, Ipf, Ebc or Common.
# @param Item The Item to be added to section dictionary.
#
def AddToPcdsDict(PcdDict, PcdItemType, PcdCode):
PcdSectionName = PcdItemType
PcdSectionName = PcdSectionName.title()
PcdSectionName = PcdSectionName.replace("_", "")
PcdSectionName = "Pcds" + PcdSectionName
PcdDict.setdefault(PcdSectionName, []).append(PcdCode)
## Regular expression to match an equation.
mReEquation = re.compile(r"\s*(\S+)\s*=\s*(\S*)\s*")
## Return a value tuple matching information in a text fle.
#
# Parse the text file and return a value tuple corresponding to an input tag
# tuple. In case of any error, an tuple of empty strings is returned.
#
# @param FileName The file name of the text file.
# @param TagTuple A tuple of tags as the key to the value.
#
# @param ValueTupe The returned tuple corresponding to the tag tuple.
#
def GetTextFileInfo(FileName, TagTuple):
ValueTuple = [""] * len(TagTuple)
try:
for Line in open(FileName):
Line = Line.split("#", 1)[0]
MatchEquation = mReEquation.match(Line)
if MatchEquation:
Tag = MatchEquation.group(1).upper()
Value = MatchEquation.group(2)
for Index in range(len(TagTuple)):
if TagTuple[Index] == Tag:
ValueTuple[Index] = Value
except:
EdkLogger.info("IO Error in reading file %s" % FileName)
return ValueTuple
## Return a value tuple matching information in an XML fle.
#
# Parse the XML file and return a value tuple corresponding to an input tag
# tuple. In case of any error, an tuple of empty strings is returned.
#
# @param FileName The file name of the XML file.
# @param TagTuple A tuple of tags as the key to the value.
#
# @param ValueTupe The returned tuple corresponding to the tag tuple.
#
def GetXmlFileInfo(FileName, TagTuple):
XmlDom = XmlParseFile(FileName)
return tuple([XmlElement(XmlDom, XmlTag) for XmlTag in TagTuple])
# Version and Copyright
__version_number__ = "1.0"
__version__ = "%prog Version " + __version_number__
__copyright__ = "Copyright (c) 2007, Intel Corporation. All rights reserved."
## Parse migration command line options
#
# Use standard Python module optparse to parse command line option of this tool.
#
# @param Source The source file type.
# @param Destinate The destinate file type.
#
# @retval Options A optparse object containing the parsed options.
# @retval InputFile Path of an source file to be migrated.
#
def MigrationOptionParser(Source, Destinate):
# use clearer usage to override default usage message
UsageString = "%prog [-a] [-o <output_file>] <input_file>"
Parser = OptionParser(description=__copyright__, version=__version__, usage=UsageString)
HelpText = "The name of the %s file to be created." % Destinate
Parser.add_option("-o", "--output", dest="OutputFile", help=HelpText)
HelpText = "Automatically create the %s file using the name of the %s file and replacing file extension" % (Source, Destinate)
Parser.add_option("-a", "--auto", dest="AutoWrite", action="store_true", default=False, help=HelpText)
Options, Args = Parser.parse_args()
# error check
if len(Args) == 0:
raise MigrationError(OPTION_MISSING, name="Input file", usage=Parser.get_usage())
if len(Args) > 1:
raise MigrationError(OPTION_NOT_SUPPORTED, name="Too many input files", usage=Parser.get_usage())
InputFile = Args[0]
if not os.path.exists(InputFile):
raise MigrationError(FILE_NOT_FOUND, name=InputFile)
if Options.OutputFile:
if Options.AutoWrite:
raise MigrationError(OPTION_CONFLICT, arg1="-o", arg2="-a", usage=Parser.get_usage())
else:
if Options.AutoWrite:
Options.OutputFile = os.path.splitext(InputFile)[0] + "." + Destinate.lower()
else:
raise MigrationError(OPTION_MISSING, name="-o", usage=Parser.get_usage())
return Options, InputFile
# This acts like the main() function for the script, unless it is 'import'ed
# into another script.
if __name__ == '__main__':
pass

View File

@@ -1,765 +0,0 @@
## @file
# Store a Platform class object to an INF file.
#
# Copyright (c) 2007 - 2009, 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
#
from LoadFpd import LoadFpd
from CommonDataClass.PlatformClass import *
from CommonDataClass.FdfClass import *
from Common.MigrationUtilities import *
from Common.ToolDefClassObject import *
from Common.TargetTxtClassObject import *
## Store Defines section
#
# Write [Defines] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Defines section
# @param Platform An input Platform class object
#
def StorePlatformDefinesSection(DscFile, Platform):
PlatformHeader = Platform.Header
DefinesTupleList = []
if PlatformHeader.Name != "":
DefinesTupleList.append(("PLATFORM_NAME", PlatformHeader.Name))
if PlatformHeader.Guid != "":
DefinesTupleList.append(("PLATFORM_GUID", PlatformHeader.Guid))
if PlatformHeader.Version != "":
DefinesTupleList.append(("PLATFORM_VERSION", PlatformHeader.Version))
for key in PlatformHeader.Specification.keys():
SpecificationValue = PlatformHeader.Specification.get(key)
DefinesTupleList.append(("DSC_ SPECIFICATION", SpecificationValue))
if PlatformHeader.OutputDirectory != "":
DefinesTupleList.append(("OUTPUT_DIRECTORY", PlatformHeader.OutputDirectory))
if PlatformHeader.SupArchList != "":
String = "|".join(PlatformHeader.SupArchList)
DefinesTupleList.append(("SUPPORTED_ARCHITECTURES", String))
if PlatformHeader.BuildTargets != "":
String = "|".join(PlatformHeader.BuildTargets)
DefinesTupleList.append(("BUILD_TARGETS", String))
if PlatformHeader.SkuIdName != "":
#DefinesTupleList.append(("SKUID_IDENTIFIER", PlatformHeader.SkuIdName))
String = "|".join(PlatformHeader.SkuIdName)
if String != "":
DefinesTupleList.append(("SKUID_IDENTIFIER", String))
String = Platform.FlashDefinitionFile.FilePath
if String != "":
DefinesTupleList.append(("FLASH_DEFINITION", String))
List = []
List.append("################################################################################")
List.append("#")
List.append("# Defines Section - statements that will be processed to create a Makefile.")
List.append("#")
List.append("################################################################################")
Section = "\n".join(List)
Section += "\n"
StoreTextFile(DscFile, Section)
StoreDefinesSection(DscFile, DefinesTupleList)
## Store SkuIds section
#
# Write [SkuIds] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Library Classes section
# @param Platform An input Platform class object
#
def StorePlatformSkuIdsSection(DscFile, Platform):
List = []
List.append("################################################################################")
List.append("#")
List.append("# SKU Identification section - list of all SKU IDs supported by this Platform.")
List.append("#")
List.append("################################################################################")
Section = "\n".join(List)
Section += "\n"
Section += "[SkuIds]" + '\n'
List = Platform.SkuInfos.SkuInfoList
for Item in List:
Section = Section + "%s" % Item[0] + '|' + "%s" % Item[1] + '\n'
Section = Section + '\n'
StoreTextFile(DscFile, Section)
## Store Build Options section
#
# Write [BuildOptions] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Build Options section
# @param Platform An input Platform class object
#
def StorePlatformBuildOptionsSection(DscFile, Platform):
# which is from tools_def.txt
StandardBuildTargets = ["DEBUG", "RELEASE"]
SupportedArches = ["COMMON", "IA32", "X64", "IPF", "EBC", "ARM"]
Target = TargetTxtClassObject()
WorkSpace = os.getenv('WORKSPACE')
Target.LoadTargetTxtFile(WorkSpace + '\\Conf\\target.txt')
ToolDef = ToolDefClassObject()
ToolDef.LoadToolDefFile(WorkSpace + '\\' + Target.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF])
# Now we have got ToolDef object
#ToolDef.ToolsDefTxtDictionary
Dict = ToolDef.ToolsDefTxtDatabase
Dict1 = ToolDef.ToolsDefTxtDictionary # we care the info in this Dict
#
# We only support *(DEBUG/RELEASE) and *(All Arch: IA32, X64, IPF and EBC) for now
#
SectionWINDDK = ''
SectionVS2003 = ''
SectionVS2005EXP = ''
SectionVS2005STD = ''
SectionVS2005PRO = ''
SectionVS2005TEAMSUITE = ''
SectionUNIXGCC = ''
SectionCYGWINGCC = ''
SectionELFGCC = ''
SectionICC = ''
SectionMYTOOLS = ''
for key in Dict1.keys():
if key.find("_CC_FLAGS") != -1:
if key.find('WINDDK3790x1830') != -1:
SectionWINDDK = " = " + Dict1.get(key) + "\n"
elif key.find('VS2003') != -1:
SectionVS2003 = " = " + Dict1.get(key)+ "\n"
elif key.find('VS2005EXP') != -1:
SectionVS2005EXP = " = " + Dict1.get(key) + "\n"
elif key.find('VS2005STD') != -1:
SectionVS2005STD = " = " + Dict1.get(key) + "\n"
elif key.find('VS2005PRO') != -1:
SectionVS2005PRO = " = " + Dict1.get(key) + "\n"
elif key.find('VS2005TEAMSUITE') != -1:
SectionVS2005TEAMSUITE = " = " + Dict1.get(key) + "\n"
elif key.find('UNIXGCC') != -1:
SectionUNIXGCC = " = " + Dict1.get(key) + "\n"
elif key.find('CYGWINGCC') != -1:
SectionCYGWINGCC = " = " + Dict1.get(key) + "\n"
elif key.find('ELFGCC') != -1:
SectionELFGCC = " = " + Dict1.get(key) + "\n"
elif key.find('ICC') != -1:
SectionICC = " = " + Dict1.get(key) + "\n"
elif key.find('MYTOOLS') != -1:
SectionMYTOOLS = " = " + Dict1.get(key) + "\n"
else:
print "Error!"
#
# First need to check which arch
#
Archs = Platform.Header.SupArchList
BuildTargets = Platform.Header.BuildTargets
#if BuildTargets == StandardBuildTargets:
#print "Debug and Release both support" # skip debug/release string search
#else:
#print "need to search debug/release string"
if len(Archs) == 4:
Arch = "*"
SectionName = "[BuildOptions.Common]\n"
else:
for Arch in Archs:
if Arch == 'IA32':
SectionName = "[BuildOptions.IA32]\n"
elif Arch == 'X64':
SectionName = "[BuildOptions.X64]\n"
elif Arch == 'IPF':
SectionName = "[BuildOptions.IPF]\n"
elif Arch == 'EBC':
SectionName = "[BuildOptions.EBC]\n"
else:
print 'Error!'
Section = ""
if SectionWINDDK != "":
SectionWINDDK = "*_WINDDK3790x1830_" + Arch + "_CC_FLAGS" + SectionWINDDK
Section += SectionWINDDK
if SectionVS2003 != "":
SectionVS2003 = "*_VS2003_" + Arch + "_CC_FLAGS" + SectionVS2003
Section += SectionVS2003
if SectionVS2005EXP != "":
SectionVS2005EXP = "*_VS2005EXP_" + Arch + "_CC_FLAGS" + SectionVS2005EXP
Section += SectionVS2005EXP
if SectionVS2005STD != "":
SectionVS2005STD = "*_VS2005STD_" + Arch + "_CC_FLAGS" + SectionVS2005STD
Section += SectionVS2005STD
if SectionVS2005PRO != "":
SectionVS2005PRO = "*_VS2005PRO_" + Arch + "_CC_FLAGS" + SectionVS2005PRO
Section += SectionVS2005PRO
if SectionVS2005TEAMSUITE != "":
SectionVS2005TEAMSUITE = "*_VS2005TEAMSUITE_" + Arch + "_CC_FLAGS" + SectionVS2005TEAMSUITE
Section += SectionVS2005TEAMSUITE
if SectionUNIXGCC != "":
SectionUNIXGCC = "*_UNIXGCC_" + Arch + "_CC_FLAGS" + SectionUNIXGCC
Section += SectionUNIXGCC
if SectionCYGWINGCC != "":
SectionCYGWINGCC = "*_CYGWINGCC_" + Arch + "_CC_FLAGS" + SectionCYGWINGCC
Section += SectionCYGWINGCC
if SectionELFGCC != "":
SectionELFGCC = "*_ELFGCC_" + Arch + "_CC_FLAGS" + SectionELFGCC
Section += SectionELFGCC
if SectionICC != "":
SectionICC = "*_ICC_" + Arch + "_CC_FLAGS" + SectionICC
Section += SectionICC
if SectionMYTOOLS != "":
SectionMYTOOLS = "*_MYTOOLS_" + Arch + "_CC_FLAGS" + SectionMYTOOLS
Section += SectionMYTOOLS
List = []
List.append("################################################################################")
List.append("#")
List.append("# Build Options section - list of all Build Options supported by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + SectionName + Section
Section += "\n"
StoreTextFile(DscFile, Section)
## Store Libraries section
#
# Write [Libraries] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Library Classes section
# @param Platform An input Platform class object
#
def StorePlatformLibrariesSection(DscFile,Platform):
List = []
List.append("################################################################################")
List.append("#")
List.append("# Libraries section - list of all Libraries needed by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + '[Libraries]\n\n'
StoreTextFile(DscFile, Section)
## Return a Platform Library Class Item
#
# Read the input LibraryClass class object and return one line of Library Class Item.
#
# @param LibraryClass An input LibraryClass class object
#
# @retval LibraryClassItem A Module Library Class Item
#
def GetPlatformLibraryClassItem(LibraryClass):
LibraryClassList = []
LibraryClassList.append(LibraryClass.Name)
LibraryClassList.append(LibraryClass.FilePath)
return "|$(WORKSPACE)/".join(LibraryClassList).rstrip("|")
## Add item to a LibraryClass section
#
# Add an Item with specific Module Type to section dictionary.
# The possible duplication is ensured to be removed.
#
# @param Section Section dictionary indexed by CPU architecture
# @param SupModuleList LibraryClass SupModuleList: BASE, SEC, PEI_CORE, PEIM, etc
# @param Item The Item to be added to section dictionary
#
def AddToLibraryClassSection(Section, SupModuleList, Item):
for ModuleType in SupModuleList:
SectionModule = Section.get(ModuleType, [])
if Item not in SectionModule:
SectionModule.append(Item)
Section[ModuleType] = SectionModule
## Get Library Classes section contents
#
# Return the content of section named SectionName.
# the contents is based on Methods and ObjectLists.
#
# @param SectionName The name of the section
# @param Method A function returning a string item of an object
# @param ObjectList The list of object
#
# @retval Section The string content of a section
#
def GetLibraryClassesSection(SectionName, Method, ObjectList):
SupportedArches = ["COMMON", "IA32", "X64", "IPF", "EBC"]
ModuleTypes = ["BASE","SEC","PEI_CORE","PEIM","DXE_CORE","DXE_DRIVER","DXE_SMM_DRIVER","DXE_SAL_DRIVER","DXE_RUNTIME_DRIVER","UEFI_DRIVER","UEFI_APPLICATION"]
SectionCommonDict = {}
SectionIA32Dict = {}
SectionX64Dict = {}
SectionIPFDict = {}
SectionEBCDict = {}
#ObjectList = list(set(ObjectList)) # delete the same element in the list
for Object in ObjectList:
if Object == None:
continue
Item = Method(Object)
if Item == "":
continue
Item = " %s" % Item
Arches = Object.SupArchList
if len(Arches) == 4:
ModuleType = Object.ModuleType
# [LibraryClasses.Common.ModuleType]
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionCommonDict, SupModuleList, Item)
else:
#
SupModuleList = Object.SupModuleList
#AddToSection(SectionDict, "|".join(SupModuleList), Item)
AddToLibraryClassSection(SectionCommonDict, SupModuleList, Item)
else:
# Arch
for Arch in SupportedArches:
if Arch.upper() in Arches:
if Arch == "IA32":
# [LibraryClasses.IA32.ModuleType]
ModuleType = Object.ModuleType
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionIA32Dict, SupModuleList, Item)
else:
SupModuleList = Object.SupModuleList
AddToLibraryClassSection(SectionIA32Dict, SupModuleList, Item)
elif Arch == "X64":
# [LibraryClasses.X64.ModuleType]
ModuleType = Object.ModuleType
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionX64Dict, SupModuleList, Item)
else:
SupModuleList = Object.SupModuleList
AddToLibraryClassSection(SectionX64Dict, SupModuleList, Item)
elif Arch == "IPF":
# [LibraryClasses.IPF.ModuleType]
ModuleType = Object.ModuleType
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionIPFDict, SupModuleList, Item)
else:
SupModuleList = Object.SupModuleList
AddToLibraryClassSection(SectionIPFDict, SupModuleList, Item)
elif Arch == "EBC":
# [LibraryClasses.EBC.ModuleType]
ModuleType = Object.ModuleType
if ModuleType == "BASE":
SupModuleList = ["BASE"]
AddToLibraryClassSection(SectionEBCDict, SupModuleList, Item)
else:
SupModuleList = Object.SupModuleList
AddToLibraryClassSection(SectionEBCDict, SupModuleList, Item)
Section = ""
for ModuleType in ModuleTypes:
SectionCommonModule = "\n".join(SectionCommonDict.get(ModuleType, []))
if SectionCommonModule != "":
Section += "[%s.Common.%s]\n%s\n" % (SectionName, ModuleType, SectionCommonModule)
Section += "\n"
for ModuleType in ModuleTypes:
ListIA32 = SectionIA32Dict.get(ModuleType, [])
if ListIA32 != []:
SectionIA32Module = "\n".join(SectionIA32Dict.get(ModuleType, []))
if SectionIA32Module != "":
Section += "[%s.IA32.%s]\n%s\n" % (SectionName, ModuleType, SectionIA32Module)
Section += "\n"
ListX64 = SectionX64Dict.get(ModuleType, [])
if ListX64 != []:
SectionX64Module = "\n".join(SectionX64Dict.get(ModuleType, []))
if SectionX64Module != "":
Section += "[%s.X64.%s]\n%s\n" % (SectionName, ModuleType, SectionX64Module)
Section += "\n"
ListIPF = SectionIPFDict.get(ModuleType, [])
if ListIPF != []:
SectionIPFModule = "\n".join(SectionIPFDict.get(ModuleType, []))
if SectionIPFModule != "":
Section += "[%s.IPF.%s]\n%s\n" % (SectionName, ModuleType, SectionIPFModule)
Section += "\n"
ListEBC = SectionEBCDict.get(ModuleType, [])
if ListEBC != []:
SectionEBCModule = "\n".join(SectionEBCDict.get(ModuleType, []))
if SectionEBCModule != "":
Section += "[%s.EBC.%s]\n%s\n" % (SectionName, ModuleType, SectionEBCModule)
Section += "\n"
if Section != "":
Section += "\n"
return Section
## Store Library Classes section
#
# Write [LibraryClasses] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Library Classes section
# @param Platform An input Platform class object
#
def StorePlatformLibraryClassesSection(DscFile, Platform):
Section = GetLibraryClassesSection("LibraryClasses", GetPlatformLibraryClassItem, Platform.LibraryClasses.LibraryList)
List = []
List.append("################################################################################")
List.append("#")
List.append("# Library Class section - list of all Library Classes needed by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + Section
StoreTextFile(DscFile, Section)
## Store Pcd section
#
# Write [Pcd] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Build Options section
# @param Platform An input Platform class object
#
def StorePlatformPcdSection(DscFile, Platform):
# {PcdsFixedAtBuild:String1, PcdsFixedAtBuild:String2, PcdsPatchableInModule:String3}
SectionDict = {}
#
# [PcdsFixedAtBuild], [PcdsPatchableInModule] and [PcdsFeatureFlag] are from platform.modules
# [PcdsDynamic] is from platform.DynamicPcdBuildDefinitions
#
Modules = Platform.Modules.ModuleList # it's a list of modules
for Module in Modules:
PcdBuildDefinitions = Module.PcdBuildDefinitions # it's a list of PcdData
for PcdData in PcdBuildDefinitions:
if PcdData.ItemType == "FEATURE_FLAG":
List = []
List.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List.append(PcdData.Value)
String = "|".join(List)
ItemType = PcdData.ItemType
SectionPcdsFeatureFlag = SectionDict.get(ItemType, [])
if String not in SectionPcdsFeatureFlag:
SectionPcdsFeatureFlag.append(String)
SectionDict[ItemType] = SectionPcdsFeatureFlag
else:
List = []
List.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List.append(PcdData.Value)
List.append(PcdData.Token)
List.append(PcdData.DatumType)
List.append(PcdData.MaxDatumSize)
String = "|".join(List)
ItemType = PcdData.ItemType
if PcdData.ItemType == "FIXED_AT_BUILD":
SectionPcdsFixedAtBuild = SectionDict.get(ItemType, [])
if String not in SectionPcdsFixedAtBuild:
SectionPcdsFixedAtBuild.append(String)
SectionDict[ItemType] = SectionPcdsFixedAtBuild
#elif PcdData.ItemType == "FEATURE_FLAG":
#SectionPcdsFeatureFlag = SectionDict.get(ItemType, [])
#if String not in SectionPcdsFeatureFlag:
#SectionPcdsFeatureFlag.append(String)
#SectionDict[ItemType] = SectionPcdsFeatureFlag
elif PcdData.ItemType == "PATCHABLE_IN_MODULE":
SectionPcdsPatchableInModule = SectionDict.get(ItemType, [])
if String not in SectionPcdsPatchableInModule:
SectionPcdsPatchableInModule.append(String)
SectionDict[ItemType] = SectionPcdsPatchableInModule
elif PcdData.ItemType == "DYNAMIC":
SectionPcdsDynamic = SectionDict.get(ItemType, [])
if String not in SectionPcdsDynamic:
SectionPcdsDynamic.append(String)
SectionDict[ItemType] = SectionPcdsDynamic
DynamicPcdBuildDefinitions = Platform.DynamicPcdBuildDefinitions # It's a list
for PcdBuildData in DynamicPcdBuildDefinitions:
List = []
List.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List.append(PcdData.Token)
List.append(PcdData.DatumType)
List.append(PcdData.MaxDatumSize)
String = "|".join(List)
if PcdBuildData.ItemType == "DYNAMIC":
ItemType = PcdBuildData.ItemType
SectionPcdsDynamic = SectionDict.get(ItemType, [])
if String not in SectionPcdsDynamic:
SectionPcdsDynamic.append(String)
SectionDict[ItemType] = SectionPcdsDynamic
ItemType = "FIXED_AT_BUILD"
Section = "[PcdsFixedAtBuild]\n " + "\n ".join(SectionDict.get(ItemType, []))
ItemType = "FEATURE_FLAG"
Section += "\n\n[PcdsFeatureFlag]\n " + "\n ".join(SectionDict.get(ItemType, []))
ItemType = "PATCHABLE_IN_MODULE"
Section += "\n\n[PcdsPatchableInModule]\n " + "\n ".join(SectionDict.get(ItemType, []))
Section += "\n\n"
List = []
List.append("################################################################################")
List.append("#")
List.append("# Pcd Dynamic Section - list of all EDK II PCD Entries defined by this Platform.")
List.append("#")
List.append("################################################################################")
String = "\n".join(List)
Section += String
ItemType = "DYNAMIC"
Section += "\n\n[PcdsDynamic]\n " + "\n ".join(SectionDict.get(ItemType, []))
Section += "\n\n"
List = []
List.append("################################################################################")
List.append("#")
List.append("# Pcd Section - list of all EDK II PCD Entries defined by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + Section
StoreTextFile(DscFile, Section)
## Add item to a section
#
# Add an Item with specific CPU architecture to section dictionary.
# The possible duplication is ensured to be removed.
#
# @param Section Section dictionary indexed by CPU architecture
# @param Arch CPU architecture: Ia32, X64, Ipf, Ebc or Common
# @param Item The Item to be added to section dictionary
#
def AddToSection(Section, Arch, Item):
SectionArch = Section.get(Arch, [])
if Item not in SectionArch:
SectionArch.append(Item)
Section[Arch] = SectionArch
## Get section contents
#
# Return the content of section named SectionName.
# the contents is based on Methods and ObjectLists.
#
# @param SectionName The name of the section
# @param Method A function returning a string item of an object
# @param ObjectList The list of object
#
# @retval Section The string content of a section
#
def GetSection(SectionName, Method, ObjectList):
SupportedArches = ["COMMON", "IA32", "X64", "IPF", "EBC"]
SectionDict = {}
for Object in ObjectList:
if Object.FilePath == "":
continue
Item = Method(Object)
if Item == "":
continue
Item = " %s" % Item
Arches = Object.SupArchList
if len(Arches) == 4:
AddToSection(SectionDict, "common", Item)
else:
for Arch in SupportedArches:
if Arch.upper() in Arches:
AddToSection(SectionDict, Arch, Item)
Section = ""
for Arch in SupportedArches:
SectionArch = "\n".join(SectionDict.get(Arch, []))
if SectionArch != "":
Section += "[%s.%s]\n%s\n" % (SectionName, Arch, SectionArch)
Section += "\n"
if Section != "":
Section += "\n"
return Section
## Return a Platform Component Item
#
# Read the input Platform Component object and return one line of Platform Component Item.
#
# @param Component An input Platform Component class object
#
# @retval ComponentItem A Platform Component Item
#
def GetPlatformComponentItem(Component):
List = []
Section = {}
List.append("$(WORKSPACE)/" + Component.FilePath)
LibraryClasses = Component.LibraryClasses
if LibraryClasses != []:
List = []
List.append("$(WORKSPACE)/" + Component.FilePath + " {")
List.append("<LibraryClasses>")
for LibraryClass in LibraryClasses:
if LibraryClass == ["", ""]:
continue
List.append(" " + LibraryClass[0] + "|$(WORKSPACE)/" + LibraryClass[1])
PcdBuildDefinitions = Component.PcdBuildDefinitions
for PcdData in PcdBuildDefinitions:
if PcdData.ItemType == "FEATURE_FLAG":
List1 = []
List1.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List1.append(PcdData.Value)
String = "|".join(List1)
ItemType = PcdData.ItemType
SectionPcd = Section.get(ItemType, [])
if String not in SectionPcd:
SectionPcd.append(String)
Section[ItemType] = SectionPcd
else:
List1 = []
List1.append(PcdData.TokenSpaceGuidCName + "." + PcdData.C_NAME)
List1.append(PcdData.Value)
List1.append(PcdData.Token)
List1.append(PcdData.DatumType)
List1.append(PcdData.MaxDatumSize)
String = "|".join(List1)
ItemType = PcdData.ItemType
if ItemType == "FIXED_AT_BUILD":
SectionPcd = Section.get(ItemType, [])
if String not in SectionPcd:
SectionPcd.append(String)
Section[ItemType] = SectionPcd
#elif ItemType == "FEATURE_FLAG":
#SectionPcd = Section.get(ItemType, [])
#if String not in SectionPcd:
#SectionPcd.append(String)
#Section[ItemType] = SectionPcd
elif ItemType == "PATCHABLE_IN_MODULE":
SectionPcd = Section.get(ItemType, [])
if String not in SectionPcd:
SectionPcd.append(String)
Section[ItemType] = SectionPcd
elif ItemType == "DYNAMIC":
SectionPcd = Section.get(ItemType, [])
if String not in SectionPcd:
SectionPcd.append(String)
Section[ItemType] = SectionPcd
ItemType = "FIXED_AT_BUILD"
if Section.get(ItemType, []) != []:
List.append("<PcdsFixedAtBuild>")
List.append(" " + "\n ".join(Section.get(ItemType,[])))
ItemType = "FEATURE_FLAG"
if Section.get(ItemType, []) != []:
List.append("<PcdsFeatureFlag>")
List.append(" " + "\n ".join(Section.get(ItemType,[])))
ItemType = "PATCHABLE_IN_MODULE"
if Section.get(ItemType, []) != []:
List.append("<PcdsPatchableInModule>")
List.append(" " + "\n ".join(Section.get(ItemType,[])))
ItemType = "DYNAMIC"
if Section.get(ItemType, []) != []:
List.append("<PcdsDynamic>")
List.append(" " + "\n ".join(Section.get(ItemType,[])))
ListOption = []
SectionOption = ""
ListBuildOptions = Component.BuildOptions # a list
if ListBuildOptions != []:
SectionOption += "\n <BuildOptions>\n"
for BuildOptions in ListBuildOptions:
Options = BuildOptions.Options
for Option in Options:
for Item in Option.BuildTargetList:
ListOption.append(Item)
List.append(Option.ToolChainFamily)
for Item in Option.SupArchList:
ListOption.append(Item)
ListOption.append(Option.ToolCode)
ListOption.append("FLAGS")
#print ListOption
SectionOption += " " + "_".join(List) + " = " + Option.Option + "\n"
ListOption = []
if SectionOption != "":
List.append(SectionOption)
if List != ["$(WORKSPACE)/" + Component.FilePath]:
List.append("}\n")
return "\n ".join(List)
## Store Components section.
#
# Write [Components] section to the DscFile based on Platform class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the Components section
# @param Platform An input Platform class object
#
def StorePlatformComponentsSection(DscFile, Platform):
Section = GetSection("Components", GetPlatformComponentItem, Platform.Modules.ModuleList)
List = []
List.append("################################################################################")
List.append("#")
List.append("# Components Section - list of all EDK II Modules needed by this Platform.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + Section
StoreTextFile(DscFile, Section)
## Store User Extensions section.
#
# Write [UserExtensions] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DscFile The output DSC file to store the User Extensions section
# @param Platform An input Platform class object
#
def StorePlatformUserExtensionsSection(DscFile, Platform):
Section = "".join(map(GetUserExtensions, Platform.UserExtensions))
List = []
List.append("################################################################################")
List.append("#")
List.append("# User Extensions Section - list of all User Extensions specified by user.")
List.append("#")
List.append("################################################################################")
SectionHeader = "\n".join(List)
SectionHeader += "\n"
Section = SectionHeader + Section
StoreTextFile(DscFile, Section)
## Store a Platform class object to a new DSC file.
#
# Read an input Platform class object and save the contents to a new DSC file.
#
# @param DSCFileName The output DSC file
# @param Platform An input Platform class object
#
def StoreDsc(DscFileName, Platform):
DscFile = open(DscFileName, "w+")
EdkLogger.info("Save file to %s" % DscFileName)
StoreHeader(DscFile, Platform.Header)
StorePlatformDefinesSection(DscFile, Platform)
StorePlatformBuildOptionsSection(DscFile,Platform)
StorePlatformSkuIdsSection(DscFile,Platform)
StorePlatformLibrariesSection(DscFile,Platform) # new in dsc, Edk I components, list of INF files
StorePlatformLibraryClassesSection(DscFile, Platform) # LibraryClasses are from Modules
StorePlatformPcdSection(DscFile, Platform)
#StorePlatformPcdDynamicSection(DscFile, Platform)
StorePlatformComponentsSection(DscFile,Platform)
StorePlatformUserExtensionsSection(DscFile,Platform)
DscFile.close()
if __name__ == '__main__':
pass

View File

@@ -1,15 +0,0 @@
## @file
# Python 'fpd2dsc' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# 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.
#

View File

@@ -1,117 +0,0 @@
## @file
# Convert an XML-based FPD file to a text-based DSC file.
#
# 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.
#
##
# Import Modules
#
import os, re, sys, xml.dom.minidom #XmlRoutines, EdkIIWorkspace
from LoadFpd import LoadFpd
from StoreDsc import StoreDsc
from optparse import OptionParser
from Common.BuildVersion import gBUILD_VERSION
# Version and Copyright
__version_number__ = ("1.0" + " " + gBUILD_VERSION)
__version__ = "%prog Version " + __version_number__
__copyright__ = "Copyright (c) 2007 - 2010, Intel Corporation All rights reserved."
## 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 Args All the arguments got from the command line
#
def MyOptionParser():
""" Argument Parser """
usage = "%prog [options] input_filename"
parser = OptionParser(usage=usage,description=__copyright__,version="%prog " + str(__version_number__))
parser.add_option("-o", "--output", dest="outfile", help="Specific Name of the DSC file to create, otherwise it is the FPD filename with the extension repalced.")
parser.add_option("-a", "--auto", action="store_true", dest="autowrite", default=False, help="Automatically create output files and write the DSC file")
parser.add_option("-q", "--quiet", action="store_const", const=0, dest="verbose", help="Do not print any messages, just return either 0 for succes or 1 for failure")
parser.add_option("-v", "--verbose", action="count", dest="verbose", help="Do not print any messages, just return either 0 for succes or 1 for failure")
parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False, help="Enable printing of debug messages.")
parser.add_option("-w", "--workspace", dest="workspace", default=str(os.environ.get('WORKSPACE')), help="Specify workspace directory.")
(options, args) = parser.parse_args(sys.argv[1:])
return options,args
## 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():
global Options
global Args
global WorkSpace
Options,Args = MyOptionParser()
WorkSpace = ""
#print Options.workspace
if (Options.workspace == None):
print "ERROR: E0000: WORKSPACE not defined.\n Please set the WORKSPACE environment variable to the location of the EDK II install directory."
sys.exit(1)
else:
WorkSpace = Options.workspace
if (Options.debug):
print "Using Workspace:", WorkSpace
try:
Options.verbose +=1
except:
Options.verbose = 1
pass
InputFile = ""
if Args == []:
print "usage:" "%prog [options] input_filename"
else:
InputFile = Args[0]
#print InputFile
if InputFile != "":
FileName = InputFile
if ((Options.verbose > 1) | (Options.autowrite)):
print "FileName:",InputFile
else:
print "ERROR: E0001 - You must specify an input filename"
sys.exit(1)
if (Options.outfile):
OutputFile = Options.outfile
else:
OutputFile = FileName.replace('.fpd', '.dsc')
if ((Options.verbose > 2) or (Options.debug)):
print "Output Filename:", OutputFile
try:
Platform = LoadFpd(FileName)
StoreDsc(OutputFile, Platform)
return 0
except Exception, e:
print e
return 1
if __name__ == '__main__':
sys.exit(Main())
#pass
#global Options
#global Args
#Options,Args = MyOptionParser()
#Main()
#sys.exit(0)

View File

@@ -1,112 +0,0 @@
## @file
# Convert an MSA Module class object ot an INF Module class object by filling
# several info required by INF file.
#
# 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.
#
##
# Import Modules
#
from LoadMsa import LoadMsa
from StoreInf import StoreInf
from Common.MigrationUtilities import *
from EdkIIWorkspaceGuidsInfo import gEdkIIWorkspaceGuidsInfo
#The default INF version number tool generates.
gInfVersion = "0x00010005"
## Add required version information.
#
# Add the default INF version, EFI specificiation version and EDK release
# version to Module class object.
#
# @param Module An input Module class object.
#
def AddModuleMiscVersion(Module):
Version = gInfVersion
Module.Header.InfVersion = Version
Version = Module.Header.Specification.get("EFI_SPECIFICATION_VERSION", "")
Module.Header.UefiSpecificationVersion = Version
Version = Module.Header.Specification.get("EDK_RELEASE_VERSION", "")
Module.Header.EdkReleaseVersion = Version
## Add Module produced library class.
#
# Add the produced library class from library class list whose usage type is
# always produced.
#
# @param Module An input Module class object.
#
def AddModuleProducedLibraryClass(Module):
for LibraryClass in Module.LibraryClasses:
if "ALWAYS_PRODUCED" in LibraryClass.Usage:
Module.Header.LibraryClass.append(LibraryClass)
## Add Module Package Dependency path.
#
# Translate Package Dependency Guid to a file path relative to workspace.
#
# @param Module An input Module class object.
#
def AddModulePackageDependencyPath(Module):
for PackageDependency in Module.PackageDependencies:
PackageGuid = PackageDependency.PackageGuid
PackageVersion = PackageDependency.PackageVersion
GuidToFilePath = gEdkIIWorkspaceGuidsInfo.ResolvePackageFilePath
PackageFilePath = GuidToFilePath(PackageGuid, PackageVersion)
PackageDependency.FilePath = PackageFilePath
## Add Module Recommended Library Instance path.
#
# Translate Module Recommened Library Instance Guid to a file path relative to
# workspace.
#
# @param Module An input Module class object.
#
def AddModuleRecommonedLibraryInstancePath(Module):
for LibraryClass in Module.LibraryClasses:
if "ALWAYS_PRODUCED" in LibraryClass.Usage:
continue
if LibraryClass.RecommendedInstanceGuid == "":
continue
LibraryGuid = LibraryClass.RecommendedInstanceGuid
LibraryVersion = LibraryClass.RecommendedIntanceVersion
GuidToFilePath = gEdkIIWorkspaceGuidsInfo.ResolveModuleFilePath
LibraryInstance = GuidToFilePath(LibraryGuid, LibraryVersion)
LibraryClass.RecommendedIntance = LibraryInstance
## Convert MSA Module class object to INF Module class object.
#
# Convert MSA module class ojbect to INF Module class object by filling in
# several information required by INF file.
#
# @param Module An input Module class object.
#
def ConvertMsaModuleToInfModule(Module):
AddModuleMiscVersion(Module)
AddModuleProducedLibraryClass(Module)
AddModulePackageDependencyPath(Module)
AddModuleRecommonedLibraryInstancePath(Module)
if __name__ == '__main__':
pass

View File

@@ -1,325 +0,0 @@
## @file
# Collects the Guid Information in current workspace.
#
# 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 os
import fnmatch
from Common.EdkIIWorkspace import EdkIIWorkspace
from Common.MigrationUtilities import *
## A class for EdkII work space to resolve Guids.
#
# This class inherits from EdkIIWorkspace and collects the Guids information
# in current workspace. The Guids information is important to translate the
# package Guids and recommended library instances Guids to relative file path
# (to workspace directory) in MSA files.
#
class EdkIIWorkspaceGuidsInfo(EdkIIWorkspace):
## The classconstructor.
#
# The constructor initialize workspace directory. It does not collect
# pakage and module Guids info at initialization; instead, it collects them
# on the fly.
#
# @param self The object pointer.
#
def __init__(self):
# Initialize parent class.
EdkIIWorkspace.__init__(self)
# The internal map from Guid to FilePath.
self.__GuidToFilePath = {}
# The internal package directory list.
self.__PackageDirList = []
# The internal flag to indicate whether package Guids info has been
# to avoid re-collection collected.
self.__PackageGuidInitialized = False
# The internal flag to indicate whether module Guids info has been
# to avoid re-collection collected.
self.__ModuleGuidInitialized = False
## Add Guid, Version and FilePath to Guids database.
#
# Add Guid, Version and FilePath to Guids database. It constructs a map
# table from Guid, Version to FilePath internally. If also detects possible
# Guid collision. For now, the version information is simply ignored and
# Guid value itself acts as master key.
#
# @param self The object pointer.
# @param Guid The Guid Value.
# @param Version The version information
#
# @retval True The Guid value is successfully added to map table.
# @retval False The Guid is an empty string or the map table
# already contains a same Guid.
#
def __AddGuidToFilePath(self, Guid, Version, FilePath):
if Guid == "":
EdkLogger.info("Cannot find Guid in file %s" % FilePath)
return False
#Add the Guid value to map table to ensure case insensitive comparison.
OldFilePath = self.__GuidToFilePath.setdefault(Guid.lower(), FilePath)
if OldFilePath == FilePath:
EdkLogger.verbose("File %s has new Guid '%s'" % (FilePath, Guid))
return True
else:
EdkLogger.info("File %s has duplicate Guid with & %s" % (FilePath, OldFilePath))
return False
## Gets file information from a module description file.
#
# Extracts Module Name, File Guid and Version number from INF, MSA and NMSA
# file. It supports to exact such information from text based INF file or
# XML based (N)MSA file.
#
# @param self The object pointer.
# @param FileName The input module file name.
#
# @retval True This module file represents a new module discovered
# in current workspace.
# @retval False This module file is not regarded as a valid module.
# The File Guid cannot be extracted or the another
# file with the same Guid already exists
#
def __GetModuleFileInfo(self, FileName):
if fnmatch.fnmatch(FileName, "*.inf"):
TagTuple = ("BASE_NAME", "FILE_GUID", "VERSION_STRING")
(Name, Guid, Version) = GetTextFileInfo(FileName, TagTuple)
else :
XmlTag1 = "ModuleSurfaceArea/MsaHeader/ModuleName"
XmlTag2 = "ModuleSurfaceArea/MsaHeader/GuidValue"
XmlTag3 = "ModuleSurfaceArea/MsaHeader/Version"
TagTuple = (XmlTag1, XmlTag2, XmlTag3)
(Name, Guid, Version) = GetXmlFileInfo(FileName, TagTuple)
return self.__AddGuidToFilePath(Guid, Version, FileName)
## Gets file information from a package description file.
#
# Extracts Package Name, File Guid and Version number from INF, SPD and NSPD
# file. It supports to exact such information from text based DEC file or
# XML based (N)SPD file. EDK Compatibility Package is hardcoded to be
# ignored since no EDKII INF file depends on that package.
#
# @param self The object pointer.
# @param FileName The input package file name.
#
# @retval True This package file represents a new package
# discovered in current workspace.
# @retval False This package is not regarded as a valid package.
# The File Guid cannot be extracted or the another
# file with the same Guid already exists
#
def __GetPackageFileInfo(self, FileName):
if fnmatch.fnmatch(FileName, "*.dec"):
TagTuple = ("PACKAGE_NAME", "PACKAGE_GUID", "PACKAGE_VERSION")
(Name, Guid, Version) = GetTextFileInfo(FileName, TagTuple)
else:
XmlTag1 = "PackageSurfaceArea/SpdHeader/PackageName"
XmlTag2 = "PackageSurfaceArea/SpdHeader/GuidValue"
XmlTag3 = "PackageSurfaceArea/SpdHeader/Version"
TagTuple = (XmlTag1, XmlTag2, XmlTag3)
(Name, Guid, Version) = GetXmlFileInfo(FileName, TagTuple)
if Name == "EdkCompatibilityPkg":
# Do not scan EDK compatibitilty package to avoid Guid collision
# with those in EDK Glue Library.
EdkLogger.verbose("Bypass EDK Compatibility Pkg")
return False
return self.__AddGuidToFilePath(Guid, Version, FileName)
## Iterate on all package files listed in framework database file.
#
# Yields all package description files listed in framework database files.
# The framework database file describes the packages current workspace
# includes.
#
# @param self The object pointer.
#
def __FrameworkDatabasePackageFiles(self):
XmlFrameworkDb = XmlParseFile(self.WorkspaceFile)
XmlTag = "FrameworkDatabase/PackageList/Filename"
for PackageFile in XmlElementList(XmlFrameworkDb, XmlTag):
yield os.path.join(self.WorkspaceDir, PackageFile)
## Iterate on all package files in current workspace directory.
#
# Yields all package description files listed in current workspace
# directory. This happens when no framework database file exists.
#
# @param self The object pointer.
#
def __TraverseAllPackageFiles(self):
for Path, Dirs, Files in os.walk(self.WorkspaceDir):
# Ignore svn version control directory.
if ".svn" in Dirs:
Dirs.remove(".svn")
if "Build" in Dirs:
Dirs.remove("Build")
# Assume priority from high to low: DEC, NSPD, SPD.
PackageFiles = fnmatch.filter(Files, "*.dec")
if len(PackageFiles) == 0:
PackageFiles = fnmatch.filter(Files, "*.nspd")
if len(PackageFiles) == 0:
PackageFiles = fnmatch.filter(Files, "*.spd")
for File in PackageFiles:
# Assume no more package decription file in sub-directory.
del Dirs[:]
yield os.path.join(Path, File)
## Iterate on all module files in current package directory.
#
# Yields all module description files listed in current package
# directory.
#
# @param self The object pointer.
#
def __TraverseAllModuleFiles(self):
for PackageDir in self.__PackageDirList:
for Path, Dirs, Files in os.walk(PackageDir):
# Ignore svn version control directory.
if ".svn" in Dirs:
Dirs.remove(".svn")
# Assume priority from high to low: INF, NMSA, MSA.
ModuleFiles = fnmatch.filter(Files, "*.inf")
if len(ModuleFiles) == 0:
ModuleFiles = fnmatch.filter(Files, "*.nmsa")
if len(ModuleFiles) == 0:
ModuleFiles = fnmatch.filter(Files, "*.msa")
for File in ModuleFiles:
yield os.path.join(Path, File)
## Initialize package Guids info mapping table.
#
# Collects all package guids map to package decription file path. This
# function is invokes on demand to avoid unnecessary directory scan.
#
# @param self The object pointer.
#
def __InitializePackageGuidInfo(self):
if self.__PackageGuidInitialized:
return
EdkLogger.verbose("Start to collect Package Guids Info.")
WorkspaceFile = os.path.join("Conf", "FrameworkDatabase.db")
self.WorkspaceFile = os.path.join(self.WorkspaceDir, WorkspaceFile)
# Try to find the frameworkdatabase file to discover package lists
if os.path.exists(self.WorkspaceFile):
TraversePackage = self.__FrameworkDatabasePackageFiles
EdkLogger.verbose("Package list bases on: %s" % self.WorkspaceFile)
else:
TraversePackage = self.__TraverseAllPackageFiles
EdkLogger.verbose("Package list in: %s" % self.WorkspaceDir)
for FileName in TraversePackage():
if self.__GetPackageFileInfo(FileName):
PackageDir = os.path.dirname(FileName)
EdkLogger.verbose("Find new package directory %s" % PackageDir)
self.__PackageDirList.append(PackageDir)
self.__PackageGuidInitialized = True
## Initialize module Guids info mapping table.
#
# Collects all module guids map to module decription file path. This
# function is invokes on demand to avoid unnecessary directory scan.
#
# @param self The object pointer.
#
def __InitializeModuleGuidInfo(self):
if self.__ModuleGuidInitialized:
return
EdkLogger.verbose("Start to collect Module Guids Info")
self.__InitializePackageGuidInfo()
for FileName in self.__TraverseAllModuleFiles():
if self.__GetModuleFileInfo(FileName):
EdkLogger.verbose("Find new module %s" % FileName)
self.__ModuleGuidInitialized = True
## Get Package file path by Package guid and Version.
#
# Translates the Package Guid and Version to a file path relative
# to workspace directory. If no package in current workspace match the
# input Guid, an empty file path is returned. For now, the version
# value is simply ignored.
#
# @param self The object pointer.
# @param Guid The Package Guid value to look for.
# @param Version The Package Version value to look for.
#
def ResolvePackageFilePath(self, Guid, Version = ""):
self.__InitializePackageGuidInfo()
EdkLogger.verbose("Resolve Package Guid '%s'" % Guid)
FileName = self.__GuidToFilePath.get(Guid.lower(), "")
if FileName == "":
EdkLogger.info("Cannot resolve Package Guid '%s'" % Guid)
else:
FileName = self.WorkspaceRelativePath(FileName)
FileName = os.path.splitext(FileName)[0] + ".dec"
FileName = FileName.replace("\\", "/")
return FileName
## Get Module file path by Package guid and Version.
#
# Translates the Module Guid and Version to a file path relative
# to workspace directory. If no module in current workspace match the
# input Guid, an empty file path is returned. For now, the version
# value is simply ignored.
#
# @param self The object pointer.
# @param Guid The Module Guid value to look for.
# @param Version The Module Version value to look for.
#
def ResolveModuleFilePath(self, Guid, Version = ""):
self.__InitializeModuleGuidInfo()
EdkLogger.verbose("Resolve Module Guid '%s'" % Guid)
FileName = self.__GuidToFilePath.get(Guid.lower(), "")
if FileName == "":
EdkLogger.info("Cannot resolve Module Guid '%s'" % Guid)
else:
FileName = self.WorkspaceRelativePath(FileName)
FileName = os.path.splitext(FileName)[0] + ".inf"
FileName = FileName.replace("\\", "/")
return FileName
# A global class object of EdkIIWorkspaceGuidsInfo for external reference.
gEdkIIWorkspaceGuidsInfo = EdkIIWorkspaceGuidsInfo()
# This acts like the main() function for the script, unless it is 'import'ed
# into another script.
if __name__ == '__main__':
# Test the translation of package Guid.
MdePkgGuid = "1E73767F-8F52-4603-AEB4-F29B510B6766"
OldMdePkgGuid = "5e0e9358-46b6-4ae2-8218-4ab8b9bbdcec"
print gEdkIIWorkspaceGuidsInfo.ResolveModuleFilePath(MdePkgGuid)
print gEdkIIWorkspaceGuidsInfo.ResolveModuleFilePath(OldMdePkgGuid)
# Test the translation of module Guid.
UefiLibGuid = "3a004ba5-efe0-4a61-9f1a-267a46ae5ba9"
UefiDriverModelLibGuid = "52af22ae-9901-4484-8cdc-622dd5838b09"
print gEdkIIWorkspaceGuidsInfo.ResolveModuleFilePath(UefiLibGuid)
print gEdkIIWorkspaceGuidsInfo.ResolveModuleFilePath(UefiDriverModelLibGuid)

View File

@@ -1,747 +0,0 @@
## @file
# Open an MSA file and load all its contents to a ModuleClass object.
#
# 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 os
from CommonDataClass.ModuleClass import *
from Common.XmlRoutines import *
from Common.MigrationUtilities import *
## Load a list of Module Cloned Records.
#
# Read an input Module XML DOM object and return a list of Cloned Records
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel ClonedRecords A list of Cloned Records loaded from XmlMsa.
#
def LoadModuleClonedRecords(XmlMsa):
XmlTag = "ModuleSurfaceArea/ModuleDefinitions/ClonedFrom/Cloned"
return map(LoadClonedRecord, XmlList(XmlMsa, XmlTag))
## Load Module Header.
#
# Read an input Module XML DOM object and return Module Header class object
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
# @param MsaFileName The file path of MSA File.
#
# @retvel ModuleHeader A new Module Header object loaded from XmlMsa.
#
def LoadModuleHeader(XmlMsa, MsaFileName):
ModuleHeader = ModuleHeaderClass()
XmlTag = "ModuleSurfaceArea/MsaHeader"
MsaHeader = XmlNode(XmlMsa, XmlTag)
SetIdentification(ModuleHeader, MsaHeader, "ModuleName", MsaFileName)
SetCommonHeader(ModuleHeader, MsaHeader)
XmlTag = "ModuleSurfaceArea/ModuleDefinitions/SupportedArchitectures"
ModuleHeader.SupArchList = XmlElement(XmlMsa, XmlTag).split()
XmlTag = "ModuleSurfaceArea/ModuleDefinitions/BinaryModule"
if XmlElement(XmlMsa, XmlTag).lower() == "true":
ModuleHeader.BinaryModule = True
XmlTag = "ModuleSurfaceArea/ModuleDefinitions/OutputFileBasename"
ModuleHeader.OutputFileBasename = XmlElement(XmlMsa, XmlTag)
XmlTag = "ModuleSurfaceArea/ModuleDefinitions/ClonedForm"
ModuleHeader.ClonedFrom = LoadModuleClonedRecords(XmlMsa)
XmlTag = "ModuleSurfaceArea/Externs/PcdDriverTypes"
ModuleHeader.PcdIsDriver = XmlElement(XmlMsa, XmlTag)
XmlTag = "ModuleSurfaceArea/Externs/TianoEdkFlashMap_h"
if XmlElement(XmlMsa, XmlTag).lower() == "true":
ModuleHeader.TianoEdkFlashMap_h = True
XmlTag = "ModuleSurfaceArea/Externs/Specification"
for Specification in XmlElementList(XmlMsa, XmlTag):
AddToSpecificationDict(ModuleHeader.Specification, Specification)
return ModuleHeader
## Load a list of Module Library Classes.
#
# Read an input Module XML DOM object and return a list of Library Classes
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel LibraryClasses A list of Library Classes loaded from XmlMsa.
#
def LoadModuleLibraryClasses(XmlMsa):
XmlTag = "ModuleSurfaceArea/LibraryClassDefinitions/LibraryClass"
return map(LoadLibraryClass, XmlList(XmlMsa, XmlTag))
## Load a new Module Source class object.
#
# Read an input XML Source DOM object and return an object of Source
# contained in the DOM object.
#
# @param XmlFilename A child XML DOM object in Module XML DOM.
#
# @retvel ModuleSource A new Source object created by XmlFilename.
#
def LoadModuleSource(XmlFilename):
ModuleSource = ModuleSourceFileClass()
ModuleSource.SourceFile = XmlElementData(XmlFilename)
XmlTag = "TagName"
ModuleSource.TagName = XmlAttribute(XmlFilename, XmlTag)
XmlTag = "ToolCode"
ModuleSource.ToolCode = XmlAttribute(XmlFilename, XmlTag)
XmlTag = "ToolChainFamily"
ModuleSource.ToolChainFamily = XmlAttribute(XmlFilename, XmlTag)
SetCommon(ModuleSource, XmlFilename)
return ModuleSource
## Load a list of Module Sources.
#
# Read an input Module XML DOM object and return a list of Sources
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel Sources A list of Sources loaded from XmlMsa.
#
def LoadModuleSources(XmlMsa):
XmlTag = "ModuleSurfaceArea/SourceFiles/Filename"
return map(LoadModuleSource, XmlList(XmlMsa, XmlTag))
## Load a new Module Binary class object.
#
# Read an input XML Binary DOM object and return an object of Binary
# contained in the DOM object.
#
# @param XmlFilename A child XML DOM object in Module XML DOM.
#
# @retvel ModuleBinary A new Binary object created by XmlFilename.
#
def LoadModuleBinary(XmlFilename):
ModuleBinary = ModuleBinaryFileClass()
ModuleBinary.BinaryFile = XmlElementData(XmlFilename)
XmlTag = "FileType"
ModuleBinary.FileType = XmlElementAttribute(XmlFilename, XmlTag)
SetCommon(ModuleBinary, XmlFilename)
## Load a list of Module Binaries.
#
# Read an input Module XML DOM object and return a list of Binaries
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel Binaries A list of Binaries loaded from XmlMsa.
#
def LoadModuleBinaries(XmlMsa):
XmlTag = "ModuleSurfaceArea/BinaryFiles/Filename"
return map(LoadModuleBinary, XmlList(XmlMsa, XmlTag))
## Load a list of Module Non Processed Files.
#
# Read an input Module XML DOM object and return a list of Non Processed Files
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel NonProcessedFiles A list of Non Processed Files loaded from XmlMsa.
#
def LoadModuleNonProcessedFiles(XmlMsa):
XmlTag = "ModuleSurfaceArea/NonProcessedFiles/Filename"
return XmlElementList(XmlMsa, XmlTag)
## Load a new Module Package Dependency class object.
#
# Read an input XML PackageDependency DOM object and return an object of Package Dependency
# contained in the DOM object.
#
# @param XmlPackage A child XML DOM object in Module XML DOM.
#
# @retvel ModulePackageDependency A new Package Dependency object created by XmlPackage.
#
def LoadModulePackageDependency(XmlPackage):
ModulePackageDependency = ModulePackageDependencyClass()
XmlTag = "PackageGuid"
PackageKey = XmlAttribute(XmlPackage, XmlTag)
#
#TODO: Add resolution for Package name, package Version
#
ModulePackageDependency.PackageGuid = PackageKey
SetCommon(ModulePackageDependency, XmlPackage)
return ModulePackageDependency
## Load a list of Module Package Dependencies.
#
# Read an input Module XML DOM object and return a list of Package Dependencies
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel PackageDependencies A list of Package Dependencies loaded from XmlMsa.
#
def LoadModulePackageDependencies(XmlMsa):
XmlTag = "ModuleSurfaceArea/PackageDependencies/Package"
return map(LoadModulePackageDependency, XmlList(XmlMsa, XmlTag))
## Load a list of Module Protocols.
#
# Read an input Module XML DOM object and return a list of Protocols
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel Protocols A list of Protocols loaded from XmlMsa.
#
def LoadModuleProtocols(XmlMsa):
XmlTag = "ModuleSurfaceArea/Protocols/Protocol"
XmlProtocolList = XmlList(XmlMsa, XmlTag)
XmlTag = "ModuleSurfaceArea/Protocols/ProtocolNotify"
XmlProtocolList += XmlList(XmlMsa, XmlTag)
return map(LoadGuidProtocolPpiCommon, XmlProtocolList)
## Load a list of Module Ppis.
#
# Read an input Module XML DOM object and return a list of Ppis
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel Ppis A list of Ppis loaded from XmlMsa.
#
def LoadModulePpis(XmlMsa):
XmlTag = "ModuleSurfaceArea/PPIs/Ppi"
XmlPpiList = XmlList(XmlMsa, XmlTag)
XmlTag = "ModuleSurfaceArea/PPIs/PpiNotify"
XmlPpiList += XmlList(XmlMsa, XmlTag)
return map(LoadGuidProtocolPpiCommon, XmlPpiList)
## Load a new Module Event class object.
#
# Read an input XML Event DOM object and return an object of Event
# contained in the DOM object.
#
# @param XmlEvent A child XML DOM object in Module XML DOM.
# @param Type Specify the event type: SIGNAL_EVENT or CREATE_EVENT.
#
# @retvel ModuleEvent A new Event object created by XmlEvent.
#
def LoadModuleEvent(XmlEvent, Type):
ModuleEvent = ModuleEventClass()
XmlTag = "EventTypes/EventType"
ModuleEvent.CName = XmlElement(XmlEvent, XmlTag)
XmlTag = "EventGuidCName"
ModuleEvent.GuidCName = XmlAttribute(XmlEvent, XmlTag)
ModuleEvent.Type = Type
SetCommon(ModuleEvent, XmlEvent)
return ModuleEvent
## Load a list of Module Events.
#
# Read an input Module XML DOM object and return a list of Events
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel Events A list of Events loaded from XmlMsa.
#
def LoadModuleEvents(XmlMsa):
ModuleEvents = []
XmlTag = "ModuleSurfaceArea/Events/CreateEvents/EventTypes"
for XmlCreateEvent in XmlList(XmlMsa, XmlTag):
ModuleEvent = LoadModuleEvent(XmlCreateEvent, "CREATE_EVENT")
ModuleEvents.append(ModuleEvent)
XmlTag = "ModuleSurfaceArea/Events/SignalEvents/EventTypes"
for XmlCreateEvent in XmlList(XmlMsa, XmlTag):
ModuleEvent = LoadModuleEvent(XmlCreateEvent, "SIGNAL_EVENT")
ModuleEvents.append(ModuleEvent)
return ModuleEvents
## Load a new Module Hob class object.
#
# Read an input XML Hob DOM object and return an object of Hob
# contained in the DOM object.
#
# @param XmlHob A child XML DOM object in Module XML DOM.
#
# @retvel ModuleHob A new Hob object created by XmlHob.
#
def LoadModuleHob(XmlHob):
ModuleHob = ModuleHobClass()
XmlTag = "HobTypes/HobType"
ModuleHob.Type = XmlElement(XmlHob, XmlTag)
XmlTag = "HobGuidCName"
ModuleHob.GuidCName = XmlAttribute(XmlHob, XmlTag)
SetCommon(ModuleHob, XmlHob)
return ModuleHob
## Load a list of Module Hobs.
#
# Read an input Module XML DOM object and return a list of Hobs
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel Hobs A list of Hobs loaded from XmlMsa.
#
def LoadModuleHobs(XmlMsa):
XmlTag = "ModuleSurfaceArea/Hobs/HobTypes"
return map(LoadModuleHob, XmlList(XmlMsa, XmlTag))
## Load a new Module Variable class object.
#
# Read an input XML Variable DOM object and return an object of Variable
# contained in the DOM object.
#
# @param XmlVariable A child XML DOM object in Module XML DOM.
#
# @retvel ModuleVariable A new Variable object created by XmlVariable.
#
def LoadModuleVariable(XmlVariable):
ModuleVariable = ModuleVariableClass()
XmlTag = "Variable/VariableName"
HexWordArray = XmlElement(XmlVariable, XmlTag).split()
try:
ModuleVariable.Name = "".join([unichr(int(a, 16)) for a in HexWordArray])
except:
ModuleVariable.Name = ""
XmlTag = "Variable/GuidC_Name"
ModuleVariable.GuidCName = XmlElement(XmlVariable, XmlTag)
SetCommon(ModuleVariable, XmlVariable)
return ModuleVariable
## Load a list of Module Variables.
#
# Read an input Module XML DOM object and return a list of Variables
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel Variables A list of Variables loaded from XmlMsa.
#
def LoadModuleVariables(XmlMsa):
XmlTag = "ModuleSurfaceArea/Variables/Variable"
return map(LoadModuleVariable, XmlList(XmlMsa, XmlTag))
## Load a new Module Boot Mode class object.
#
# Read an input XML BootMode DOM object and return an object of Boot Mode
# contained in the DOM object.
#
# @param XmlBootMode A child XML DOM object in Module XML DOM.
#
# @retvel ModuleBootMode A new Boot Mode object created by XmlBootMode.
#
def LoadModuleBootMode(XmlBootMode):
ModuleBootMode = ModuleBootModeClass()
XmlTag = "BootModeName"
ModuleBootMode.Name = XmlAttribute(XmlBootMode, XmlTag)
SetCommon(ModuleBootMode, XmlBootMode)
return ModuleBootMode
## Load a list of Module Boot Modes.
#
# Read an input Module XML DOM object and return a list of Boot Modes
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel BootModes A list of Boot Modes loaded from XmlMsa.
#
def LoadModuleBootModes(XmlMsa):
XmlTag = "ModuleSurfaceArea/BootModes/BootMode"
return map(LoadModuleBootMode, XmlList(XmlMsa, XmlTag))
## Load a new Module System Table class object.
#
# Read an input XML SystemTable DOM object and return an object of System Table
# contained in the DOM object.
#
# @param XmlSystemTable A child XML DOM object in Module XML DOM.
#
# @retvel ModuleSystemTable A new System Table object created by XmlSystemTable.
#
def LoadModuleSystemTable(XmlSystemTable):
ModuleSystemTable = ModuleSystemTableClass()
XmlTag = "SystemTable/SystemTableCName"
ModuleSystemTable.CName = XmlElement(XmlSystemTable, XmlTag)
SetCommon(ModuleSystemTable, XmlSystemTable)
return ModuleSystemTable
## Load a list of Module System Tables.
#
# Read an input Module XML DOM object and return a list of System Tables
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel SystemTables A list of System Tables loaded from XmlMsa.
#
def LoadModuleSystemTables(XmlMsa):
XmlTag = "ModuleSurfaceArea/SystemTables/SystemTableCNames"
return map(LoadModuleSystemTable, XmlList(XmlMsa, XmlTag))
## Load a new Module Data Hub class object.
#
# Read an input XML DataHub DOM object and return an object of Data Hub
# contained in the DOM object.
#
# @param XmlDataHub A child XML DOM object in Module XML DOM.
#
# @retvel ModuleDataHub A new Data Hub object created by XmlDataHub.
#
def LoadModuleDataHub(XmlDataHub):
ModuleDataHub = ModuleDataHubClass()
XmlTag = "DataHub/DataHubCName"
ModuleDataHub.CName = XmlElement(XmlDataHub, "DataHubCName")
SetCommon(ModuleDataHub, XmlDataHub)
return ModuleDataHub
## Load a list of Module Data Hubs.
#
# Read an input Module XML DOM object and return a list of Data Hubs
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel DataHubs A list of Data Hubs loaded from XmlMsa.
#
def LoadModuleDataHubs(XmlMsa):
XmlTag = "ModuleSurfaceArea/DataHubs/DataHubRecord"
return map(LoadModuleDataHub, XmlList(XmlMsa, XmlTag))
## Load a new Module Hii Package class object.
#
# Read an input XML HiiPackage DOM object and return an object of Hii Package
# contained in the DOM object.
#
# @param XmlHiiPackage A child XML DOM object in Module XML DOM.
#
# @retvel ModuleHiiPackage A new Hii Package object created by XmlHiiPackage.
#
def LoadModuleHiiPackage(XmlHiiPackage):
ModuleHiiPackage = ModuleHiiPackageClass()
XmlTag = "HiiPackage/HiiPackageCName"
ModuleHiiPackage.CName = XmlElement(XmlHiiPackage, "HiiCName")
SetCommon(ModuleHiiPackage, XmlHiiPackage)
return ModuleHiiPackage
## Load a list of Module Hii Packages.
#
# Read an input Module XML DOM object and return a list of Hii Packages
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel HiiPackages A list of Hii Packages loaded from XmlMsa.
#
def LoadModuleHiiPackages(XmlMsa):
XmlTag = "ModuleSurfaceArea/HiiPackages/HiiPackage"
return map(LoadModuleHiiPackage, XmlList(XmlMsa, XmlTag))
## Load a list of Module Guids.
#
# Read an input Module XML DOM object and return a list of Guids
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel Guids A list of Guids loaded from XmlMsa.
#
def LoadModuleGuids(XmlMsa):
XmlTag = "ModuleSurfaceArea/Guids/GuidCNames"
return map(LoadGuidProtocolPpiCommon, XmlList(XmlMsa, XmlTag))
## Load a list of Module Pcd Codes.
#
# Read an input Module XML DOM object and return a list of Pcd Codes
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel PcdCodes A list of Pcd Codes loaded from XmlMsa.
#
def LoadModulePcdCodes(XmlMsa):
XmlTag = "ModuleSurfaceArea/PcdCoded/PcdEntry"
return map(LoadPcd, XmlList(XmlMsa, XmlTag))
## Load a list of Module Extern Images.
#
# Read an input Module XML DOM object and return a list of Extern Images
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel ExternImages A list of Extern Images loaded from XmlMsa.
#
def LoadModuleExternImages(XmlMsa):
ModuleExternImages = []
XmlTag = "ModuleSurfaceArea/Externs/Extern"
for XmlExtern in XmlList(XmlMsa, XmlTag):
XmlTag = "Extern/ModuleEntryPoint"
ModuleEntryPoint = XmlElement(XmlExtern, XmlTag)
XmlTag = "Extern/ModuleUnloadImage"
ModuleUnloadImage = XmlElement(XmlExtern, XmlTag)
if ModuleEntryPoint == "" and ModuleUnloadImage == "":
continue
ModuleExtern = ModuleExternImageClass()
ModuleExtern.ModuleEntryPoint = ModuleEntryPoint
ModuleExtern.ModuleUnloadImage = ModuleUnloadImage
ModuleExternImages.append(ModuleExtern)
return ModuleExternImages
## Load a list of Module Extern Libraries.
#
# Read an input Module XML DOM object and return a list of Extern Libraries
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel ExternLibraries A list of Extern Libraries loaded from XmlMsa.
#
def LoadModuleExternLibraries(XmlMsa):
ModuleExternLibraries = []
XmlTag = "ModuleSurfaceArea/Externs/Extern"
for XmlExtern in XmlList(XmlMsa, XmlTag):
XmlTag = "Extern/Constructor"
Constructor = XmlElement(XmlExtern, XmlTag)
XmlTag = "Extern/Destructor"
Destructor = XmlElement(XmlExtern, XmlTag)
if Constructor == "" and Destructor == "":
continue
ModuleExtern = ModuleExternLibraryClass()
ModuleExtern.Constructor = Constructor
ModuleExtern.Destructor = Destructor
ModuleExternLibraries.append(ModuleExtern)
return ModuleExternLibraries
## Load a list of Module Extern Drivers.
#
# Read an input Module XML DOM object and return a list of Extern Drivers
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel ExternDrivers A list of Extern Drivers loaded from XmlMsa.
#
def LoadModuleExternDrivers(XmlMsa):
ModuleExternDrivers = []
XmlTag = "ModuleSurfaceArea/Externs/Extern"
for XmlExtern in XmlList(XmlMsa, XmlTag):
XmlTag = "Extern/DriverBinding"
DriverBinding = XmlElement(XmlExtern, XmlTag)
XmlTag = "Extern/ComponentName"
ComponentName = XmlElement(XmlExtern, XmlTag)
XmlTag = "Extern/DriverConfig"
DriverConfig = XmlElement(XmlExtern, XmlTag)
XmlTag = "Extern/DriverDiag"
DriverDiag = XmlElement(XmlExtern, XmlTag)
if DriverBinding == "":
continue
ModuleExtern = ModuleExternDriverClass()
ModuleExtern.DriverBinding = DriverBinding
ModuleExtern.ComponentName = ComponentName
ModuleExtern.DriverConfig = DriverConfig
ModuleExtern.DriverDiag = DriverDiag
ModuleExternDrivers.append(ModuleExtern)
return ModuleExternDrivers
## Load a list of Module Extern Call Backs.
#
# Read an input Module XML DOM object and return a list of Extern Call Backs
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel ExternCallBacks A list of Extern Call Backs loaded from XmlMsa.
#
def LoadModuleExternCallBacks(XmlMsa):
ModuleExternCallBacks = []
XmlTag = "ModuleSurfaceArea/Externs/Extern"
for XmlExtern in XmlList(XmlMsa, XmlTag):
XmlTag = "Extern/SetVirtualAddressMapCallBack"
SetVirtualAddressMap = XmlElement(XmlExtern, XmlTag)
XmlTag = "Extern/ExitBootServicesCallBack"
ExitBootServices = XmlElement(XmlExtern, XmlTag)
if SetVirtualAddressMap == "" and ExitBootServices == "":
continue
ModuleExtern = ModuleExternCallBackClass()
ModuleExtern.ExitBootServicesCallBack = ExitBootServices
ModuleExtern.SetVirtualAddressMapCallBack = SetVirtualAddressMap
ModuleExternCallBacks.append(ModuleExtern)
return ModuleExternCallBacks
## Load a list of Module Build Options.
#
# Read an input Module XML DOM object and return a list of Build Options
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel BuildOptions A list of Build Options loaded from XmlMsa.
#
def LoadModuleBuildOptions(XmlMsa):
XmlTag = "ModuleSurfaceArea/ModuleBuildOptions/Options/Option"
return map(LoadBuildOption, XmlList(XmlMsa, XmlTag))
## Load a list of Module User Extensions.
#
# Read an input Module XML DOM object and return a list of User Extensions
# contained in the DOM object.
#
# @param XmlMsa An XML DOM object read from MSA file.
#
# @retvel UserExtensions A list of User Extensions loaded from XmlMsa.
#
def LoadModuleUserExtensions(XmlMsa):
XmlTag = "ModuleSurfaceArea/UserExtensions"
return map(LoadUserExtensions, XmlList(XmlMsa, XmlTag))
## Load a new Module class object.
#
# Read an input MSA File and return a new Module class Object.
#
# @param MsaFileName An XML DOM object read from MSA file.
#
# @retvel Module A new Module class object loaded from MSA File.
#
def LoadMsa(MsaFileName):
XmlMsa = XmlParseFile(MsaFileName)
EdkLogger.verbose("Load MSA File: %s" % MsaFileName)
Module = ModuleClass()
Module.Header = LoadModuleHeader(XmlMsa, MsaFileName)
Module.LibraryClasses = LoadModuleLibraryClasses(XmlMsa)
Module.Sources = LoadModuleSources(XmlMsa)
Module.BinaryFiles = LoadModuleBinaries(XmlMsa)
Module.NonProcessedFiles = LoadModuleNonProcessedFiles(XmlMsa)
Module.PackageDependencies = LoadModulePackageDependencies(XmlMsa)
Module.Protocols = LoadModuleProtocols(XmlMsa)
Module.Ppis = LoadModulePpis(XmlMsa)
Module.Events = LoadModuleEvents(XmlMsa)
Module.Hobs = LoadModuleHobs(XmlMsa)
Module.Variables = LoadModuleVariables(XmlMsa)
Module.BootModes = LoadModuleBootModes(XmlMsa)
Module.SystemTables = LoadModuleSystemTables(XmlMsa)
Module.DataHubs = LoadModuleDataHubs(XmlMsa)
Module.HiiPackages = LoadModuleHiiPackages(XmlMsa)
Module.Guids = LoadModuleGuids(XmlMsa)
Module.PcdCodes = LoadModulePcdCodes(XmlMsa)
Module.ExternImages = LoadModuleExternImages(XmlMsa)
Module.ExternLibraries = LoadModuleExternLibraries(XmlMsa)
Module.ExternDrivers = LoadModuleExternDrivers(XmlMsa)
Module.ExternCallBacks = LoadModuleExternCallBacks(XmlMsa)
Module.BuildOptions = LoadModuleBuildOptions(XmlMsa)
Module.UserExtensions = LoadModuleUserExtensions(XmlMsa)
return Module
# This acts like the main() function for the script, unless it is 'import'ed
# into another script.
if __name__ == '__main__':
pass

View File

@@ -1,44 +0,0 @@
## @file
# Convert an XML-based MSA file to a text-based INF file.
#
# 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
from Common.MigrationUtilities import *
from LoadMsa import LoadMsa
from StoreInf import StoreInf
from ConvertModule import ConvertMsaModuleToInfModule
## 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:
Options, InputFile = MigrationOptionParser("MSA", "INF", "%prog")
Module = LoadMsa(InputFile)
ConvertMsaModuleToInfModule(Module)
StoreInf(Options.OutputFile, Module)
return 0
except Exception, e:
print e
return 1
if __name__ == '__main__':
sys.exit(Main())

View File

@@ -1,442 +0,0 @@
## @file
# Store a Module class object to an INF file.
#
# 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
#
from LoadMsa import LoadMsa
from CommonDataClass.ModuleClass import *
from Common.MigrationUtilities import *
## Get the produced library class.
#
# Return the item of Library Class based on Library .
#
# @param LibraryClasses A list of library classes the module produces.
#
# @retval LibraryClassItem A text format library class item.
#
def GetModuleLibraryClass(LibraryClasses):
ProducedLibraryClasses = []
for LibraryClass in LibraryClasses:
ProducedLibraryClass = LibraryClass.LibraryClass
SupportedModueTypes = " ".join(LibraryClass.SupModuleList)
if SupportedModueTypes != "":
ProducedLibraryClass += "|" + SupportedModueTypes
ProducedLibraryClasses.append(ProducedLibraryClass)
return "|".join(ProducedLibraryClasses)
## Store Defines section.
#
# Write [Defines] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Defines section.
# @param Module An input Module class object.
#
def StoreModuleDefinesSection(InfFile, Module):
ModuleHeader = Module.Header
DefinesTupleList = []
DefinesTupleList.append(("INF_VERSION", ModuleHeader.InfVersion))
if ModuleHeader.Name != "":
DefinesTupleList.append(("BASE_NAME", ModuleHeader.Name))
if ModuleHeader.Guid != "":
DefinesTupleList.append(("FILE_GUID", ModuleHeader.Guid))
if ModuleHeader.Version != "":
DefinesTupleList.append(("VERSION_STRING", ModuleHeader.Version))
if ModuleHeader.ModuleType != "":
DefinesTupleList.append(("MODULE_TYPE", ModuleHeader.ModuleType))
if ModuleHeader.UefiSpecificationVersion != "":
DefinesTupleList.append(("UEFI_SPECIFICATION_VERSION", ModuleHeader.UefiSpecificationVersion))
if ModuleHeader.EdkReleaseVersion != "":
DefinesTupleList.append(("EDK_RELEASE_VERSION", ModuleHeader.EdkReleaseVersion))
ProducedLibraryClass = GetModuleLibraryClass(ModuleHeader.LibraryClass)
if ProducedLibraryClass != "":
DefinesTupleList.append(("LIBRARY_CLASS", ProducedLibraryClass))
if ModuleHeader.MakefileName != "":
DefinesTupleList.append(("MAKEFILE_NAME", ModuleHeader.MakeFileName))
if ModuleHeader.PcdIsDriver != "":
DefinesTupleList.append(("PCD_DRIVER", "TRUE"))
if len(Module.ExternImages) > 0:
ModuleEntryPoint = Module.ExternImages[0].ModuleEntryPoint
ModuleUnloadImage = Module.ExternImages[0].ModuleUnloadImage
if ModuleEntryPoint != "":
DefinesTupleList.append(("ENTRY_POINT", ModuleEntryPoint))
if ModuleUnloadImage != "":
DefinesTupleList.append(("UNLOAD_IMAGE", ModuleUnloadImage))
if len(Module.ExternLibraries) > 0:
Constructor = Module.ExternLibraries[0].Constructor
Destructor = Module.ExternLibraries[0].Destructor
if Constructor != "":
DefinesTupleList.append(("CONSTRUCTOR", Constructor))
if Destructor != "":
DefinesTupleList.append(("DESTRUCTOR", Destructor))
StoreDefinesSection(InfFile, DefinesTupleList)
## Return a Module Source Item.
#
# Read the input ModuleSourceFile class object and return one line of Source Item.
#
# @param ModuleSourceFile An input ModuleSourceFile class object.
#
# @retval SourceItem A Module Source Item.
#
def GetModuleSourceItem(ModuleSourceFile):
Source = []
Source.append(ModuleSourceFile.SourceFile)
Source.append(ModuleSourceFile.ToolChainFamily)
Source.append(ModuleSourceFile.TagName)
Source.append(ModuleSourceFile.ToolCode)
Source.append(ModuleSourceFile.FeatureFlag)
return "|".join(Source).rstrip("|")
## Store Sources section.
#
# Write [Sources] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Sources section.
# @param Module An input Module class object.
#
def StoreModuleSourcesSection(InfFile, Module):
Section = GetSection("Sources", GetModuleSourceItem, Module.Sources)
StoreTextFile(InfFile, Section)
## Return a Module Binary Item.
#
# Read the input ModuleBinaryFile class object and return one line of Binary Item.
#
# @param ModuleBinaryFile An input ModuleBinaryFile class object.
#
# @retval BinaryItem A Module Binary Item.
#
def GetModuleBinaryItem(ModuleBinaryFile):
Binary = []
Binary.append(ModuleBinaryFile.FileType)
Binary.append(ModuleBinaryFile.BinaryFile)
Binary.append(ModuleBinaryFile.Target)
Binary.append(ModuleBinaryFile.FeatureFlag)
return "|".join(Binary).rstrip("|")
## Store Binaries section.
#
# Write [Binaries] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Binaries section.
# @param Module An input Module class object.
#
def StoreModuleBinariesSection(InfFile, Module):
Section = GetSection("Binaries", GetModuleBinaryItem, Module.Binaries)
StoreTextFile(InfFile, Section)
## Return a Module Library Class Item.
#
# Read the input LibraryClass class object and return one line of Library Class Item.
#
# @param LibraryClass An input LibraryClass class object.
#
# @retval LibraryClassItem A Module Library Class Item.
#
def GetModuleLibraryClassItem(LibraryClass):
if "ALWAYS_PRODUCED" in LibraryClass.Usage:
return ""
LibraryClassList = []
LibraryClassList.append(LibraryClass.LibraryClass)
LibraryClassList.append(LibraryClass.RecommendedInstance)
LibraryClassList.append(LibraryClass.FeatureFlag)
return "|".join(LibraryClassList).rstrip("|")
## Store Library Classes section.
#
# Write [LibraryClasses] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Library Classes section.
# @param Module An input Module class object.
#
def StoreModuleLibraryClassesSection(InfFile, Module):
Section = GetSection("LibraryClasses", GetModuleLibraryClassItem, Module.LibraryClasses)
StoreTextFile(InfFile, Section)
## Return a Module Package Item.
#
# Read the input PackageDependency class object and return one line of Package Item.
#
# @param PackageDependency An input PackageDependency class object.
#
# @retval PackageItem A Module Package Item.
#
def GetModulePackageItem(PackageDependency):
return PackageDependency.FilePath
## Store Packages section.
#
# Write [Packages] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Packages section.
# @param Module An input Module class object.
#
def StoreModulePackagesSection(InfFile, Module):
Section = GetSection("Packages", GetModulePackageItem, Module.PackageDependencies)
StoreTextFile(InfFile, Section)
## Return a Module Guid C Name Item.
#
# Read the input Guid class object and return one line of Guid C Name Item.
#
# @param Guid An input Guid class object.
#
# @retval GuidCNameItem A Module Guid C Name Item.
#
def GetModuleGuidCNameItem(Guid):
try:
return Guid.GuidCName
except:
return Guid.CName
## Store Protocols section.
#
# Write [Protocols] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Protocols section.
# @param Module An input Module class object.
#
def StoreModuleProtocolsSection(InfFile, Module):
Section = GetSection("Protocols", GetModuleGuidCNameItem, Module.Protocols)
StoreTextFile(InfFile, Section)
## Store Ppis section.
#
# Write [Ppis] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Ppis section.
# @param Module An input Module class object.
#
def StoreModulePpisSection(InfFile, Module):
Section = GetSection("Ppis", GetModuleGuidCNameItem, Module.Ppis)
StoreTextFile(InfFile, Section)
## Store Guids section.
#
# Write [Guids] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Guids section.
# @param Module An input Module class object.
#
def StoreModuleGuidsSection(InfFile, Module):
Guids = []
Guids += Module.Guids
Guids += Module.Events
Guids += Module.Hobs
Guids += Module.Variables
Guids += Module.SystemTables
Guids += Module.DataHubs
Guids += Module.HiiPackages
Section = GetSection("Guids", GetModuleGuidCNameItem, Guids)
StoreTextFile(InfFile, Section)
## Return a Module Pcd Item.
#
# Read the input Pcd class object and return one line of Pcd Item.
#
# @param Pcd An input Pcd class object.
#
# @retval PcdItem A Module Pcd Item.
#
def GetModulePcdItem(Pcd):
PcdItem = "%s.%s" % (Pcd.TokenSpaceGuidCName, Pcd.CName)
if Pcd.DefaultValue != "":
PcdItem = "%s|%s" % (PcdItem, Pcd.DefaultValue)
return PcdItem
## DEC Pcd Section Name dictionary indexed by PCD Item Type.
mInfPcdSectionNameDict = {
"FEATURE_FLAG" : "FeaturePcd",
"FIXED_AT_BUILD" : "FixedPcd",
"PATCHABLE_IN_MODULE" : "PatchPcd",
"DYNAMIC" : "Pcd",
"DYNAMIC_EX" : "PcdEx"
}
## Store Pcds section.
#
# Write [(PcdType)] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Pcds section.
# @param Module An input Module class object.
#
def StoreModulePcdsSection(InfFile, Module):
PcdsDict = {}
for Pcd in Module.PcdCodes:
PcdSectionName = mInfPcdSectionNameDict.get(Pcd.ItemType)
if PcdSectionName:
PcdsDict.setdefault(PcdSectionName, []).append(Pcd)
else:
EdkLogger.info("Unknown Pcd Item Type: %s" % Pcd.ItemType)
Section = ""
for PcdSectionName in PcdsDict:
Pcds = PcdsDict[PcdSectionName]
Section += GetSection(PcdSectionName, GetModulePcdItem, Pcds)
Section += "\n"
StoreTextFile(InfFile, Section)
## Return a Module Depex Item.
#
# Read the input Depex class object and return one line of Depex Item.
#
# @param Depex An input Depex class object.
#
# @retval DepexItem A Module Depex Item.
#
def GetModuleDepexItem(Depex):
return Depex.Depex
## Store Depex section.
#
# Write [Depex] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Depex section.
# @param Module An input Module class object.
#
def StoreModuleDepexSection(InfFile, Module):
Section = GetSection("Depex", GetModuleDepexItem, Module.Depex)
StoreTextFile(InfFile, Section)
## Return a Module Build Option Item.
#
# Read the input BuildOption class object and return one line of Build Option Item.
#
# @param BuildOption An input BuildOption class object.
#
# @retval BuildOptionItem A Module Build Option Item.
#
def GetModuleBuildOptionItem(BuildOption):
BuildTarget = BuildOption.BuildTarget
if BuildTarget == "":
BuildTarget = "*"
TagName = BuildOption.TagName
if TagName == "":
TagName = "*"
ToolCode = BuildOption.ToolCode
if ToolCode == "":
ToolCode = "*"
Item = "_".join((BuildTarget, TagName, "*", ToolCode, "Flag"))
ToolChainFamily = BuildOption.ToolChainFamily
if ToolChainFamily != "":
Item = "%s:%s" % (ToolChainFamily, Item)
return "%-30s = %s" % (Item, BuildOption.Option)
## Store Build Options section.
#
# Write [BuildOptions] section to the InfFile based on Module class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param InfFile The output INF file to store the Build Options section.
# @param Module An input Module class object.
#
def StoreModuleBuildOptionsSection(InfFile, Module):
Section = GetSection("BuildOption", GetModuleBuildOptionItem, Module.BuildOptions)
StoreTextFile(InfFile, Section)
## Store User Extensions section.
#
# Write [UserExtensions] section to the InfFile based on Module class object.
#
# @param InfFile The output INF file to store the User Extensions section.
# @param Module An input Module class object.
#
def StoreModuleUserExtensionsSection(InfFile, Module):
Section = "".join(map(GetUserExtensions, Module.UserExtensions))
StoreTextFile(InfFile, Section)
## Store a Module class object to a new INF file.
#
# Read an input Module class object and save the contents to a new INF file.
#
# @param INFFileName The output INF file.
# @param Module An input Package class object.
#
def StoreInf(InfFileName, Module):
InfFile = open(InfFileName, "w+")
EdkLogger.info("Save file to %s" % InfFileName)
StoreHeader(InfFile, Module.Header)
StoreModuleDefinesSection(InfFile, Module)
StoreModuleSourcesSection(InfFile, Module)
StoreModuleBinariesSection(InfFile, Module)
StoreModulePackagesSection(InfFile, Module)
StoreModuleLibraryClassesSection(InfFile, Module)
StoreModuleProtocolsSection(InfFile, Module)
StoreModulePpisSection(InfFile, Module)
StoreModuleGuidsSection(InfFile, Module)
StoreModulePcdsSection(InfFile, Module)
StoreModuleDepexSection(InfFile, Module)
StoreModuleBuildOptionsSection(InfFile, Module)
StoreModuleUserExtensionsSection(InfFile, Module)
InfFile.close()
if __name__ == '__main__':
pass

View File

@@ -1,15 +0,0 @@
## @file
# Python 'msa2inf' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# 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.
#

View File

@@ -1,66 +0,0 @@
## @file
# Convert an SPD Package class object ot a DEC Package class object by filling
# some fields required by DEC file.
#
# 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 os
from Common.MigrationUtilities import *
from LoadSpd import LoadSpd
from StoreDec import StoreDec
#The default DEC version number tool generates.
gDecVersion = "0x00010005"
## Add required version information.
#
# Add the default DEC specification version to Package class object.
#
# @param Package An input Package class object.
#
def AddPackageMiscVersion(Package):
PackageHeader = Package.Header
PackageHeader.DecSpecification = gDecVersion
## Add package include information.
#
# Adds the default "Include" folder to if that directory exists.
#
# @param Package An input Package class object.
#
def AddPackageInclude(Package):
PackageDir = os.path.dirname(Package.Header.FullPath)
DefaultIncludeDir = os.path.join(PackageDir, "Include")
if os.path.exists(DefaultIncludeDir):
Include = IncludeClass()
Include.FilePath = "Include"
Package.Includes.insert(0, Include)
## Convert SPD Package class object to DEC Package class object.
#
# Convert SPD Package class ojbect to DEC Package class object by filling in
# several information required by DEC file.
#
# @param Package An input Package class object.
#
def ConvertSpdPackageToDecPackage(Package):
AddPackageMiscVersion(Package)
AddPackageInclude(Package)
# This acts like the main() function for the script, unless it is 'import'ed
# into another script.
if __name__ == '__main__':
pass

View File

@@ -1,273 +0,0 @@
## @file
# Open an SPD file and load all its contents to a PackageClass object.
#
# 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 os
from Common.XmlRoutines import *
from Common.MigrationUtilities import *
from CommonDataClass.PackageClass import *
## Load a list of Package Cloned Records.
#
# Read an input Package XML DOM object and return a list of Cloned Records
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel ClonedRecords A list of Cloned Records loaded from XmlSpd.
#
def LoadPackageClonedRecords(XmlSpd):
XmlTag = "PackageSurfaceArea/PackageDefinitions/ClonedFrom/Cloned"
return map(LoadClonedRecord, XmlList(XmlSpd, XmlTag))
## Load Package Header.
#
# Read an input Package XML DOM object and return Package Header class object
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
# @param SpdFileName The file path of SPD File.
#
# @retvel PackageHeader A new Package Header object loaded from XmlSpd.
#
def LoadPackageHeader(XmlSpd, SpdFileName):
PackageHeader = PackageHeaderClass()
XmlTag = "PackageSurfaceArea/SpdHeader"
SpdHeader = XmlNode(XmlSpd, XmlTag)
SetIdentification(PackageHeader, SpdHeader, "PackageName", SpdFileName)
SetCommonHeader(PackageHeader, SpdHeader)
XmlTag = "PackageSurfaceArea/PackageDefinitions/ReadOnly"
if XmlElement(XmlSpd, XmlTag).lower() == "true":
PackageHeader.ReadOnly = True
XmlTag = "PackageSurfaceArea/PackageDefinitions/RePackage"
if XmlElement(XmlSpd, XmlTag).lower() == "true":
PackageHeader.RePackage = True
PackageHeader.ClonedFrom = LoadPackageClonedRecords(XmlSpd)
return PackageHeader
## Load a list of Package Library Classes.
#
# Read an input Package XML DOM object and return a list of Library Classes
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel LibraryClasses A list of Library Classes loaded from XmlSpd.
#
def LoadPackageLibraryClasses(XmlSpd):
XmlTag = "PackageSurfaceArea/LibraryClassDeclarations/LibraryClass"
return map(LoadLibraryClass, XmlList(XmlSpd, XmlTag))
## Load a new Package Industry Std Header class object.
#
# Read an input XML IndustryStdHeader DOM object and return an object of
# Industry Std Header contained in the DOM object.
#
# @param XmlIndustryStdHeader A child XML DOM object in Package XML DOM.
#
# @retvel PackageIndustryStdHeader A new Industry Std Header object created by XmlIndustryStdHeader.
#
def LoadPackageIndustryStdHeader(XmlIndustryStdHeader):
PackageIndustryStdHeader = PackageIndustryStdHeaderClass()
XmlTag = "Name"
Name = XmlAttribute(XmlIndustryStdHeader, XmlTag)
PackageIndustryStdHeader.Name = Name
XmlTag = "IndustryStdHeader/IncludeHeader"
IncludeHeader = XmlElement(XmlIndustryStdHeader, XmlTag)
PackageIndustryStdHeader.IncludeHeader = IncludeHeader
SetCommon(PackageIndustryStdHeader, XmlIndustryStdHeader)
return PackageIndustryStdHeader
## Load a list of Package Industry Std Headers.
#
# Read an input Package XML DOM object and return a list of Industry Std Headers
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel IndustryStdHeaders A list of Industry Std Headers loaded from XmlSpd.
#
def LoadPackageIndustryStdHeaders(XmlSpd):
XmlTag = "PackageSurfaceArea/IndustryStdIncludes/IndustryStdHeader"
return map(LoadPackageIndustryStdHeader, XmlList(XmlSpd, XmlTag))
## Load a list of Package Module Files.
#
# Read an input Package XML DOM object and return a list of Module Files
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel ModuleFiles A list of Module Files loaded from XmlSpd.
#
def LoadPackageModuleFiles(XmlSpd):
XmlTag = "PackageSurfaceArea/MsaFiles/Filename"
return XmlElementList(XmlSpd, XmlTag)
## Load a new Package Include Pkg Header class object.
#
# Read an input XML IncludePkgHeader DOM object and return an object of Include
# Package Header contained in the DOM object.
#
# @param XmlPackageIncludeHeader A child XML DOM object in Package XML DOM.
#
# @retvel PackageIncludePkgHeader A new Include Pkg Header object created by
# XmlPackageIncludeHeader.
#
def LoadPackageIncludePkgHeader(XmlPackageIncludeHeader):
PackageIncludeHeader = PackageIncludePkgHeaderClass()
IncludeHeader = XmlElementData(XmlPackageIncludeHeader)
PackageIncludeHeader.IncludeHeader = IncludeHeader
XmlTag = "ModuleType"
ModuleTypes = XmlAttribute(XmlPackageIncludeHeader, XmlTag)
PackageIncludeHeader.ModuleType = ModuleTypes.split()
return PackageIncludeHeader
## Load a list of Package Include Pkg Headers.
#
# Read an input Package XML DOM object and return a list of Include Pkg Headers
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel IncludePkgHeaders A list of Include Pkg Headers loaded from XmlSpd.
#
def LoadPackageIncludePkgHeaders(XmlSpd):
XmlTag = "PackageSurfaceArea/PackageHeaders/IncludePkgHeader"
return map(LoadPackageIncludePkgHeader, XmlList(XmlSpd, XmlTag))
## Load a list of Package Guid Declarations.
#
# Read an input Package XML DOM object and return a list of Guid Declarations
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel GuidDeclarations A list of Guid Declarations loaded from XmlSpd.
#
def LoadPackageGuidDeclarations(XmlSpd):
XmlTag = "PackageSurfaceArea/GuidDeclarations/Entry"
return map(LoadGuidProtocolPpiCommon, XmlList(XmlSpd, XmlTag))
## Load a list of Package Protocol Declarations.
#
# Read an input Package XML DOM object and return a list of Protocol Declarations
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel ProtocolDeclarations A list of Protocol Declarations loaded from XmlSpd.
#
def LoadPackageProtocolDeclarations(XmlSpd):
XmlTag = "PackageSurfaceArea/ProtocolDeclarations/Entry"
return map(LoadGuidProtocolPpiCommon, XmlList(XmlSpd, XmlTag))
## Load a list of Package Ppi Declarations.
#
# Read an input Package XML DOM object and return a list of Ppi Declarations
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel PpiDeclarations A list of Ppi Declarations loaded from XmlSpd.
#
def LoadPackagePpiDeclarations(XmlSpd):
XmlTag = "PackageSurfaceArea/PpiDeclarations/Entry"
return map(LoadGuidProtocolPpiCommon, XmlList(XmlSpd, XmlTag))
## Load a list of Package Pcd Declarations.
#
# Read an input Package XML DOM object and return a list of Pcd Declarations
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel PcdDeclarations A list of Pcd Declarations loaded from XmlSpd.
#
def LoadPackagePcdDeclarations(XmlSpd):
XmlTag = "PackageSurfaceArea/PcdDeclarations/PcdEntry"
return map(LoadPcd, XmlList(XmlSpd, XmlTag))
## Load a list of Package User Extensions.
#
# Read an input Package XML DOM object and return a list of User Extensions
# contained in the DOM object.
#
# @param XmlSpd An XML DOM object read from SPD file.
#
# @retvel UserExtensions A list of User Extensions loaded from XmlSpd.
#
def LoadPackageUserExtensions(XmlSpd):
XmlTag = "PackageSurfaceArea/UserExtensions"
return map(LoadUserExtensions, XmlList(XmlSpd, XmlTag))
## Load a new Package class object.
#
# Read an input SPD File and return a new Package class Object.
#
# @param SpdFileName An XML DOM object read from SPD file.
#
# @retvel Package A new Module class object loaded from SPD File.
#
def LoadSpd(SpdFileName):
XmlSpd = XmlParseFile(SpdFileName)
EdkLogger.verbose("Xml Object loaded for file %s" % SpdFileName)
Package = PackageClass()
Package.Header = LoadPackageHeader(XmlSpd, SpdFileName)
Package.LibraryClassDeclarations = LoadPackageLibraryClasses(XmlSpd)
Package.IndustryStdHeaders = LoadPackageIndustryStdHeaders(XmlSpd)
Package.ModuleFiles = LoadPackageModuleFiles(XmlSpd)
Package.PackageIncludePkgHeaders = LoadPackageIncludePkgHeaders(XmlSpd)
Package.GuidDeclarations = LoadPackageGuidDeclarations(XmlSpd)
Package.ProtocolDeclarations = LoadPackageProtocolDeclarations(XmlSpd)
Package.PpiDeclarations = LoadPackagePpiDeclarations(XmlSpd)
Package.PcdDeclarations = LoadPackagePcdDeclarations(XmlSpd)
Package.UserExtensions = LoadPackageUserExtensions(XmlSpd)
return Package
# This acts like the main() function for the script, unless it is 'import'ed
# into another script.
if __name__ == '__main__':
pass

View File

@@ -1,46 +0,0 @@
## @file
# Convert an XML-based SPD file to a text-based DEC file.
#
# 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
from Common.MigrationUtilities import *
from LoadSpd import LoadSpd
from StoreDec import StoreDec
from ConvertPackage import ConvertSpdPackageToDecPackage
## 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:
Options, InputFile = MigrationOptionParser("SPD", "DEC", "%prog")
Package = LoadSpd(InputFile)
ConvertSpdPackageToDecPackage(Package)
StoreDec(Options.OutputFile, Package)
return 0
except Exception, e:
print e
return 1
if __name__ == '__main__':
sys.exit(Main())

View File

@@ -1,247 +0,0 @@
## @file
# Store a Package class object to a DEC file.
#
# 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 os
from Common.MigrationUtilities import *
from LoadSpd import LoadSpd
from CommonDataClass.PackageClass import *
## Store Defines section.
#
# Write [Defines] section to the DecFile based on Package class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DecFile The output DEC file to store the Defines section.
# @param Package An input Package class object.
#
def StorePackageDefinesSection(DecFile, Package):
DefinesTupleList = []
DefinesTupleList.append(("DEC_VERSION", Package.Header.DecSpecification))
DefinesTupleList.append(("PACKAGE_NAME", Package.Header.Name))
DefinesTupleList.append(("PACKAGE_GUID", Package.Header.Guid))
StoreDefinesSection(DecFile, DefinesTupleList)
## Return a Package Include Class Item.
#
# Read the input Include class object and return one Include Class Item.
#
# @param Include An input Include class object.
#
# @retval IncludeClassItem A Package Include Class Item.
#
def GetPackageIncludeClassItem(Include):
return Include.FilePath
## Store Includes section.
#
# Write [Includes] section to the DecFile based on Package class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DecFile The output DEC file to store the Includes section.
# @param Package An input Package class object.
#
def StorePackageIncludesSection(DecFile, Package):
Includes = Package.Includes
Section = GetSection("Includes", GetPackageIncludeClassItem, Includes)
StoreTextFile(DecFile, Section)
## Return a Package Library Class Item.
#
# Read the input LibraryClass class object and return one Library Class Item.
#
# @param LibraryClass An input LibraryClass class object.
#
# @retval LibraryClassItem A Package Library Class Item.
#
def GetPackageLibraryClassItem(LibraryClass):
return "|".join((LibraryClass.LibraryClass, LibraryClass.IncludeHeader))
## Store Library Classes section.
#
# Write [LibraryClasses] section to the DecFile based on Package class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DecFile The output DEC file to store the Library Classes
# section.
# @param Package An input Package class object.
#
def StorePackageLibraryClassesSection(DecFile, Package):
LibraryClasses = Package.LibraryClassDeclarations
Section = GetSection("LibraryClasses", GetPackageLibraryClassItem, LibraryClasses)
StoreTextFile(DecFile, Section)
## Return a Package Guid Declaration Item.
#
# Read the input Guid class object and return one line of Guid Declaration Item.
#
# @param Guid An input Guid class object.
#
# @retval GuidDeclarationItem A Package Guid Declaration Item.
#
def GetPackageGuidDeclarationItem(Guid):
GuidCName = Guid.CName
GuidValue = Guid.Guid.replace("-", "")
GuidValueList = [GuidValue[0:8]]
GuidValueList += [GuidValue[i : i + 4] for i in range(8, 16, 4)]
GuidValueList += [GuidValue[i : i + 2] for i in range(16, 32, 2)]
GuidCFormat = "{0x%s" + ", 0x%s" * 2 + ", {0x%s" + ", 0x%s" * 7 + "}}"
GuidCValue = GuidCFormat % tuple(GuidValueList)
return "%-30s = %s" % (GuidCName, GuidCValue)
## Store Protocols section.
#
# Write [Protocols] section to the DecFile based on Package class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DecFile The output DEC file to store the Protocols section.
# @param Package An input Package class object.
#
def StorePackageProtocolsSection(DecFile, Package):
Protocols = Package.ProtocolDeclarations
Section = GetSection("Protocols", GetPackageGuidDeclarationItem, Protocols)
StoreTextFile(DecFile, Section)
## Store Ppis section.
#
# Write [Ppis] section to the DecFile based on Package class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DecFile The output DEC file to store the Ppis section.
# @param Package An input Package class object.
#
def StorePackagePpisSection(DecFile, Package):
Ppis = Package.PpiDeclarations
Section = GetSection("Ppis", GetPackageGuidDeclarationItem, Ppis)
StoreTextFile(DecFile, Section)
## Store Guids section.
#
# Write [Guids] section to the DecFile based on Package class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DecFile The output DEC file to store the Guids section.
# @param Package An input Package class object.
#
def StorePackageGuidsSection(DecFile, Package):
Guids = Package.GuidDeclarations
Section = GetSection("Guids", GetPackageGuidDeclarationItem, Guids)
StoreTextFile(DecFile, Section)
## Return a Package Pcd Item.
#
# Read the input Pcd class object and return one line of Pcd Item.
#
# @param Pcd An input Pcd class object.
#
# @retval PcdItem A Package Pcd Item.
#
def GetPackagePcdItem(Pcd):
PcdPair = "%s.%s" % (Pcd.TokenSpaceGuidCName, Pcd.CName)
DatumType = Pcd.DatumType
DefaultValue = Pcd.DefaultValue
Token = Pcd.Token
PcdList = [PcdPair, DefaultValue, DatumType, Token]
return "|".join(PcdList)
## DEC Pcd Section Name dictionary indexed by PCD Item Type.
mDecPcdSectionNameDict = {
"FEATURE_FLAG" : "PcdsFeatureFlag",
"FIXED_AT_BUILD" : "PcdsFixedAtBuild",
"PATCHABLE_IN_MODULE" : "PcdsPatchableInModule",
"DYNAMIC" : "PcdsDynamic",
"DYNAMIC_EX" : "PcdsDynamicEx"
}
## Store Pcds section.
#
# Write [Pcds*] section to the DecFile based on Package class object.
# Different CPU architectures are specified in the subsection if possible.
#
# @param DecFile The output DEC file to store the Pcds section.
# @param Package An input Package class object.
#
def StorePackagePcdsSection(DecFile, Package):
PcdsDict = {}
for Pcd in Package.PcdDeclarations:
for PcdItemType in Pcd.ValidUsage:
PcdSectionName = mDecPcdSectionNameDict.get(PcdItemType)
if PcdSectionName:
PcdsDict.setdefault(PcdSectionName, []).append(Pcd)
else:
EdkLogger.info("Unknown Pcd Item Type: %s" % PcdItemType)
Section = ""
for PcdSectionName in PcdsDict:
Pcds = PcdsDict[PcdSectionName]
Section += GetSection(PcdSectionName, GetPackagePcdItem, Pcds)
StoreTextFile(DecFile, Section)
## Store User Extensions section.
#
# Write [UserExtensions] section to the DecFile based on Package class object.
#
# @param DecFile The output DEC file to store the User Extensions section.
# @param Package An input Package class object.
#
def StorePackageUserExtensionsSection(DecFile, Package):
Section = "".join(map(GetUserExtensions, Package.UserExtensions))
StoreTextFile(DecFile, Section)
## Store a Package class object to a new DEC file.
#
# Read an input Package class object and ave the contents to a new DEC file.
#
# @param DecFileName The output DEC file.
# @param Package An input Package class object.
#
def StoreDec(DecFileName, Package):
DecFile = open(DecFileName, "w+")
EdkLogger.info("Save file to %s" % DecFileName)
StoreHeader(DecFile, Package.Header)
StorePackageDefinesSection(DecFile, Package)
StorePackageIncludesSection(DecFile, Package)
StorePackageLibraryClassesSection(DecFile, Package)
StorePackageProtocolsSection(DecFile, Package)
StorePackagePpisSection(DecFile, Package)
StorePackageGuidsSection(DecFile, Package)
StorePackagePcdsSection(DecFile, Package)
StorePackageUserExtensionsSection(DecFile, Package)
DecFile.close()
# This acts like the main() function for the script, unless it is 'import'ed
# into another script.
if __name__ == '__main__':
pass

View File

@@ -1,15 +0,0 @@
## @file
# Python 'spd2dec' package initialization file.
#
# This file is required to make Python interpreter treat the directory
# as containing package.
#
# 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.
#