Add in the 1st version of ECP.

git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@2832 6f19259b-4bc3-4df7-8a09-765794883524
This commit is contained in:
qwang12
2007-06-28 07:00:39 +00:00
parent 30d4a0c7ec
commit 3eb9473ea9
1433 changed files with 266617 additions and 0 deletions

View File

@@ -0,0 +1,97 @@
#/*++
#
# Copyright (c) 2006 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the BootsectImage utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=BootsectImage
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\BootsectImage.c"
TARGET_EXE_INCLUDE = "$(TARGET_SOURCE_DIR)\fat.h" \
"$(TARGET_SOURCE_DIR)\mbr.h" \
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(EDK_TOOLS_OUTPUT)\Common.lib
$(LINK) $(MSVS_LINK_LIBPATHS) $(EDK_TOOLS_OUTPUT)\Common.lib $(L_FLAGS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,881 @@
/*++
Copyright 2006 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
bootsectimage.c
Abstract:
Patch the BPB information in boot sector image file.
Patch the MBR code in MBR image file.
--*/
#include <windows.h>
#include <stdio.h>
#include "fat.h"
#include "mbr.h"
#include "EfiUtilityMsgs.h"
#define DEBUG_WARN 0x1
#define DEBUG_ERROR 0x2
int WriteToFile (
void *BootSector,
char *FileName
)
/*++
Routine Description:
Write 512 bytes boot sector to file.
Arguments:
BootSector - point to a buffer containing 512 bytes boot sector to write
FileName - file to write to
Return:
int - number of bytes wrote,
512 indicates write successful
0 indicates write failure
--*/
{
FILE *FileHandle;
int result;
FileHandle = fopen (FileName, "r+b");
if (FileHandle == NULL) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "Open file: %s", FileName);
return 0;
}
fseek (FileHandle, 0, SEEK_SET);
result = fwrite (BootSector, 1, 512, FileHandle);
if (result != 512) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "Write file: %s", FileName);
result = 0;
}
fclose (FileHandle);
return result;
}
int ReadFromFile (
void *BootSector,
char *FileName
)
/*++
Routine Description:
Read first 512 bytes from file.
Arguments:
BootSector - point to a buffer receiving the first 512 bytes data from file
FileName - file to read from
Return:
int - number of bytes read,
512 indicates read successful
0 indicates read failure
--*/
{
FILE *FileHandle;
int result;
FileHandle = fopen (FileName, "rb");
if (FileHandle == NULL) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "Open file: %s", FileName);
return 0;
}
result = fread (BootSector, 1, 512, FileHandle);
if (result != 512) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "Read file: %s", FileName);
result = 0;
}
fclose (FileHandle);
return result;
}
char *
FatTypeToString (
IN FAT_TYPE FatType
)
/*++
Routine Description:
Convert enum type of FatType to string
--*/
{
switch (FatType) {
case FatTypeFat12:
return "FAT12";
case FatTypeFat16:
return "FAT16";
case FatTypeFat32:
return "FAT32";
default:
break;
}
return "FAT Unknown";
}
FAT_TYPE
GetFatType (
IN FAT_BPB_STRUCT *FatBpb
)
/*++
Routine Description:
Determine the FAT type according to BIOS Paramater Block (BPB) data
Arguments:
FatBpb - BIOS Parameter Block (BPB) data, 512 Bytes
Return:
FatTypeUnknown - Cannot determine the FAT type
FatTypeFat12 - FAT12
FatTypeFat16 - FAT16
FatTypeFat32 - FAT32
--*/
{
FAT_TYPE FatType;
UINTN RootDirSectors;
UINTN FATSz;
UINTN TotSec;
UINTN DataSec;
UINTN CountOfClusters;
CHAR8 FilSysType[9];
FatType = FatTypeUnknown;
//
// Simple check
//
if (FatBpb->Fat12_16.Signature != FAT_BS_SIGNATURE) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT: Signature Invalid - %04x, expected - %04x",
FatBpb->Fat12_16.Signature, FAT_BS_SIGNATURE);
return FatTypeUnknown;
}
//
// Check according to FAT spec
//
if ((FatBpb->Fat12_16.BS_jmpBoot[0] != FAT_BS_JMP1) &&
(FatBpb->Fat12_16.BS_jmpBoot[0] != FAT_BS_JMP2)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT: BS_jmpBoot - %02x, expected - %02x or %02x",
FatBpb->Fat12_16.BS_jmpBoot[0], FAT_BS_JMP1, FAT_BS_JMP2);
return FatTypeUnknown;
}
if ((FatBpb->Fat12_16.BPB_BytsPerSec != 512) &&
(FatBpb->Fat12_16.BPB_BytsPerSec != 1024) &&
(FatBpb->Fat12_16.BPB_BytsPerSec != 2048) &&
(FatBpb->Fat12_16.BPB_BytsPerSec != 4096)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT: BPB_BytsPerSec - %04x, expected - %04x, %04x, %04x, or %04x",
FatBpb->Fat12_16.BPB_BytsPerSec, 512, 1024, 2048, 4096);
return FatTypeUnknown;
}
if (FatBpb->Fat12_16.BPB_BytsPerSec != 512) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT: BPB_BytsPerSec - %04x, expected - %04x",
FatBpb->Fat12_16.BPB_BytsPerSec, 512);
}
if ((FatBpb->Fat12_16.BPB_SecPerClus != 1) &&
(FatBpb->Fat12_16.BPB_SecPerClus != 2) &&
(FatBpb->Fat12_16.BPB_SecPerClus != 4) &&
(FatBpb->Fat12_16.BPB_SecPerClus != 8) &&
(FatBpb->Fat12_16.BPB_SecPerClus != 16) &&
(FatBpb->Fat12_16.BPB_SecPerClus != 32) &&
(FatBpb->Fat12_16.BPB_SecPerClus != 64) &&
(FatBpb->Fat12_16.BPB_SecPerClus != 128)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT: BPB_SecPerClus - %02x, expected - %02x, %02x, %02x, %02x, %02x, %02x, %02x, or %02x",
FatBpb->Fat12_16.BPB_BytsPerSec, 1, 2, 4, 8, 16, 32, 64, 128);
return FatTypeUnknown;
}
if (FatBpb->Fat12_16.BPB_BytsPerSec * FatBpb->Fat12_16.BPB_SecPerClus > 32 * 1024) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT: BPB_BytsPerSec * BPB_SecPerClus - %08x, expected <= %08x",
FatBpb->Fat12_16.BPB_BytsPerSec * FatBpb->Fat12_16.BPB_SecPerClus, 32 * 1024);
return FatTypeUnknown;
}
if (FatBpb->Fat12_16.BPB_RsvdSecCnt == 0) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT: BPB_RsvdSecCnt - %04x, expected - Non-Zero",
FatBpb->Fat12_16.BPB_RsvdSecCnt);
return FatTypeUnknown;
}
if (FatBpb->Fat12_16.BPB_NumFATs != 2) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT: BPB_NumFATs - %02x, expected - %02x",
FatBpb->Fat12_16.BPB_NumFATs, 2);
}
if ((FatBpb->Fat12_16.BPB_Media != 0xF0) &&
(FatBpb->Fat12_16.BPB_Media != 0xF8) &&
(FatBpb->Fat12_16.BPB_Media != 0xF9) &&
(FatBpb->Fat12_16.BPB_Media != 0xFA) &&
(FatBpb->Fat12_16.BPB_Media != 0xFB) &&
(FatBpb->Fat12_16.BPB_Media != 0xFC) &&
(FatBpb->Fat12_16.BPB_Media != 0xFD) &&
(FatBpb->Fat12_16.BPB_Media != 0xFE) &&
(FatBpb->Fat12_16.BPB_Media != 0xFF)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT: BPB_Media - %02x, expected - %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, or %02x",
FatBpb->Fat12_16.BPB_Media, 0xF0, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF);
return FatTypeUnknown;
}
//
// Algo in FAT spec
//
RootDirSectors = ((FatBpb->Fat12_16.BPB_RootEntCnt * sizeof(FAT_DIRECTORY_ENTRY)) +
(FatBpb->Fat12_16.BPB_BytsPerSec - 1)) /
FatBpb->Fat12_16.BPB_BytsPerSec;
if (FatBpb->Fat12_16.BPB_FATSz16 != 0) {
FATSz = FatBpb->Fat12_16.BPB_FATSz16;
} else {
FATSz = FatBpb->Fat32.BPB_FATSz32;
}
if (FATSz == 0) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT: BPB_FATSz16, BPB_FATSz32 - 0, expected - Non-Zero");
return FatTypeUnknown;
}
if (FatBpb->Fat12_16.BPB_TotSec16 != 0) {
TotSec = FatBpb->Fat12_16.BPB_TotSec16;
} else {
TotSec = FatBpb->Fat12_16.BPB_TotSec32;
}
if (TotSec == 0) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT: BPB_TotSec16, BPB_TotSec32 - 0, expected - Non-Zero");
return FatTypeUnknown;
}
DataSec = TotSec - (
FatBpb->Fat12_16.BPB_RsvdSecCnt +
FatBpb->Fat12_16.BPB_NumFATs * FATSz +
RootDirSectors
);
CountOfClusters = DataSec / FatBpb->Fat12_16.BPB_SecPerClus;
if (CountOfClusters < FAT_MAX_FAT12_CLUSTER) {
FatType = FatTypeFat12;
} else if (CountOfClusters < FAT_MAX_FAT16_CLUSTER) {
FatType = FatTypeFat16;
} else {
FatType = FatTypeFat32;
}
//
// Check according to FAT spec
//
if (((FatType == FatTypeFat12) || (FatType == FatTypeFat16)) &&
(FatBpb->Fat12_16.BPB_RsvdSecCnt != 1)) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT12_16: BPB_RsvdSecCnt - %04x, expected - %04x",
FatBpb->Fat12_16.BPB_RsvdSecCnt, 1);
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat12_16.BPB_RsvdSecCnt != 32)) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT32: BPB_RsvdSecCnt - %04x, expected - %04x",
FatBpb->Fat12_16.BPB_RsvdSecCnt, 32);
}
if ((FatType == FatTypeFat16) &&
(FatBpb->Fat12_16.BPB_RootEntCnt != 512)) {
printf ("WARNING: FAT16: BPB_RootEntCnt - %04x, expected - %04x\n",
FatBpb->Fat12_16.BPB_RootEntCnt, 512);
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat12_16.BPB_RootEntCnt != 0)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT32: BPB_RootEntCnt - %04x, expected - %04x",
FatBpb->Fat12_16.BPB_RootEntCnt, 0);
return FatTypeUnknown;
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat12_16.BPB_TotSec16 != 0)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT32: BPB_TotSec16 - %04x, expected - %04x",
FatBpb->Fat12_16.BPB_TotSec16, 0);
return FatTypeUnknown;
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat12_16.BPB_FATSz16 != 0)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT32: BPB_FATSz16 - %04x, expected - %04x",
FatBpb->Fat12_16.BPB_FATSz16, 0);
return FatTypeUnknown;
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat12_16.BPB_TotSec32 == 0)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT32: BPB_TotSec32 - %04x, expected - Non-Zero",
FatBpb->Fat12_16.BPB_TotSec32);
return FatTypeUnknown;
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat32.BPB_FATSz32 == 0)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT32: BPB_FATSz32 - %08x, expected - Non-Zero",
FatBpb->Fat32.BPB_FATSz32);
return FatTypeUnknown;
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat32.BPB_FSVer != 0)) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT32: BPB_FSVer - %08x, expected - %04x",
FatBpb->Fat32.BPB_FSVer, 0);
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat32.BPB_RootClus != 2)) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT32: BPB_RootClus - %08x, expected - %04x",
FatBpb->Fat32.BPB_RootClus, 2);
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat32.BPB_FSInfo != 1)) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT32: BPB_FSInfo - %08x, expected - %04x",
FatBpb->Fat32.BPB_FSInfo, 1);
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat32.BPB_BkBootSec != 6)) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT32: BPB_BkBootSec - %08x, expected - %04x",
FatBpb->Fat32.BPB_BkBootSec, 6);
}
if ((FatType == FatTypeFat32) &&
((*(UINT32 *)FatBpb->Fat32.BPB_Reserved != 0) ||
(*((UINT32 *)FatBpb->Fat32.BPB_Reserved + 1) != 0) ||
(*((UINT32 *)FatBpb->Fat32.BPB_Reserved + 2) != 0))) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT32: BPB_Reserved - %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x, expected - 0",
FatBpb->Fat32.BPB_Reserved[0],
FatBpb->Fat32.BPB_Reserved[1],
FatBpb->Fat32.BPB_Reserved[2],
FatBpb->Fat32.BPB_Reserved[3],
FatBpb->Fat32.BPB_Reserved[4],
FatBpb->Fat32.BPB_Reserved[5],
FatBpb->Fat32.BPB_Reserved[6],
FatBpb->Fat32.BPB_Reserved[7],
FatBpb->Fat32.BPB_Reserved[8],
FatBpb->Fat32.BPB_Reserved[9],
FatBpb->Fat32.BPB_Reserved[10],
FatBpb->Fat32.BPB_Reserved[11]);
return FatTypeUnknown;
}
if (((FatType == FatTypeFat12) || (FatType == FatTypeFat16)) &&
(FatBpb->Fat12_16.BS_Reserved1 != 0)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT12_16: BS_Reserved1 - %02x, expected - 0\n",
FatBpb->Fat12_16.BS_Reserved1);
return FatTypeUnknown;
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat32.BS_Reserved1 != 0)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT32: BS_Reserved1 - %02x, expected - 0\n",
FatBpb->Fat32.BS_Reserved1);
return FatTypeUnknown;
}
if (((FatType == FatTypeFat12) || (FatType == FatTypeFat16)) &&
(FatBpb->Fat12_16.BS_BootSig != FAT_BS_BOOTSIG)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT12_16: BS_BootSig - %02x, expected - %02x\n",
FatBpb->Fat12_16.BS_BootSig, FAT_BS_BOOTSIG);
return FatTypeUnknown;
}
if ((FatType == FatTypeFat32) &&
(FatBpb->Fat32.BS_BootSig != FAT_BS_BOOTSIG)) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT32: BS_BootSig - %02x, expected - %02x\n",
FatBpb->Fat32.BS_BootSig, FAT_BS_BOOTSIG);
return FatTypeUnknown;
}
if ((FatType == FatTypeFat12) || (FatType == FatTypeFat16)) {
memcpy (FilSysType, FatBpb->Fat12_16.BS_FilSysType, 8);
FilSysType[8] = 0;
if ((FatType == FatTypeFat12) &&
(strcmp (FilSysType, FAT12_FILSYSTYPE) != 0) &&
(strcmp (FilSysType, FAT_FILSYSTYPE) != 0)) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT12: BS_FilSysType - %s, expected - %s, or %s\n",
FilSysType, FAT12_FILSYSTYPE, FAT_FILSYSTYPE);
}
if ((FatType == FatTypeFat16) &&
(strcmp (FilSysType, FAT16_FILSYSTYPE) != 0) &&
(strcmp (FilSysType, FAT_FILSYSTYPE) != 0)) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT16: BS_FilSysType - %s, expected - %s, or %s\n",
FilSysType, FAT16_FILSYSTYPE, FAT_FILSYSTYPE);
}
}
if (FatType == FatTypeFat32) {
memcpy (FilSysType, FatBpb->Fat32.BS_FilSysType, 8);
FilSysType[8] = 0;
if (strcmp (FilSysType, FAT32_FILSYSTYPE) != 0) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT32: BS_FilSysType - %s, expected - %s\n",
FilSysType, FAT32_FILSYSTYPE);
}
}
//
// pass all check, get FAT type
//
return FatType;
}
void
ParseBootSector (
char *FileName
)
{
FAT_BPB_STRUCT FatBpb;
FAT_TYPE FatType;
if (ReadFromFile ((void *)&FatBpb, FileName) == 0) {
return ;
}
FatType = GetFatType (&FatBpb);
if (FatType <= FatTypeUnknown || FatType >= FatTypeMax) {
printf ("ERROR: Unknown Fat Type!\n");
return;
}
printf ("\nBoot Sector %s:\n", FatTypeToString (FatType));
printf ("\n");
printf (" Offset Title Data\n");
printf ("==================================================================\n");
printf (" 0 JMP instruction %02x %02x %02x\n",
FatBpb.Fat12_16.BS_jmpBoot[0],
FatBpb.Fat12_16.BS_jmpBoot[1],
FatBpb.Fat12_16.BS_jmpBoot[2]);
printf (" 3 OEM %c%c%c%c%c%c%c%c\n",
FatBpb.Fat12_16.BS_OEMName[0],
FatBpb.Fat12_16.BS_OEMName[1],
FatBpb.Fat12_16.BS_OEMName[2],
FatBpb.Fat12_16.BS_OEMName[3],
FatBpb.Fat12_16.BS_OEMName[4],
FatBpb.Fat12_16.BS_OEMName[5],
FatBpb.Fat12_16.BS_OEMName[6],
FatBpb.Fat12_16.BS_OEMName[7]);
printf ("\n");
printf ("BIOS Parameter Block\n");
printf (" B Bytes per sector %04x\n", FatBpb.Fat12_16.BPB_BytsPerSec);
printf (" D Sectors per cluster %02x\n", FatBpb.Fat12_16.BPB_SecPerClus);
printf (" E Reserved sectors %04x\n", FatBpb.Fat12_16.BPB_RsvdSecCnt);
printf (" 10 Number of FATs %02x\n", FatBpb.Fat12_16.BPB_NumFATs);
printf (" 11 Root entries %04x\n", FatBpb.Fat12_16.BPB_RootEntCnt);
printf (" 13 Sectors (under 32MB) %04x\n", FatBpb.Fat12_16.BPB_TotSec16);
printf (" 15 Media descriptor %02x\n", FatBpb.Fat12_16.BPB_Media);
printf (" 16 Sectors per FAT (small vol.) %04x\n", FatBpb.Fat12_16.BPB_FATSz16);
printf (" 18 Sectors per track %04x\n", FatBpb.Fat12_16.BPB_SecPerTrk);
printf (" 1A Heads %04x\n", FatBpb.Fat12_16.BPB_NumHeads);
printf (" 1C Hidden sectors %08x\n", FatBpb.Fat12_16.BPB_HiddSec);
printf (" 20 Sectors (over 32MB) %08x\n", FatBpb.Fat12_16.BPB_TotSec32);
printf ("\n");
if (FatType != FatTypeFat32) {
printf (" 24 BIOS drive %02x\n", FatBpb.Fat12_16.BS_DrvNum);
printf (" 25 (Unused) %02x\n", FatBpb.Fat12_16.BS_Reserved1);
printf (" 26 Ext. boot signature %02x\n", FatBpb.Fat12_16.BS_BootSig);
printf (" 27 Volume serial number %08x\n", FatBpb.Fat12_16.BS_VolID);
printf (" 2B Volume lable %c%c%c%c%c%c%c%c%c%c%c\n",
FatBpb.Fat12_16.BS_VolLab[0],
FatBpb.Fat12_16.BS_VolLab[1],
FatBpb.Fat12_16.BS_VolLab[2],
FatBpb.Fat12_16.BS_VolLab[3],
FatBpb.Fat12_16.BS_VolLab[4],
FatBpb.Fat12_16.BS_VolLab[5],
FatBpb.Fat12_16.BS_VolLab[6],
FatBpb.Fat12_16.BS_VolLab[7],
FatBpb.Fat12_16.BS_VolLab[8],
FatBpb.Fat12_16.BS_VolLab[9],
FatBpb.Fat12_16.BS_VolLab[10]);
printf (" 36 File system %c%c%c%c%c%c%c%c\n",
FatBpb.Fat12_16.BS_FilSysType[0],
FatBpb.Fat12_16.BS_FilSysType[1],
FatBpb.Fat12_16.BS_FilSysType[2],
FatBpb.Fat12_16.BS_FilSysType[3],
FatBpb.Fat12_16.BS_FilSysType[4],
FatBpb.Fat12_16.BS_FilSysType[5],
FatBpb.Fat12_16.BS_FilSysType[6],
FatBpb.Fat12_16.BS_FilSysType[7]);
printf ("\n");
} else {
printf ("FAT32 Section\n");
printf (" 24 Sectors per FAT (large vol.) %08x\n", FatBpb.Fat32.BPB_FATSz32);
printf (" 28 Flags %04x\n", FatBpb.Fat32.BPB_ExtFlags);
printf (" 2A Version %04x\n", FatBpb.Fat32.BPB_FSVer);
printf (" 2C Root dir 1st cluster %08x\n", FatBpb.Fat32.BPB_RootClus);
printf (" 30 FSInfo sector %04x\n", FatBpb.Fat32.BPB_FSInfo);
printf (" 32 Backup boot sector %04x\n", FatBpb.Fat32.BPB_BkBootSec);
printf (" 34 (Reserved) %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
FatBpb.Fat32.BPB_Reserved[0],
FatBpb.Fat32.BPB_Reserved[1],
FatBpb.Fat32.BPB_Reserved[2],
FatBpb.Fat32.BPB_Reserved[3],
FatBpb.Fat32.BPB_Reserved[4],
FatBpb.Fat32.BPB_Reserved[5],
FatBpb.Fat32.BPB_Reserved[6],
FatBpb.Fat32.BPB_Reserved[7],
FatBpb.Fat32.BPB_Reserved[8],
FatBpb.Fat32.BPB_Reserved[9],
FatBpb.Fat32.BPB_Reserved[10],
FatBpb.Fat32.BPB_Reserved[11]);
printf ("\n");
printf (" 40 BIOS drive %02x\n", FatBpb.Fat32.BS_DrvNum);
printf (" 41 (Unused) %02x\n", FatBpb.Fat32.BS_Reserved1);
printf (" 42 Ext. boot signature %02x\n", FatBpb.Fat32.BS_BootSig);
printf (" 43 Volume serial number %08x\n", FatBpb.Fat32.BS_VolID);
printf (" 47 Volume lable %c%c%c%c%c%c%c%c%c%c%c\n",
FatBpb.Fat32.BS_VolLab[0],
FatBpb.Fat32.BS_VolLab[1],
FatBpb.Fat32.BS_VolLab[2],
FatBpb.Fat32.BS_VolLab[3],
FatBpb.Fat32.BS_VolLab[4],
FatBpb.Fat32.BS_VolLab[5],
FatBpb.Fat32.BS_VolLab[6],
FatBpb.Fat32.BS_VolLab[7],
FatBpb.Fat32.BS_VolLab[8],
FatBpb.Fat32.BS_VolLab[9],
FatBpb.Fat32.BS_VolLab[10]);
printf (" 52 File system %c%c%c%c%c%c%c%c\n",
FatBpb.Fat32.BS_FilSysType[0],
FatBpb.Fat32.BS_FilSysType[1],
FatBpb.Fat32.BS_FilSysType[2],
FatBpb.Fat32.BS_FilSysType[3],
FatBpb.Fat32.BS_FilSysType[4],
FatBpb.Fat32.BS_FilSysType[5],
FatBpb.Fat32.BS_FilSysType[6],
FatBpb.Fat32.BS_FilSysType[7]);
printf ("\n");
}
printf (" 1FE Signature %04x\n", FatBpb.Fat12_16.Signature);
printf ("\n");
return ;
}
void
PatchBootSector (
char *DestFileName,
char *SourceFileName,
BOOL ForcePatch
)
/*++
Routine Description:
Patch destination file according to the information from source file.
Only patch BPB data but leave boot code un-touched.
Arguments:
DestFileName - Destination file to patch
SourceFileName - Source file where patch from
--*/
{
FAT_BPB_STRUCT DestFatBpb;
FAT_BPB_STRUCT SourceFatBpb;
FAT_TYPE DestFatType;
FAT_TYPE SourceFatType;
CHAR8 VolLab[11];
CHAR8 FilSysType[8];
if (ReadFromFile ((void *)&DestFatBpb, DestFileName) == 0) {
return ;
}
if (ReadFromFile ((void *)&SourceFatBpb, SourceFileName) == 0) {
return ;
}
DestFatType = GetFatType (&DestFatBpb);
SourceFatType = GetFatType (&SourceFatBpb);
if (DestFatType != SourceFatType) {
//
// FAT type mismatch
//
if (ForcePatch) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "FAT type mismatch: Dest - %s, Source - %s",
FatTypeToString(DestFatType), FatTypeToString(SourceFatType));
} else {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "FAT type mismatch: Dest - %s, Source - %s",
FatTypeToString(DestFatType), FatTypeToString(SourceFatType));
return ;
}
}
if (SourceFatType <= FatTypeUnknown || SourceFatType >= FatTypeMax) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "Unknown Fat Type!\n");
return;
}
//
// Copy BPB/boot data (excluding BS_jmpBoot, BS_OEMName, BootCode and Signature) from SourceFatBpb to DestFatBpb
//
printf ("Patching %s BPB: ", FatTypeToString (SourceFatType));
if (SourceFatType != FatTypeFat32) {
memcpy (
&DestFatBpb.Fat12_16.BPB_BytsPerSec,
&SourceFatBpb.Fat12_16.BPB_BytsPerSec,
((UINTN)&DestFatBpb.Fat12_16.Reserved - (UINTN)&DestFatBpb.Fat12_16.BPB_BytsPerSec)
);
} else {
memcpy (
&DestFatBpb.Fat32.BPB_BytsPerSec,
&SourceFatBpb.Fat32.BPB_BytsPerSec,
((UINTN)&DestFatBpb.Fat32.Reserved - (UINTN)&DestFatBpb.Fat32.BPB_BytsPerSec)
);
}
//
// Set BS_VolLab and BS_FilSysType of DestFatBpb
//
// BS_VolLab BS_FilSysType
// FAT12: EFI FAT12 FAT12
// FAT16: EFI FAT16 FAT16
// FAT32: EFI FAT32 FAT32
//
if (SourceFatType == FatTypeFat32) {
memcpy (VolLab, "EFI FAT32 ", sizeof(VolLab));
memcpy (FilSysType, FAT32_FILSYSTYPE, sizeof(FilSysType));
} else if (SourceFatType == FatTypeFat16) {
memcpy (VolLab, "EFI FAT16 ", sizeof(VolLab));
memcpy (FilSysType, FAT16_FILSYSTYPE, sizeof(FilSysType));
} else {
memcpy (VolLab, "EFI FAT12 ", sizeof(VolLab));
memcpy (FilSysType, FAT12_FILSYSTYPE, sizeof(FilSysType));
}
if (SourceFatType != FatTypeFat32) {
memcpy (DestFatBpb.Fat12_16.BS_VolLab, VolLab, sizeof(VolLab));
memcpy (DestFatBpb.Fat12_16.BS_FilSysType, FilSysType, sizeof(FilSysType));
} else {
memcpy (DestFatBpb.Fat32.BS_VolLab, VolLab, sizeof(VolLab));
memcpy (DestFatBpb.Fat32.BS_FilSysType, FilSysType, sizeof(FilSysType));
}
//
// Set Signature of DestFatBpb to 55AA
//
DestFatBpb.Fat12_16.Signature = FAT_BS_SIGNATURE;
//
// Write DestFatBpb
//
if (WriteToFile ((void *)&DestFatBpb, DestFileName)) {
printf ("successfully!\n");
} else {
printf ("failed!\n");
}
return ;
}
void
ParseMbr (
char *FileName
)
{
MASTER_BOOT_RECORD Mbr;
if (ReadFromFile ((void *)&Mbr, FileName) == 0) {
return ;
}
printf ("\nMaster Boot Record:\n");
printf ("\n");
printf (" Offset Title Value\n");
printf ("==================================================================\n");
printf (" 0 Master bootstrap loader code (not list)\n");
printf (" 1B8 Windows disk signature %08x\n", Mbr.UniqueMbrSignature);
printf ("\n");
printf ("Partition Table Entry #1\n");
printf (" 1BE 80 = active partition %02x\n", Mbr.PartitionRecord[0].BootIndicator);
printf (" 1BF Start head %02x\n", Mbr.PartitionRecord[0].StartHead);
printf (" 1C0 Start sector %02x\n", Mbr.PartitionRecord[0].StartSector);
printf (" 1C1 Start cylinder %02x\n", Mbr.PartitionRecord[0].StartTrack);
printf (" 1C2 Partition type indicator %02x\n", Mbr.PartitionRecord[0].OSType);
printf (" 1C3 End head %02x\n", Mbr.PartitionRecord[0].EndHead);
printf (" 1C4 End sector %02x\n", Mbr.PartitionRecord[0].EndSector);
printf (" 1C5 End cylinder %02x\n", Mbr.PartitionRecord[0].EndTrack);
printf (" 1C6 Sectors preceding partition %08x\n", Mbr.PartitionRecord[0].StartingLBA);
printf (" 1CA Sectors in partition %08x\n", Mbr.PartitionRecord[0].SizeInLBA);
printf ("\n");
printf ("Partition Table Entry #2\n");
printf (" 1CE 80 = active partition %02x\n", Mbr.PartitionRecord[1].BootIndicator);
printf (" 1CF Start head %02x\n", Mbr.PartitionRecord[1].StartHead);
printf (" 1D0 Start sector %02x\n", Mbr.PartitionRecord[1].StartSector);
printf (" 1D1 Start cylinder %02x\n", Mbr.PartitionRecord[1].StartTrack);
printf (" 1D2 Partition type indicator %02x\n", Mbr.PartitionRecord[1].OSType);
printf (" 1D3 End head %02x\n", Mbr.PartitionRecord[1].EndHead);
printf (" 1D4 End sector %02x\n", Mbr.PartitionRecord[1].EndSector);
printf (" 1D5 End cylinder %02x\n", Mbr.PartitionRecord[1].EndTrack);
printf (" 1D6 Sectors preceding partition %08x\n", Mbr.PartitionRecord[1].StartingLBA);
printf (" 1DA Sectors in partition %08x\n", Mbr.PartitionRecord[1].SizeInLBA);
printf ("\n");
printf ("Partition Table Entry #3\n");
printf (" 1DE 80 = active partition %02x\n", Mbr.PartitionRecord[2].BootIndicator);
printf (" 1DF Start head %02x\n", Mbr.PartitionRecord[2].StartHead);
printf (" 1E0 Start sector %02x\n", Mbr.PartitionRecord[2].StartSector);
printf (" 1E1 Start cylinder %02x\n", Mbr.PartitionRecord[2].StartTrack);
printf (" 1E2 Partition type indicator %02x\n", Mbr.PartitionRecord[2].OSType);
printf (" 1E3 End head %02x\n", Mbr.PartitionRecord[2].EndHead);
printf (" 1E4 End sector %02x\n", Mbr.PartitionRecord[2].EndSector);
printf (" 1E5 End cylinder %02x\n", Mbr.PartitionRecord[2].EndTrack);
printf (" 1E6 Sectors preceding partition %08x\n", Mbr.PartitionRecord[2].StartingLBA);
printf (" 1EA Sectors in partition %08x\n", Mbr.PartitionRecord[2].SizeInLBA);
printf ("\n");
printf ("Partition Table Entry #4\n");
printf (" 1EE 80 = active partition %02x\n", Mbr.PartitionRecord[3].BootIndicator);
printf (" 1EF Start head %02x\n", Mbr.PartitionRecord[3].StartHead);
printf (" 1F0 Start sector %02x\n", Mbr.PartitionRecord[3].StartSector);
printf (" 1F1 Start cylinder %02x\n", Mbr.PartitionRecord[3].StartTrack);
printf (" 1F2 Partition type indicator %02x\n", Mbr.PartitionRecord[3].OSType);
printf (" 1F3 End head %02x\n", Mbr.PartitionRecord[3].EndHead);
printf (" 1F4 End sector %02x\n", Mbr.PartitionRecord[3].EndSector);
printf (" 1F5 End cylinder %02x\n", Mbr.PartitionRecord[3].EndTrack);
printf (" 1F6 Sectors preceding partition %08x\n", Mbr.PartitionRecord[3].StartingLBA);
printf (" 1FA Sectors in partition %08x\n", Mbr.PartitionRecord[3].SizeInLBA);
printf ("\n");
printf (" 1FE Signature %04x\n", Mbr.Signature);
printf ("\n");
return ;
}
void
PatchMbr (
char *DestFileName,
char *SourceFileName
)
{
MASTER_BOOT_RECORD DestMbr;
MASTER_BOOT_RECORD SourceMbr;
if (ReadFromFile ((void *)&DestMbr, DestFileName) == 0) {
return ;
}
if (ReadFromFile ((void *)&SourceMbr, SourceFileName) == 0) {
return ;
}
if (SourceMbr.Signature != MBR_SIGNATURE) {
printf ("ERROR: Invalid MBR!\n");
return;
}
printf ("Patching MBR:\n");
memcpy (
&DestMbr.PartitionRecord[0],
&SourceMbr.PartitionRecord[0],
sizeof(DestMbr.PartitionRecord)
);
DestMbr.Signature = MBR_SIGNATURE;
if (WriteToFile ((void *)&DestMbr, DestFileName)) {
printf ("\tsuccessfully!\n");
}
return ;
}
void
PrintUsage (
void
)
{
printf (
"Usage:\n"
"bootsectimage [-m] [-v] -p SrcImage\n"
"bootsectimage [-m] [-v] [-f] -g SrcImage DstImage\n"
"where\n"
" -p: parse SrcImage\n"
" -g: get info from SrcImage, and patch to DstImage\n"
" -f: force patch even FAT type of SrcImage and DstImage mismatch\n"
" -m: process MBR instead of boot sector\n"
" -v: verbose\n"
);
}
int
main (
int argc,
char *argv[]
)
{
char *SrcImage;
char *DstImage;
BOOL ForcePatch; // -f
BOOL ProcessMbr; // -m
BOOL DoParse; // -p SrcImage or -g SrcImage DstImage
BOOL Verbose; // -v
SrcImage = DstImage = NULL;
ForcePatch = FALSE;
ProcessMbr = FALSE;
DoParse = TRUE;
Verbose = FALSE;
SetUtilityName ("bootsectimage");
argc--; argv++;
if (argc == 0) {
PrintUsage ();
return -1;
}
while (argc != 0) {
if (strcmp (*argv, "-f") == 0) {
ForcePatch = TRUE;
} else if (strcmp (*argv, "-p") == 0) {
DoParse = TRUE;
argc--; argv++;
if (argc < 1) {
PrintUsage ();
return -1;
}
SrcImage = *argv;
} else if (strcmp (*argv, "-g") == 0) {
DoParse = FALSE;
argc--; argv++;
if (argc < 2) {
PrintUsage ();
return -1;
}
SrcImage = *argv;
argc--; argv++;
DstImage = *argv;
} else if (strcmp (*argv, "-m") == 0) {
ProcessMbr = TRUE;
} else if (strcmp (*argv, "-v") == 0) {
Verbose = TRUE;
} else {
PrintUsage ();
return -1;
}
argc--; argv++;
}
if (ForcePatch && DoParse) {
printf ("Cannot apply force(-f) to parse(-p)!\n");
PrintUsage ();
return -1;
}
if (ForcePatch && !DoParse && ProcessMbr) {
printf ("Cannot apply force(-f) to processing MBR (-g -m)!\n");
PrintUsage ();
return -1;
}
if (Verbose) {
SetDebugMsgMask (DEBUG_WARN | DEBUG_ERROR);
} else {
SetDebugMsgMask (0);
}
if (DoParse) {
if (ProcessMbr) {
ParseMbr (SrcImage);
} else {
ParseBootSector (SrcImage);
}
} else {
if (ProcessMbr) {
PatchMbr (DstImage, SrcImage);
} else {
PatchBootSector (DstImage, SrcImage, ForcePatch);
}
}
return 0;
}

View File

@@ -0,0 +1,158 @@
/*++
Copyright 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
fat.h
Abstract:
Revision History
--*/
#ifndef _FAT_BPB_H_
#define _FAT_BPB_H_
#include "Tiano.h"
#pragma pack(1)
typedef struct {
//
// Fat common field
//
UINT8 BS_jmpBoot[3];
CHAR8 BS_OEMName[8];
UINT16 BPB_BytsPerSec;
UINT8 BPB_SecPerClus;
UINT16 BPB_RsvdSecCnt;
UINT8 BPB_NumFATs;
UINT16 BPB_RootEntCnt;
UINT16 BPB_TotSec16;
UINT8 BPB_Media;
UINT16 BPB_FATSz16;
UINT16 BPB_SecPerTrk;
UINT16 BPB_NumHeads;
UINT32 BPB_HiddSec;
UINT32 BPB_TotSec32;
//
// Fat12/16 specific field
//
UINT8 BS_DrvNum;
UINT8 BS_Reserved1;
UINT8 BS_BootSig;
UINT32 BS_VolID;
CHAR8 BS_VolLab[11];
CHAR8 BS_FilSysType[8];
//
// Boot Code and Data
//
UINT8 Reserved[448];
//
// Fat common signature - 0xAA55
//
UINT16 Signature;
} FAT12_16_BPB_STRUCT;
typedef struct {
//
// Fat common field
//
UINT8 BS_jmpBoot[3];
CHAR8 BS_OEMName[8];
UINT16 BPB_BytsPerSec;
UINT8 BPB_SecPerClus;
UINT16 BPB_RsvdSecCnt;
UINT8 BPB_NumFATs;
UINT16 BPB_RootEntCnt;
UINT16 BPB_TotSec16;
UINT8 BPB_Media;
UINT16 BPB_FATSz16;
UINT16 BPB_SecPerTrk;
UINT16 BPB_NumHeads;
UINT32 BPB_HiddSec;
UINT32 BPB_TotSec32;
//
// Fat32 specific field
//
UINT32 BPB_FATSz32;
UINT16 BPB_ExtFlags;
UINT16 BPB_FSVer;
UINT32 BPB_RootClus;
UINT16 BPB_FSInfo;
UINT16 BPB_BkBootSec;
UINT8 BPB_Reserved[12];
UINT8 BS_DrvNum;
UINT8 BS_Reserved1;
UINT8 BS_BootSig;
UINT32 BS_VolID;
CHAR8 BS_VolLab[11];
CHAR8 BS_FilSysType[8];
//
// Boot Code and Data
//
UINT8 Reserved[420];
//
// Fat common signature - 0xAA55
//
UINT16 Signature;
} FAT32_BPB_STRUCT;
typedef union {
FAT12_16_BPB_STRUCT Fat12_16;
FAT32_BPB_STRUCT Fat32;
} FAT_BPB_STRUCT;
typedef enum {
FatTypeUnknown,
FatTypeFat12,
FatTypeFat16,
FatTypeFat32,
FatTypeMax
} FAT_TYPE;
typedef struct {
CHAR8 DIR_Name[11];
UINT8 DIR_Attr;
UINT8 DIR_NTRes;
UINT8 DIR_CrtTimeTenth;
UINT16 DIR_CrtTime;
UINT16 DIR_CrtDate;
UINT16 DIR_LstAccDate;
UINT16 DIR_FstClusHI;
UINT16 DIR_WrtTime;
UINT16 DIR_WrtDate;
UINT16 DIR_FstClusLO;
UINT32 DIR_FileSize;
} FAT_DIRECTORY_ENTRY;
#pragma pack()
#define FAT_MAX_FAT12_CLUSTER 0xFF5
#define FAT_MAX_FAT16_CLUSTER 0xFFF5
#define FAT_BS_SIGNATURE 0xAA55
#define FAT_BS_BOOTSIG 0x29
#define FAT_BS_JMP1 0xEB
#define FAT_BS_JMP2 0xE9
#define FAT_FILSYSTYPE "FAT "
#define FAT12_FILSYSTYPE "FAT12 "
#define FAT16_FILSYSTYPE "FAT16 "
#define FAT32_FILSYSTYPE "FAT32 "
#endif

View File

@@ -0,0 +1,64 @@
/*++
Copyright 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
mbr.h
Abstract:
Revision History
--*/
#ifndef _MBR_H_
#define _MBR_H_
#include "Tiano.h"
#pragma pack(1)
#define MAX_MBR_PARTITIONS 4
//
// MBR Partition Entry
//
typedef struct {
UINT8 BootIndicator;
UINT8 StartHead;
UINT8 StartSector;
UINT8 StartTrack;
UINT8 OSType;
UINT8 EndHead;
UINT8 EndSector;
UINT8 EndTrack;
UINT32 StartingLBA;
UINT32 SizeInLBA;
} MBR_PARTITION_RECORD;
//
// MBR Partition table
//
typedef struct {
UINT8 BootCode[440];
UINT32 UniqueMbrSignature;
UINT16 Unknown;
MBR_PARTITION_RECORD PartitionRecord[MAX_MBR_PARTITIONS];
UINT16 Signature;
} MASTER_BOOT_RECORD;
#pragma pack()
#define MBR_SIGNATURE 0xAA55
#define EXTENDED_DOS_PARTITION 0x05
#define EXTENDED_WINDOWS_PARTITION 0x0F
#endif

View File

@@ -0,0 +1,497 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
CommonLib.c
Abstract:
Common Library Functions
--*/
#include "TianoCommon.h"
#include "PeiHob.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "CommonLib.h"
VOID
PeiZeroMem (
IN VOID *Buffer,
IN UINTN Size
)
/*++
Routine Description:
Set Buffer to zero for Size bytes.
Arguments:
Buffer - Memory to set.
Size - Number of bytes to set
Returns:
None
--*/
{
INT8 *Ptr;
Ptr = Buffer;
while (Size--) {
*(Ptr++) = 0;
}
}
VOID
PeiCopyMem (
IN VOID *Destination,
IN VOID *Source,
IN UINTN Length
)
/*++
Routine Description:
Copy Length bytes from Source to Destination.
Arguments:
Destination - Target of copy
Source - Place to copy from
Length - Number of bytes to copy
Returns:
None
--*/
{
CHAR8 *Destination8;
CHAR8 *Source8;
Destination8 = Destination;
Source8 = Source;
while (Length--) {
*(Destination8++) = *(Source8++);
}
}
VOID
ZeroMem (
IN VOID *Buffer,
IN UINTN Size
)
{
PeiZeroMem (Buffer, Size);
}
VOID
CopyMem (
IN VOID *Destination,
IN VOID *Source,
IN UINTN Length
)
{
PeiCopyMem (Destination, Source, Length);
}
INTN
CompareGuid (
IN EFI_GUID *Guid1,
IN EFI_GUID *Guid2
)
/*++
Routine Description:
Compares to GUIDs
Arguments:
Guid1 - guid to compare
Guid2 - guid to compare
Returns:
= 0 if Guid1 == Guid2
!= 0 if Guid1 != Guid2
--*/
{
INT32 *g1;
INT32 *g2;
INT32 r;
//
// Compare 32 bits at a time
//
g1 = (INT32 *) Guid1;
g2 = (INT32 *) Guid2;
r = g1[0] - g2[0];
r |= g1[1] - g2[1];
r |= g1[2] - g2[2];
r |= g1[3] - g2[3];
return r;
}
EFI_STATUS
GetFileImage (
IN CHAR8 *InputFileName,
OUT CHAR8 **InputFileImage,
OUT UINT32 *BytesRead
)
/*++
Routine Description:
This function opens a file and reads it into a memory buffer. The function
will allocate the memory buffer and returns the size of the buffer.
Arguments:
InputFileName The name of the file to read.
InputFileImage A pointer to the memory buffer.
BytesRead The size of the memory buffer.
Returns:
EFI_SUCCESS The function completed successfully.
EFI_INVALID_PARAMETER One of the input parameters was invalid.
EFI_ABORTED An error occurred.
EFI_OUT_OF_RESOURCES No resource to complete operations.
--*/
{
FILE *InputFile;
UINT32 FileSize;
//
// Verify input parameters.
//
if (InputFileName == NULL || strlen (InputFileName) == 0 || InputFileImage == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Open the file and copy contents into a memory buffer.
//
//
// Open the file
//
InputFile = fopen (InputFileName, "rb");
if (InputFile == NULL) {
printf ("ERROR: Could not open input file \"%s\".\n", InputFileName);
return EFI_ABORTED;
}
//
// Go to the end so that we can determine the file size
//
if (fseek (InputFile, 0, SEEK_END)) {
printf ("ERROR: System error reading input file \"%s\".\n", InputFileName);
fclose (InputFile);
return EFI_ABORTED;
}
//
// Get the file size
//
FileSize = ftell (InputFile);
if (FileSize == -1) {
printf ("ERROR: System error parsing input file \"%s\".\n", InputFileName);
fclose (InputFile);
return EFI_ABORTED;
}
//
// Allocate a buffer
//
*InputFileImage = malloc (FileSize);
if (*InputFileImage == NULL) {
fclose (InputFile);
return EFI_OUT_OF_RESOURCES;
}
//
// Reset to the beginning of the file
//
if (fseek (InputFile, 0, SEEK_SET)) {
printf ("ERROR: System error reading input file \"%s\".\n", InputFileName);
fclose (InputFile);
free (*InputFileImage);
*InputFileImage = NULL;
return EFI_ABORTED;
}
//
// Read all of the file contents.
//
*BytesRead = fread (*InputFileImage, sizeof (UINT8), FileSize, InputFile);
if (*BytesRead != sizeof (UINT8) * FileSize) {
printf ("ERROR: Reading file \"%s\"%i.\n", InputFileName);
fclose (InputFile);
free (*InputFileImage);
*InputFileImage = NULL;
return EFI_ABORTED;
}
//
// Close the file
//
fclose (InputFile);
return EFI_SUCCESS;
}
UINT8
CalculateChecksum8 (
IN UINT8 *Buffer,
IN UINTN Size
)
/*++
Routine Description:
This function calculates the value needed for a valid UINT8 checksum
Arguments:
Buffer Pointer to buffer containing byte data of component.
Size Size of the buffer
Returns:
The 8 bit checksum value needed.
--*/
{
return (UINT8) (0x100 - CalculateSum8 (Buffer, Size));
}
UINT8
CalculateSum8 (
IN UINT8 *Buffer,
IN UINT32 Size
)
/*++
Routine Description::
This function calculates the UINT8 sum for the requested region.
Arguments:
Buffer Pointer to buffer containing byte data of component.
Size Size of the buffer
Returns:
The 8 bit checksum value needed.
--*/
{
UINTN Index;
UINT8 Sum;
Sum = 0;
//
// Perform the byte sum for buffer
//
for (Index = 0; Index < Size; Index++) {
Sum = (UINT8) (Sum + Buffer[Index]);
}
return Sum;
}
UINT16
CalculateChecksum16 (
IN UINT16 *Buffer,
IN UINTN Size
)
/*++
Routine Description::
This function calculates the value needed for a valid UINT16 checksum
Arguments:
Buffer Pointer to buffer containing byte data of component.
Size Size of the buffer
Returns:
The 16 bit checksum value needed.
--*/
{
return (UINT16) (0x10000 - CalculateSum16 (Buffer, Size));
}
UINT16
CalculateSum16 (
IN UINT16 *Buffer,
IN UINTN Size
)
/*++
Routine Description:
This function calculates the UINT16 sum for the requested region.
Arguments:
Buffer Pointer to buffer containing byte data of component.
Size Size of the buffer
Returns:
The 16 bit checksum
--*/
{
UINTN Index;
UINT16 Sum;
Sum = 0;
//
// Perform the word sum for buffer
//
for (Index = 0; Index < Size; Index++) {
Sum = (UINT16) (Sum + Buffer[Index]);
}
return (UINT16) Sum;
}
EFI_STATUS
PrintGuid (
IN EFI_GUID *Guid
)
/*++
Routine Description:
This function prints a GUID to STDOUT.
Arguments:
Guid Pointer to a GUID to print.
Returns:
EFI_SUCCESS The GUID was printed.
EFI_INVALID_PARAMETER The input was NULL.
--*/
{
if (Guid == NULL) {
printf ("ERROR: PrintGuid called with a NULL value.\n");
return EFI_INVALID_PARAMETER;
}
printf (
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
Guid->Data1,
Guid->Data2,
Guid->Data3,
Guid->Data4[0],
Guid->Data4[1],
Guid->Data4[2],
Guid->Data4[3],
Guid->Data4[4],
Guid->Data4[5],
Guid->Data4[6],
Guid->Data4[7]
);
return EFI_SUCCESS;
}
EFI_STATUS
PrintGuidToBuffer (
IN EFI_GUID *Guid,
IN OUT UINT8 *Buffer,
IN UINT32 BufferLen,
IN BOOLEAN Uppercase
)
/*++
Routine Description:
This function prints a GUID to a buffer
Arguments:
Guid - Pointer to a GUID to print.
Buffer - Pointer to a user-provided buffer to print to
BufferLen - Size of the Buffer
Uppercase - If use upper case.
Returns:
EFI_SUCCESS The GUID was printed.
EFI_INVALID_PARAMETER The input was NULL.
EFI_BUFFER_TOO_SMALL The input buffer was not big enough
--*/
{
if (Guid == NULL) {
printf ("ERROR: PrintGuidToBuffer() called with a NULL value\n");
return EFI_INVALID_PARAMETER;
}
if (BufferLen < PRINTED_GUID_BUFFER_SIZE) {
printf ("ERORR: PrintGuidToBuffer() called with invalid buffer size\n");
return EFI_BUFFER_TOO_SMALL;
}
if (Uppercase) {
sprintf (
Buffer,
"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
Guid->Data1,
Guid->Data2,
Guid->Data3,
Guid->Data4[0],
Guid->Data4[1],
Guid->Data4[2],
Guid->Data4[3],
Guid->Data4[4],
Guid->Data4[5],
Guid->Data4[6],
Guid->Data4[7]
);
} else {
sprintf (
Buffer,
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
Guid->Data1,
Guid->Data2,
Guid->Data3,
Guid->Data4[0],
Guid->Data4[1],
Guid->Data4[2],
Guid->Data4[3],
Guid->Data4[4],
Guid->Data4[5],
Guid->Data4[6],
Guid->Data4[7]
);
}
return EFI_SUCCESS;
}

View File

@@ -0,0 +1,120 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
CommonLib.h
Abstract:
Common library assistance routines.
--*/
#ifndef _EFI_COMMON_LIB_H
#define _EFI_COMMON_LIB_H
#include "TianoCommon.h"
#define PRINTED_GUID_BUFFER_SIZE 37 // including null-termination
//
// Function declarations
//
VOID
PeiZeroMem (
IN VOID *Buffer,
IN UINTN Size
)
;
VOID
PeiCopyMem (
IN VOID *Destination,
IN VOID *Source,
IN UINTN Length
)
;
VOID
ZeroMem (
IN VOID *Buffer,
IN UINTN Size
)
;
VOID
CopyMem (
IN VOID *Destination,
IN VOID *Source,
IN UINTN Length
)
;
INTN
CompareGuid (
IN EFI_GUID *Guid1,
IN EFI_GUID *Guid2
)
;
EFI_STATUS
GetFileImage (
IN CHAR8 *InputFileName,
OUT CHAR8 **InputFileImage,
OUT UINT32 *BytesRead
)
;
UINT8
CalculateChecksum8 (
IN UINT8 *Buffer,
IN UINTN Size
)
;
UINT8
CalculateSum8 (
IN UINT8 *Buffer,
IN UINTN Size
)
;
UINT16
CalculateChecksum16 (
IN UINT16 *Buffer,
IN UINTN Size
)
;
UINT16
CalculateSum16 (
IN UINT16 *Buffer,
IN UINTN Size
)
;
EFI_STATUS
PrintGuid (
IN EFI_GUID *Guid
)
;
#define PRINTED_GUID_BUFFER_SIZE 37 // including null-termination
EFI_STATUS
PrintGuidToBuffer (
IN EFI_GUID *Guid,
IN OUT UINT8 *Buffer,
IN UINT32 BufferLen,
IN BOOLEAN Uppercase
)
;
#endif

View File

@@ -0,0 +1,90 @@
/*++
Copyright (c) 2004 - 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
Compress.h
Abstract:
Header file for compression routine.
Providing both EFI and Tiano Compress algorithms.
--*/
#ifndef _COMPRESS_H_
#define _COMPRESS_H_
/*++
Routine Description:
Tiano compression routine.
--*/
EFI_STATUS
TianoCompress (
IN UINT8 *SrcBuffer,
IN UINT32 SrcSize,
IN UINT8 *DstBuffer,
IN OUT UINT32 *DstSize
)
;
/*++
Routine Description:
Efi compression routine.
--*/
EFI_STATUS
EfiCompress (
IN UINT8 *SrcBuffer,
IN UINT32 SrcSize,
IN UINT8 *DstBuffer,
IN OUT UINT32 *DstSize
)
;
/*++
Routine Description:
The compression routine.
Arguments:
SrcBuffer - The buffer storing the source data
SrcSize - The size of source data
DstBuffer - The buffer to store the compressed data
DstSize - On input, the size of DstBuffer; On output,
the size of the actual compressed data.
Returns:
EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. In this case,
DstSize contains the size needed.
EFI_SUCCESS - Compression is successful.
EFI_OUT_OF_RESOURCES - No resource to complete function.
EFI_INVALID_PARAMETER - Parameter supplied is wrong.
--*/
typedef
EFI_STATUS
(*COMPRESS_FUNCTION) (
IN UINT8 *SrcBuffer,
IN UINT32 SrcSize,
IN UINT8 *DstBuffer,
IN OUT UINT32 *DstSize
);
#endif

View File

@@ -0,0 +1,327 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
crc32.c
Abstract:
CalcuateCrc32 routine.
--*/
#include <stdlib.h>
#include "TianoCommon.h"
#include "crc32.h"
UINT32 mCrcTable[256] = {
0x00000000,
0x77073096,
0xEE0E612C,
0x990951BA,
0x076DC419,
0x706AF48F,
0xE963A535,
0x9E6495A3,
0x0EDB8832,
0x79DCB8A4,
0xE0D5E91E,
0x97D2D988,
0x09B64C2B,
0x7EB17CBD,
0xE7B82D07,
0x90BF1D91,
0x1DB71064,
0x6AB020F2,
0xF3B97148,
0x84BE41DE,
0x1ADAD47D,
0x6DDDE4EB,
0xF4D4B551,
0x83D385C7,
0x136C9856,
0x646BA8C0,
0xFD62F97A,
0x8A65C9EC,
0x14015C4F,
0x63066CD9,
0xFA0F3D63,
0x8D080DF5,
0x3B6E20C8,
0x4C69105E,
0xD56041E4,
0xA2677172,
0x3C03E4D1,
0x4B04D447,
0xD20D85FD,
0xA50AB56B,
0x35B5A8FA,
0x42B2986C,
0xDBBBC9D6,
0xACBCF940,
0x32D86CE3,
0x45DF5C75,
0xDCD60DCF,
0xABD13D59,
0x26D930AC,
0x51DE003A,
0xC8D75180,
0xBFD06116,
0x21B4F4B5,
0x56B3C423,
0xCFBA9599,
0xB8BDA50F,
0x2802B89E,
0x5F058808,
0xC60CD9B2,
0xB10BE924,
0x2F6F7C87,
0x58684C11,
0xC1611DAB,
0xB6662D3D,
0x76DC4190,
0x01DB7106,
0x98D220BC,
0xEFD5102A,
0x71B18589,
0x06B6B51F,
0x9FBFE4A5,
0xE8B8D433,
0x7807C9A2,
0x0F00F934,
0x9609A88E,
0xE10E9818,
0x7F6A0DBB,
0x086D3D2D,
0x91646C97,
0xE6635C01,
0x6B6B51F4,
0x1C6C6162,
0x856530D8,
0xF262004E,
0x6C0695ED,
0x1B01A57B,
0x8208F4C1,
0xF50FC457,
0x65B0D9C6,
0x12B7E950,
0x8BBEB8EA,
0xFCB9887C,
0x62DD1DDF,
0x15DA2D49,
0x8CD37CF3,
0xFBD44C65,
0x4DB26158,
0x3AB551CE,
0xA3BC0074,
0xD4BB30E2,
0x4ADFA541,
0x3DD895D7,
0xA4D1C46D,
0xD3D6F4FB,
0x4369E96A,
0x346ED9FC,
0xAD678846,
0xDA60B8D0,
0x44042D73,
0x33031DE5,
0xAA0A4C5F,
0xDD0D7CC9,
0x5005713C,
0x270241AA,
0xBE0B1010,
0xC90C2086,
0x5768B525,
0x206F85B3,
0xB966D409,
0xCE61E49F,
0x5EDEF90E,
0x29D9C998,
0xB0D09822,
0xC7D7A8B4,
0x59B33D17,
0x2EB40D81,
0xB7BD5C3B,
0xC0BA6CAD,
0xEDB88320,
0x9ABFB3B6,
0x03B6E20C,
0x74B1D29A,
0xEAD54739,
0x9DD277AF,
0x04DB2615,
0x73DC1683,
0xE3630B12,
0x94643B84,
0x0D6D6A3E,
0x7A6A5AA8,
0xE40ECF0B,
0x9309FF9D,
0x0A00AE27,
0x7D079EB1,
0xF00F9344,
0x8708A3D2,
0x1E01F268,
0x6906C2FE,
0xF762575D,
0x806567CB,
0x196C3671,
0x6E6B06E7,
0xFED41B76,
0x89D32BE0,
0x10DA7A5A,
0x67DD4ACC,
0xF9B9DF6F,
0x8EBEEFF9,
0x17B7BE43,
0x60B08ED5,
0xD6D6A3E8,
0xA1D1937E,
0x38D8C2C4,
0x4FDFF252,
0xD1BB67F1,
0xA6BC5767,
0x3FB506DD,
0x48B2364B,
0xD80D2BDA,
0xAF0A1B4C,
0x36034AF6,
0x41047A60,
0xDF60EFC3,
0xA867DF55,
0x316E8EEF,
0x4669BE79,
0xCB61B38C,
0xBC66831A,
0x256FD2A0,
0x5268E236,
0xCC0C7795,
0xBB0B4703,
0x220216B9,
0x5505262F,
0xC5BA3BBE,
0xB2BD0B28,
0x2BB45A92,
0x5CB36A04,
0xC2D7FFA7,
0xB5D0CF31,
0x2CD99E8B,
0x5BDEAE1D,
0x9B64C2B0,
0xEC63F226,
0x756AA39C,
0x026D930A,
0x9C0906A9,
0xEB0E363F,
0x72076785,
0x05005713,
0x95BF4A82,
0xE2B87A14,
0x7BB12BAE,
0x0CB61B38,
0x92D28E9B,
0xE5D5BE0D,
0x7CDCEFB7,
0x0BDBDF21,
0x86D3D2D4,
0xF1D4E242,
0x68DDB3F8,
0x1FDA836E,
0x81BE16CD,
0xF6B9265B,
0x6FB077E1,
0x18B74777,
0x88085AE6,
0xFF0F6A70,
0x66063BCA,
0x11010B5C,
0x8F659EFF,
0xF862AE69,
0x616BFFD3,
0x166CCF45,
0xA00AE278,
0xD70DD2EE,
0x4E048354,
0x3903B3C2,
0xA7672661,
0xD06016F7,
0x4969474D,
0x3E6E77DB,
0xAED16A4A,
0xD9D65ADC,
0x40DF0B66,
0x37D83BF0,
0xA9BCAE53,
0xDEBB9EC5,
0x47B2CF7F,
0x30B5FFE9,
0xBDBDF21C,
0xCABAC28A,
0x53B39330,
0x24B4A3A6,
0xBAD03605,
0xCDD70693,
0x54DE5729,
0x23D967BF,
0xB3667A2E,
0xC4614AB8,
0x5D681B02,
0x2A6F2B94,
0xB40BBE37,
0xC30C8EA1,
0x5A05DF1B,
0x2D02EF8D
};
EFI_STATUS
CalculateCrc32 (
IN UINT8 *Data,
IN UINTN DataSize,
IN OUT UINT32 *CrcOut
)
/*++
Routine Description:
The CalculateCrc32 routine.
Arguments:
Data - The buffer contaning the data to be processed
DataSize - The size of data to be processed
CrcOut - A pointer to the caller allocated UINT32 that on
contains the CRC32 checksum of Data
Returns:
EFI_SUCCESS - Calculation is successful.
EFI_INVALID_PARAMETER - Data / CrcOut = NULL, or DataSize = 0
--*/
{
UINT32 Crc;
UINTN Index;
UINT8 *Ptr;
if ((DataSize == 0) || (Data == NULL) || (CrcOut == NULL)) {
return EFI_INVALID_PARAMETER;
}
Crc = 0xffffffff;
for (Index = 0, Ptr = Data; Index < DataSize; Index++, Ptr++) {
Crc = (Crc >> 8) ^ mCrcTable[(UINT8) Crc ^ *Ptr];
}
*CrcOut = Crc ^ 0xffffffff;
return EFI_SUCCESS;
}

View File

@@ -0,0 +1,51 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
crc32.h
Abstract:
Header file for CalcuateCrc32 routine
--*/
#ifndef _CRC32_H
#define _CRC32_H
EFI_STATUS
CalculateCrc32 (
IN UINT8 *Data,
IN UINTN DataSize,
IN OUT UINT32 *CrcOut
)
;
/*++
Routine Description:
The CalculateCrc32 routine.
Arguments:
Data - The buffer contaning the data to be processed
DataSize - The size of data to be processed
CrcOut - A pointer to the caller allocated UINT32 that on
contains the CRC32 checksum of Data
Returns:
EFI_SUCCESS - Calculation is successful.
EFI_INVALID_PARAMETER - Data / CrcOut = NULL, or DataSize = 0
--*/
#endif

View File

@@ -0,0 +1,995 @@
/*++
Copyright (c) 2004 - 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
Decompress.c
Abstract:
Decompressor. Algorithm Ported from OPSD code (Decomp.asm)
--*/
#include "TianoCommon.h"
//
// Decompression algorithm begins here
//
#define BITBUFSIZ 32
#define MAXMATCH 256
#define THRESHOLD 3
#define CODE_BIT 16
#define UINT8_MAX 0xff
#define BAD_TABLE - 1
//
// C: Char&Len Set; P: Position Set; T: exTra Set
//
#define NC (0xff + MAXMATCH + 2 - THRESHOLD)
#define CBIT 9
#define MAXPBIT 5
#define TBIT 5
#define MAXNP ((1U << MAXPBIT) - 1)
#define NT (CODE_BIT + 3)
#if NT > MAXNP
#define NPT NT
#else
#define NPT MAXNP
#endif
typedef struct {
UINT8 *mSrcBase; // Starting address of compressed data
UINT8 *mDstBase; // Starting address of decompressed data
UINT32 mOutBuf;
UINT32 mInBuf;
UINT16 mBitCount;
UINT32 mBitBuf;
UINT32 mSubBitBuf;
UINT16 mBlockSize;
UINT32 mCompSize;
UINT32 mOrigSize;
UINT16 mBadTableFlag;
UINT16 mLeft[2 * NC - 1];
UINT16 mRight[2 * NC - 1];
UINT8 mCLen[NC];
UINT8 mPTLen[NPT];
UINT16 mCTable[4096];
UINT16 mPTTable[256];
//
// The length of the field 'Position Set Code Length Array Size' in Block Header.
// For EFI 1.1 de/compression algorithm, mPBit = 4
// For Tiano de/compression algorithm, mPBit = 5
//
UINT8 mPBit;
} SCRATCH_DATA;
STATIC
VOID
FillBuf (
IN SCRATCH_DATA *Sd,
IN UINT16 NumOfBits
)
/*++
Routine Description:
Shift mBitBuf NumOfBits left. Read in NumOfBits of bits from source.
Arguments:
Sd - The global scratch data
NumOfBits - The number of bits to shift and read.
Returns: (VOID)
--*/
{
Sd->mBitBuf = (UINT32) (Sd->mBitBuf << NumOfBits);
while (NumOfBits > Sd->mBitCount) {
Sd->mBitBuf |= (UINT32) (Sd->mSubBitBuf << (NumOfBits = (UINT16) (NumOfBits - Sd->mBitCount)));
if (Sd->mCompSize > 0) {
//
// Get 1 byte into SubBitBuf
//
Sd->mCompSize--;
Sd->mSubBitBuf = 0;
Sd->mSubBitBuf = Sd->mSrcBase[Sd->mInBuf++];
Sd->mBitCount = 8;
} else {
//
// No more bits from the source, just pad zero bit.
//
Sd->mSubBitBuf = 0;
Sd->mBitCount = 8;
}
}
Sd->mBitCount = (UINT16) (Sd->mBitCount - NumOfBits);
Sd->mBitBuf |= Sd->mSubBitBuf >> Sd->mBitCount;
}
STATIC
UINT32
GetBits (
IN SCRATCH_DATA *Sd,
IN UINT16 NumOfBits
)
/*++
Routine Description:
Get NumOfBits of bits out from mBitBuf. Fill mBitBuf with subsequent
NumOfBits of bits from source. Returns NumOfBits of bits that are
popped out.
Arguments:
Sd - The global scratch data.
NumOfBits - The number of bits to pop and read.
Returns:
The bits that are popped out.
--*/
{
UINT32 OutBits;
OutBits = (UINT32) (Sd->mBitBuf >> (BITBUFSIZ - NumOfBits));
FillBuf (Sd, NumOfBits);
return OutBits;
}
STATIC
UINT16
MakeTable (
IN SCRATCH_DATA *Sd,
IN UINT16 NumOfChar,
IN UINT8 *BitLen,
IN UINT16 TableBits,
OUT UINT16 *Table
)
/*++
Routine Description:
Creates Huffman Code mapping table according to code length array.
Arguments:
Sd - The global scratch data
NumOfChar - Number of symbols in the symbol set
BitLen - Code length array
TableBits - The width of the mapping table
Table - The table
Returns:
0 - OK.
BAD_TABLE - The table is corrupted.
--*/
{
UINT16 Count[17];
UINT16 Weight[17];
UINT16 Start[18];
UINT16 *Pointer;
UINT16 Index3;
UINT16 Index;
UINT16 Len;
UINT16 Char;
UINT16 JuBits;
UINT16 Avail;
UINT16 NextCode;
UINT16 Mask;
for (Index = 1; Index <= 16; Index++) {
Count[Index] = 0;
}
for (Index = 0; Index < NumOfChar; Index++) {
Count[BitLen[Index]]++;
}
Start[1] = 0;
for (Index = 1; Index <= 16; Index++) {
Start[Index + 1] = (UINT16) (Start[Index] + (Count[Index] << (16 - Index)));
}
if (Start[17] != 0) {
/*(1U << 16)*/
return (UINT16) BAD_TABLE;
}
JuBits = (UINT16) (16 - TableBits);
for (Index = 1; Index <= TableBits; Index++) {
Start[Index] >>= JuBits;
Weight[Index] = (UINT16) (1U << (TableBits - Index));
}
while (Index <= 16) {
Weight[Index++] = (UINT16) (1U << (16 - Index));
}
Index = (UINT16) (Start[TableBits + 1] >> JuBits);
if (Index != 0) {
Index3 = (UINT16) (1U << TableBits);
while (Index != Index3) {
Table[Index++] = 0;
}
}
Avail = NumOfChar;
Mask = (UINT16) (1U << (15 - TableBits));
for (Char = 0; Char < NumOfChar; Char++) {
Len = BitLen[Char];
if (Len == 0) {
continue;
}
NextCode = (UINT16) (Start[Len] + Weight[Len]);
if (Len <= TableBits) {
for (Index = Start[Len]; Index < NextCode; Index++) {
Table[Index] = Char;
}
} else {
Index3 = Start[Len];
Pointer = &Table[Index3 >> JuBits];
Index = (UINT16) (Len - TableBits);
while (Index != 0) {
if (*Pointer == 0) {
Sd->mRight[Avail] = Sd->mLeft[Avail] = 0;
*Pointer = Avail++;
}
if (Index3 & Mask) {
Pointer = &Sd->mRight[*Pointer];
} else {
Pointer = &Sd->mLeft[*Pointer];
}
Index3 <<= 1;
Index--;
}
*Pointer = Char;
}
Start[Len] = NextCode;
}
//
// Succeeds
//
return 0;
}
STATIC
UINT32
DecodeP (
IN SCRATCH_DATA *Sd
)
/*++
Routine Description:
Decodes a position value.
Arguments:
Sd - the global scratch data
Returns:
The position value decoded.
--*/
{
UINT16 Val;
UINT32 Mask;
UINT32 Pos;
Val = Sd->mPTTable[Sd->mBitBuf >> (BITBUFSIZ - 8)];
if (Val >= MAXNP) {
Mask = 1U << (BITBUFSIZ - 1 - 8);
do {
if (Sd->mBitBuf & Mask) {
Val = Sd->mRight[Val];
} else {
Val = Sd->mLeft[Val];
}
Mask >>= 1;
} while (Val >= MAXNP);
}
//
// Advance what we have read
//
FillBuf (Sd, Sd->mPTLen[Val]);
Pos = Val;
if (Val > 1) {
Pos = (UINT32) ((1U << (Val - 1)) + GetBits (Sd, (UINT16) (Val - 1)));
}
return Pos;
}
STATIC
UINT16
ReadPTLen (
IN SCRATCH_DATA *Sd,
IN UINT16 nn,
IN UINT16 nbit,
IN UINT16 Special
)
/*++
Routine Description:
Reads code lengths for the Extra Set or the Position Set
Arguments:
Sd - The global scratch data
nn - Number of symbols
nbit - Number of bits needed to represent nn
Special - The special symbol that needs to be taken care of
Returns:
0 - OK.
BAD_TABLE - Table is corrupted.
--*/
{
UINT16 Number;
UINT16 CharC;
UINT16 Index;
UINT32 Mask;
Number = (UINT16) GetBits (Sd, nbit);
if (Number == 0) {
CharC = (UINT16) GetBits (Sd, nbit);
for (Index = 0; Index < 256; Index++) {
Sd->mPTTable[Index] = CharC;
}
for (Index = 0; Index < nn; Index++) {
Sd->mPTLen[Index] = 0;
}
return 0;
}
Index = 0;
while (Index < Number) {
CharC = (UINT16) (Sd->mBitBuf >> (BITBUFSIZ - 3));
if (CharC == 7) {
Mask = 1U << (BITBUFSIZ - 1 - 3);
while (Mask & Sd->mBitBuf) {
Mask >>= 1;
CharC += 1;
}
}
FillBuf (Sd, (UINT16) ((CharC < 7) ? 3 : CharC - 3));
Sd->mPTLen[Index++] = (UINT8) CharC;
if (Index == Special) {
CharC = (UINT16) GetBits (Sd, 2);
while ((INT16) (--CharC) >= 0) {
Sd->mPTLen[Index++] = 0;
}
}
}
while (Index < nn) {
Sd->mPTLen[Index++] = 0;
}
return MakeTable (Sd, nn, Sd->mPTLen, 8, Sd->mPTTable);
}
STATIC
VOID
ReadCLen (
SCRATCH_DATA *Sd
)
/*++
Routine Description:
Reads code lengths for Char&Len Set.
Arguments:
Sd - the global scratch data
Returns: (VOID)
--*/
{
UINT16 Number;
UINT16 CharC;
UINT16 Index;
UINT32 Mask;
Number = (UINT16) GetBits (Sd, CBIT);
if (Number == 0) {
CharC = (UINT16) GetBits (Sd, CBIT);
for (Index = 0; Index < NC; Index++) {
Sd->mCLen[Index] = 0;
}
for (Index = 0; Index < 4096; Index++) {
Sd->mCTable[Index] = CharC;
}
return ;
}
Index = 0;
while (Index < Number) {
CharC = Sd->mPTTable[Sd->mBitBuf >> (BITBUFSIZ - 8)];
if (CharC >= NT) {
Mask = 1U << (BITBUFSIZ - 1 - 8);
do {
if (Mask & Sd->mBitBuf) {
CharC = Sd->mRight[CharC];
} else {
CharC = Sd->mLeft[CharC];
}
Mask >>= 1;
} while (CharC >= NT);
}
//
// Advance what we have read
//
FillBuf (Sd, Sd->mPTLen[CharC]);
if (CharC <= 2) {
if (CharC == 0) {
CharC = 1;
} else if (CharC == 1) {
CharC = (UINT16) (GetBits (Sd, 4) + 3);
} else if (CharC == 2) {
CharC = (UINT16) (GetBits (Sd, CBIT) + 20);
}
while ((INT16) (--CharC) >= 0) {
Sd->mCLen[Index++] = 0;
}
} else {
Sd->mCLen[Index++] = (UINT8) (CharC - 2);
}
}
while (Index < NC) {
Sd->mCLen[Index++] = 0;
}
MakeTable (Sd, NC, Sd->mCLen, 12, Sd->mCTable);
return ;
}
STATIC
UINT16
DecodeC (
SCRATCH_DATA *Sd
)
/*++
Routine Description:
Decode a character/length value.
Arguments:
Sd - The global scratch data.
Returns:
The value decoded.
--*/
{
UINT16 Index2;
UINT32 Mask;
if (Sd->mBlockSize == 0) {
//
// Starting a new block
//
Sd->mBlockSize = (UINT16) GetBits (Sd, 16);
Sd->mBadTableFlag = ReadPTLen (Sd, NT, TBIT, 3);
if (Sd->mBadTableFlag != 0) {
return 0;
}
ReadCLen (Sd);
Sd->mBadTableFlag = ReadPTLen (Sd, MAXNP, Sd->mPBit, (UINT16) (-1));
if (Sd->mBadTableFlag != 0) {
return 0;
}
}
Sd->mBlockSize--;
Index2 = Sd->mCTable[Sd->mBitBuf >> (BITBUFSIZ - 12)];
if (Index2 >= NC) {
Mask = 1U << (BITBUFSIZ - 1 - 12);
do {
if (Sd->mBitBuf & Mask) {
Index2 = Sd->mRight[Index2];
} else {
Index2 = Sd->mLeft[Index2];
}
Mask >>= 1;
} while (Index2 >= NC);
}
//
// Advance what we have read
//
FillBuf (Sd, Sd->mCLen[Index2]);
return Index2;
}
STATIC
VOID
Decode (
SCRATCH_DATA *Sd
)
/*++
Routine Description:
Decode the source data and put the resulting data into the destination buffer.
Arguments:
Sd - The global scratch data
Returns: (VOID)
--*/
{
UINT16 BytesRemain;
UINT32 DataIdx;
UINT16 CharC;
BytesRemain = (UINT16) (-1);
DataIdx = 0;
for (;;) {
CharC = DecodeC (Sd);
if (Sd->mBadTableFlag != 0) {
return ;
}
if (CharC < 256) {
//
// Process an Original character
//
if (Sd->mOutBuf >= Sd->mOrigSize) {
return ;
} else {
Sd->mDstBase[Sd->mOutBuf++] = (UINT8) CharC;
}
} else {
//
// Process a Pointer
//
CharC = (UINT16) (CharC - (UINT8_MAX + 1 - THRESHOLD));
BytesRemain = CharC;
DataIdx = Sd->mOutBuf - DecodeP (Sd) - 1;
BytesRemain--;
while ((INT16) (BytesRemain) >= 0) {
Sd->mDstBase[Sd->mOutBuf++] = Sd->mDstBase[DataIdx++];
if (Sd->mOutBuf >= Sd->mOrigSize) {
return ;
}
BytesRemain--;
}
}
}
return ;
}
EFI_STATUS
GetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
)
/*++
Routine Description:
The internal implementation of *_DECOMPRESS_PROTOCOL.GetInfo().
Arguments:
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
DstSize - The size of destination buffer.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successull retrieved.
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
{
UINT8 *Src;
*ScratchSize = sizeof (SCRATCH_DATA);
Src = Source;
if (SrcSize < 8) {
return EFI_INVALID_PARAMETER;
}
*DstSize = Src[4] + (Src[5] << 8) + (Src[6] << 16) + (Src[7] << 24);
return EFI_SUCCESS;
}
EFI_STATUS
Decompress (
IN VOID *Source,
IN UINT32 SrcSize,
IN OUT VOID *Destination,
IN UINT32 DstSize,
IN OUT VOID *Scratch,
IN UINT32 ScratchSize,
IN UINT8 Version
)
/*++
Routine Description:
The internal implementation of *_DECOMPRESS_PROTOCOL.Decompress().
Arguments:
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
Destination - The destination buffer to store the decompressed data
DstSize - The size of destination buffer.
Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data.
ScratchSize - The size of scratch buffer.
Version - The version of de/compression algorithm.
Version 1 for EFI 1.1 de/compression algorithm.
Version 2 for Tiano de/compression algorithm.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
{
UINT32 Index;
UINT32 CompSize;
UINT32 OrigSize;
EFI_STATUS Status;
SCRATCH_DATA *Sd;
UINT8 *Src;
UINT8 *Dst;
Status = EFI_SUCCESS;
Src = Source;
Dst = Destination;
if (ScratchSize < sizeof (SCRATCH_DATA)) {
return EFI_INVALID_PARAMETER;
}
Sd = (SCRATCH_DATA *) Scratch;
if (SrcSize < 8) {
return EFI_INVALID_PARAMETER;
}
CompSize = Src[0] + (Src[1] << 8) + (Src[2] << 16) + (Src[3] << 24);
OrigSize = Src[4] + (Src[5] << 8) + (Src[6] << 16) + (Src[7] << 24);
//
// If compressed file size is 0, return
//
if (OrigSize == 0) {
return Status;
}
if (SrcSize < CompSize + 8) {
return EFI_INVALID_PARAMETER;
}
if (DstSize != OrigSize) {
return EFI_INVALID_PARAMETER;
}
Src = Src + 8;
for (Index = 0; Index < sizeof (SCRATCH_DATA); Index++) {
((UINT8 *) Sd)[Index] = 0;
}
//
// The length of the field 'Position Set Code Length Array Size' in Block Header.
// For EFI 1.1 de/compression algorithm(Version 1), mPBit = 4
// For Tiano de/compression algorithm(Version 2), mPBit = 5
//
switch (Version) {
case 1:
Sd->mPBit = 4;
break;
case 2:
Sd->mPBit = 5;
break;
default:
//
// Currently, only have 2 versions
//
return EFI_INVALID_PARAMETER;
}
Sd->mSrcBase = Src;
Sd->mDstBase = Dst;
Sd->mCompSize = CompSize;
Sd->mOrigSize = OrigSize;
//
// Fill the first BITBUFSIZ bits
//
FillBuf (Sd, BITBUFSIZ);
//
// Decompress it
//
Decode (Sd);
if (Sd->mBadTableFlag != 0) {
//
// Something wrong with the source
//
Status = EFI_INVALID_PARAMETER;
}
return Status;
}
EFI_STATUS
EFIAPI
EfiGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
)
/*++
Routine Description:
The implementation is same as that of EFI_DECOMPRESS_PROTOCOL.GetInfo().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
DstSize - The size of destination buffer.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successull retrieved.
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
{
return GetInfo (
Source,
SrcSize,
DstSize,
ScratchSize
);
}
EFI_STATUS
EFIAPI
EfiDecompress (
IN VOID *Source,
IN UINT32 SrcSize,
IN OUT VOID *Destination,
IN UINT32 DstSize,
IN OUT VOID *Scratch,
IN UINT32 ScratchSize
)
/*++
Routine Description:
The implementation is same as that of EFI_DECOMPRESS_PROTOCOL.Decompress().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
Destination - The destination buffer to store the decompressed data
DstSize - The size of destination buffer.
Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
{
//
// For EFI 1.1 de/compression algorithm, the version is 1.
//
return Decompress (
Source,
SrcSize,
Destination,
DstSize,
Scratch,
ScratchSize,
1
);
}
EFI_STATUS
EFIAPI
TianoGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
)
/*++
Routine Description:
The implementation is same as that of EFI_TIANO_DECOMPRESS_PROTOCOL.GetInfo().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
DstSize - The size of destination buffer.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successull retrieved.
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
{
return GetInfo (
Source,
SrcSize,
DstSize,
ScratchSize
);
}
EFI_STATUS
EFIAPI
TianoDecompress (
IN VOID *Source,
IN UINT32 SrcSize,
IN OUT VOID *Destination,
IN UINT32 DstSize,
IN OUT VOID *Scratch,
IN UINT32 ScratchSize
)
/*++
Routine Description:
The implementation is same as that of EFI_TIANO_DECOMPRESS_PROTOCOL.Decompress().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
Destination - The destination buffer to store the decompressed data
DstSize - The size of destination buffer.
Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
{
//
// For Tiano de/compression algorithm, the version is 2.
//
return Decompress (
Source,
SrcSize,
Destination,
DstSize,
Scratch,
ScratchSize,
2
);
}

View File

@@ -0,0 +1,174 @@
/*++
Copyright (c) 2004 - 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
Decompress.h
Abstract:
Header file for decompression routine.
Providing both EFI and Tiano decompress algorithms.
--*/
#ifndef _DECOMPRESS_H_
#define _DECOMPRESS_H_
EFI_STATUS
EFIAPI
EfiGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
)
/*++
Routine Description:
The implementation is same as that of EFI_DECOMPRESS_PROTOCOL.GetInfo().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
DstSize - The size of destination buffer.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successull retrieved.
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
;
EFI_STATUS
EFIAPI
EfiDecompress (
IN VOID *Source,
IN UINT32 SrcSize,
IN OUT VOID *Destination,
IN UINT32 DstSize,
IN OUT VOID *Scratch,
IN UINT32 ScratchSize
)
/*++
Routine Description:
The implementation is same as that of EFI_DECOMPRESS_PROTOCOL.Decompress().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
Destination - The destination buffer to store the decompressed data
DstSize - The size of destination buffer.
Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
;
EFI_STATUS
EFIAPI
TianoGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
)
/*++
Routine Description:
The implementation is same as that of EFI_TIANO_DECOMPRESS_PROTOCOL.GetInfo().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
DstSize - The size of destination buffer.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successull retrieved.
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
;
EFI_STATUS
EFIAPI
TianoDecompress (
IN VOID *Source,
IN UINT32 SrcSize,
IN OUT VOID *Destination,
IN UINT32 DstSize,
IN OUT VOID *Scratch,
IN UINT32 ScratchSize
)
/*++
Routine Description:
The implementation is same as that of EFI_TIANO_DECOMPRESS_PROTOCOL.Decompress().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
Destination - The destination buffer to store the decompressed data
DstSize - The size of destination buffer.
Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
;
typedef
EFI_STATUS
(*GETINFO_FUNCTION) (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
);
typedef
EFI_STATUS
(*DECOMPRESS_FUNCTION) (
IN VOID *Source,
IN UINT32 SrcSize,
IN OUT VOID *Destination,
IN UINT32 DstSize,
IN OUT VOID *Scratch,
IN UINT32 ScratchSize
);
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,138 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
EfiCustomizedCompress.h
Abstract:
Header file for Customized compression routine
--*/
#ifndef _EFICUSTOMIZEDCOMPRESS_H
#define _EFICUSTOMIZEDCOMPRESS_H
EFI_STATUS
SetCustomizedCompressionType (
IN CHAR8 *Type
)
;
/*++
Routine Description:
The implementation of Customized SetCompressionType().
Arguments:
Type - The type if compression.
Returns:
EFI_SUCCESS - The type has been set.
EFI_UNSUPPORTED - This type is unsupported.
--*/
EFI_STATUS
CustomizedGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
)
;
/*++
Routine Description:
The implementation of Customized GetInfo().
Arguments:
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
DstSize - The size of destination buffer.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successull retrieved.
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
EFI_STATUS
CustomizedDecompress (
IN VOID *Source,
IN UINT32 SrcSize,
IN OUT VOID *Destination,
IN UINT32 DstSize,
IN OUT VOID *Scratch,
IN UINT32 ScratchSize
)
;
/*++
Routine Description:
The implementation of Customized Decompress().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
Destination - The destination buffer to store the decompressed data
DstSize - The size of destination buffer.
Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
EFI_STATUS
CustomizedCompress (
IN UINT8 *SrcBuffer,
IN UINT32 SrcSize,
IN UINT8 *DstBuffer,
IN OUT UINT32 *DstSize
)
;
/*++
Routine Description:
The Customized compression routine.
Arguments:
SrcBuffer - The buffer storing the source data
SrcSize - The size of source data
DstBuffer - The buffer to store the compressed data
DstSize - On input, the size of DstBuffer; On output,
the size of the actual compressed data.
Returns:
EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. In this case,
DstSize contains the size needed.
EFI_SUCCESS - Compression is successful.
--*/
#endif

View File

@@ -0,0 +1,756 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
EfiUtilityMsgs.c
Abstract:
EFI tools utility functions to display warning, error, and informational
messages.
--*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include "Tiano.h"
#include "EfiUtilityMsgs.h"
#define MAX_LINE_LEN 200
//
// Declare module globals for keeping track of the the utility's
// name and other settings.
//
static STATUS mStatus = STATUS_SUCCESS;
static INT8 mUtilityName[50] = { 0 };
static UINT32 mDebugMsgMask = 0;
static INT8 *mSourceFileName = NULL;
static UINT32 mSourceFileLineNum = 0;
static UINT32 mErrorCount = 0;
static UINT32 mWarningCount = 0;
static UINT32 mMaxErrors = 0;
static UINT32 mMaxWarnings = 0;
static UINT32 mMaxWarningsPlusErrors = 0;
static INT8 mPrintLimitsSet = 0;
static
void
PrintMessage (
INT8 *Type,
INT8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
va_list List
);
static
void
PrintLimitExceeded (
VOID
);
void
Error (
INT8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Prints an error message.
Arguments:
All arguments are optional, though the printed message may be useless if
at least something valid is not specified.
FileName - name of the file or application. If not specified, then the
utilty name (as set by the utility calling SetUtilityName()
earlier) is used. Otherwise "Unknown utility" is used.
LineNumber - the line number of error, typically used by parsers. If the
utility is not a parser, then 0 should be specified. Otherwise
the FileName and LineNumber info can be used to cause
MS Visual Studio to jump to the error.
MessageCode - an application-specific error code that can be referenced in
other documentation.
Text - the text in question, typically used by parsers.
MsgFmt - the format string for the error message. Can contain formatting
controls for use with the varargs.
Returns:
None.
Notes:
We print the following (similar to the Warn() and Debug()
W
Typical error/warning message format:
bin\VfrCompile.cpp(330) : error C2660: 'AddVfrDataStructField' : function does not take 2 parameters
BUGBUG -- these three utility functions are almost identical, and
should be modified to share code.
Visual Studio does not find error messages with:
" error :"
" error 1:"
" error c1:"
" error 1000:"
" error c100:"
It does find:
" error c1000:"
--*/
{
va_list List;
//
// If limits have been set, then check that we have not exceeded them
//
if (mPrintLimitsSet) {
//
// See if we've exceeded our total count
//
if (mMaxWarningsPlusErrors != 0) {
if (mErrorCount + mWarningCount > mMaxWarningsPlusErrors) {
PrintLimitExceeded ();
return ;
}
}
//
// See if we've exceeded our error count
//
if (mMaxErrors != 0) {
if (mErrorCount > mMaxErrors) {
PrintLimitExceeded ();
return ;
}
}
}
mErrorCount++;
va_start (List, MsgFmt);
PrintMessage ("error", FileName, LineNumber, MessageCode, Text, MsgFmt, List);
va_end (List);
//
// Set status accordingly
//
if (mStatus < STATUS_ERROR) {
mStatus = STATUS_ERROR;
}
}
void
ParserError (
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Print a parser error, using the source file name and line number
set by a previous call to SetParserPosition().
Arguments:
MessageCode - application-specific error code
Text - text to print in the error message
MsgFmt - format string to print at the end of the error message
Returns:
NA
--*/
{
va_list List;
//
// If limits have been set, then check them
//
if (mPrintLimitsSet) {
//
// See if we've exceeded our total count
//
if (mMaxWarningsPlusErrors != 0) {
if (mErrorCount + mWarningCount > mMaxWarningsPlusErrors) {
PrintLimitExceeded ();
return ;
}
}
//
// See if we've exceeded our error count
//
if (mMaxErrors != 0) {
if (mErrorCount > mMaxErrors) {
PrintLimitExceeded ();
return ;
}
}
}
mErrorCount++;
va_start (List, MsgFmt);
PrintMessage ("error", mSourceFileName, mSourceFileLineNum, MessageCode, Text, MsgFmt, List);
va_end (List);
//
// Set status accordingly
//
if (mStatus < STATUS_ERROR) {
mStatus = STATUS_ERROR;
}
}
void
ParserWarning (
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Print a parser warning, using the source file name and line number
set by a previous call to SetParserPosition().
Arguments:
ErrorCode - application-specific error code
OffendingText - text to print in the warning message
MsgFmt - format string to print at the end of the warning message
Returns:
NA
--*/
{
va_list List;
//
// If limits have been set, then check them
//
if (mPrintLimitsSet) {
//
// See if we've exceeded our total count
//
if (mMaxWarningsPlusErrors != 0) {
if (mErrorCount + mWarningCount > mMaxWarningsPlusErrors) {
PrintLimitExceeded ();
return ;
}
}
//
// See if we've exceeded our warning count
//
if (mMaxWarnings != 0) {
if (mWarningCount > mMaxWarnings) {
PrintLimitExceeded ();
return ;
}
}
}
mWarningCount++;
va_start (List, MsgFmt);
PrintMessage ("warning", mSourceFileName, mSourceFileLineNum, ErrorCode, OffendingText, MsgFmt, List);
va_end (List);
//
// Set status accordingly
//
if (mStatus < STATUS_WARNING) {
mStatus = STATUS_WARNING;
}
}
void
Warning (
INT8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Print a warning message.
Arguments:
FileName - name of the file where the warning was detected, or the name
of the application that detected the warning
LineNumber - the line number where the warning was detected (parsers).
0 should be specified if the utility is not a parser.
MessageCode - an application-specific warning code that can be referenced in
other documentation.
Text - the text in question (parsers)
MsgFmt - the format string for the warning message. Can contain formatting
controls for use with varargs.
Returns:
None.
--*/
{
va_list List;
//
// If limits have been set, then check them
//
if (mPrintLimitsSet) {
//
// See if we've exceeded our total count
//
if (mMaxWarningsPlusErrors != 0) {
if (mErrorCount + mWarningCount > mMaxWarningsPlusErrors) {
PrintLimitExceeded ();
return ;
}
}
//
// See if we've exceeded our warning count
//
if (mMaxWarnings != 0) {
if (mWarningCount > mMaxWarnings) {
PrintLimitExceeded ();
return ;
}
}
}
mWarningCount++;
va_start (List, MsgFmt);
PrintMessage ("warning", FileName, LineNumber, MessageCode, Text, MsgFmt, List);
va_end (List);
//
// Set status accordingly
//
if (mStatus < STATUS_WARNING) {
mStatus = STATUS_WARNING;
}
}
void
DebugMsg (
INT8 *FileName,
UINT32 LineNumber,
UINT32 MsgMask,
INT8 *Text,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Print a warning message.
Arguments:
FileName - typically the name of the utility printing the debug message, but
can be the name of a file being parsed.
LineNumber - the line number in FileName (parsers)
MsgMask - an application-specific bitmask that, in combination with mDebugMsgMask,
determines if the debug message gets printed.
Text - the text in question (parsers)
MsgFmt - the format string for the debug message. Can contain formatting
controls for use with varargs.
Returns:
None.
--*/
{
va_list List;
//
// If the debug mask is not applicable, then do nothing.
//
if ((MsgMask != 0) && ((mDebugMsgMask & MsgMask) == 0)) {
return ;
}
va_start (List, MsgFmt);
PrintMessage ("debug", FileName, LineNumber, 0, Text, MsgFmt, List);
va_end (List);
}
static
void
PrintMessage (
INT8 *Type,
INT8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
va_list List
)
/*++
Routine Description:
Worker routine for all the utility printing services. Prints the message in
a format that Visual Studio will find when scanning build outputs for
errors or warnings.
Arguments:
Type - "warning" or "error" string to insert into the message to be
printed. The first character of this string (converted to uppercase)
is used to preceed the MessageCode value in the output string.
FileName - name of the file where the warning was detected, or the name
of the application that detected the warning
LineNumber - the line number where the warning was detected (parsers).
0 should be specified if the utility is not a parser.
MessageCode - an application-specific warning code that can be referenced in
other documentation.
Text - part of the message to print
MsgFmt - the format string for the message. Can contain formatting
controls for use with varargs.
List - the variable list.
Returns:
None.
Notes:
If FileName == NULL then this utility will use the string passed into SetUtilityName().
LineNumber is only used if the caller is a parser, in which case FileName refers to the
file being parsed.
Text and MsgFmt are both optional, though it would be of little use calling this function with
them both NULL.
Output will typically be of the form:
<FileName>(<LineNumber>) : <Type> <Type[0]><MessageCode>: <Text> : <MsgFmt>
Parser (LineNumber != 0)
VfrCompile.cpp(330) : error E2660: AddVfrDataStructField : function does not take 2 parameters
Generic utility (LineNumber == 0)
UtilityName : error E1234 : Text string : MsgFmt string and args
--*/
{
INT8 Line[MAX_LINE_LEN];
INT8 Line2[MAX_LINE_LEN];
INT8 *Cptr;
//
// If given a filename, then add it (and the line number) to the string.
// If there's no filename, then use the program name if provided.
//
if (FileName != NULL) {
Cptr = FileName;
} else if (mUtilityName[0] != 0) {
Cptr = mUtilityName;
} else {
Cptr = "Unknown utility";
}
strcpy (Line, Cptr);
if (LineNumber != 0) {
sprintf (Line2, "(%d)", LineNumber);
strcat (Line, Line2);
}
//
// Have to print an error code or Visual Studio won't find the
// message for you. It has to be decimal digits too.
//
sprintf (Line2, " : %s %c%04d", Type, toupper (Type[0]), MessageCode);
strcat (Line, Line2);
fprintf (stdout, "%s", Line);
//
// If offending text was provided, then print it
//
if (Text != NULL) {
fprintf (stdout, ": %s ", Text);
}
//
// Print formatted message if provided
//
if (MsgFmt != NULL) {
vsprintf (Line2, MsgFmt, List);
fprintf (stdout, ": %s", Line2);
}
fprintf (stdout, "\n");
}
void
ParserSetPosition (
INT8 *SourceFileName,
UINT32 LineNum
)
/*++
Routine Description:
Set the position in a file being parsed. This can be used to
print error messages deeper down in a parser.
Arguments:
SourceFileName - name of the source file being parsed
LineNum - line number of the source file being parsed
Returns:
NA
--*/
{
mSourceFileName = SourceFileName;
mSourceFileLineNum = LineNum;
}
void
SetUtilityName (
INT8 *UtilityName
)
/*++
Routine Description:
All printed error/warning/debug messages follow the same format, and
typically will print a filename or utility name followed by the error
text. However if a filename is not passed to the print routines, then
they'll print the utility name if you call this function early in your
app to set the utility name.
Arguments:
UtilityName - name of the utility, which will be printed with all
error/warning/debug messags.
Returns:
NA
--*/
{
//
// Save the name of the utility in our local variable. Make sure its
// length does not exceed our buffer.
//
if (UtilityName != NULL) {
if (strlen (UtilityName) >= sizeof (mUtilityName)) {
Error (UtilityName, 0, 0, "application error", "utility name length exceeds internal buffer size");
strncpy (mUtilityName, UtilityName, sizeof (mUtilityName) - 1);
mUtilityName[sizeof (mUtilityName) - 1] = 0;
return ;
} else {
strcpy (mUtilityName, UtilityName);
}
} else {
Error (NULL, 0, 0, "application error", "SetUtilityName() called with NULL utility name");
}
}
STATUS
GetUtilityStatus (
VOID
)
/*++
Routine Description:
When you call Error() or Warning(), this module keeps track of it and
sets a local mStatus to STATUS_ERROR or STATUS_WARNING. When the utility
exits, it can call this function to get the status and use it as a return
value.
Arguments:
None.
Returns:
Worst-case status reported, as defined by which print function was called.
--*/
{
return mStatus;
}
void
SetDebugMsgMask (
UINT32 DebugMask
)
/*++
Routine Description:
Set the debug printing mask. This is used by the DebugMsg() function
to determine when/if a debug message should be printed.
Arguments:
DebugMask - bitmask, specific to the calling application
Returns:
NA
--*/
{
mDebugMsgMask = DebugMask;
}
void
SetPrintLimits (
UINT32 MaxErrors,
UINT32 MaxWarnings,
UINT32 MaxWarningsPlusErrors
)
/*++
Routine Description:
Set the limits of how many errors, warnings, and errors+warnings
we will print.
Arguments:
MaxErrors - maximum number of error messages to print
MaxWarnings - maximum number of warning messages to print
MaxWarningsPlusErrors
- maximum number of errors+warnings to print
Returns:
NA
--*/
{
mMaxErrors = MaxErrors;
mMaxWarnings = MaxWarnings;
mMaxWarningsPlusErrors = MaxWarningsPlusErrors;
mPrintLimitsSet = 1;
}
static
void
PrintLimitExceeded (
VOID
)
{
static INT8 mPrintLimitExceeded = 0;
//
// If we've already printed the message, do nothing. Otherwise
// temporarily increase our print limits so we can pass one
// more message through.
//
if (mPrintLimitExceeded == 0) {
mPrintLimitExceeded++;
mMaxErrors++;
mMaxWarnings++;
mMaxWarningsPlusErrors++;
Error (NULL, 0, 0, "error/warning print limit exceeded", NULL);
mMaxErrors--;
mMaxWarnings--;
mMaxWarningsPlusErrors--;
}
}
#if 0
void
TestUtilityMessages (
VOID
)
{
char *ArgStr = "ArgString";
int ArgInt;
ArgInt = 0x12345678;
//
// Test without setting utility name
//
fprintf (stdout, "* Testing without setting utility name\n");
fprintf (stdout, "** Test debug message not printed\n");
DebugMsg (NULL, 0, 0x00000001, NULL, NULL);
fprintf (stdout, "** Test warning with two strings and two args\n");
Warning (NULL, 0, 1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
fprintf (stdout, "** Test error with two strings and two args\n");
Warning (NULL, 0, 1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
fprintf (stdout, "** Test parser warning with nothing\n");
ParserWarning (0, NULL, NULL);
fprintf (stdout, "** Test parser error with nothing\n");
ParserError (0, NULL, NULL);
//
// Test with utility name set now
//
fprintf (stdout, "** Testingin with utility name set\n");
SetUtilityName ("MyUtilityName");
//
// Test debug prints
//
SetDebugMsgMask (2);
fprintf (stdout, "** Test debug message with one string\n");
DebugMsg (NULL, 0, 0x00000002, "Text1", NULL);
fprintf (stdout, "** Test debug message with one string\n");
DebugMsg (NULL, 0, 0x00000002, NULL, "Text2");
fprintf (stdout, "** Test debug message with two strings\n");
DebugMsg (NULL, 0, 0x00000002, "Text1", "Text2");
fprintf (stdout, "** Test debug message with two strings and two args\n");
DebugMsg (NULL, 0, 0x00000002, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
//
// Test warning prints
//
fprintf (stdout, "** Test warning with no strings\n");
Warning (NULL, 0, 1234, NULL, NULL);
fprintf (stdout, "** Test warning with one string\n");
Warning (NULL, 0, 1234, "Text1", NULL);
fprintf (stdout, "** Test warning with one string\n");
Warning (NULL, 0, 1234, NULL, "Text2");
fprintf (stdout, "** Test warning with two strings and two args\n");
Warning (NULL, 0, 1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
//
// Test error prints
//
fprintf (stdout, "** Test error with no strings\n");
Error (NULL, 0, 1234, NULL, NULL);
fprintf (stdout, "** Test error with one string\n");
Error (NULL, 0, 1234, "Text1", NULL);
fprintf (stdout, "** Test error with one string\n");
Error (NULL, 0, 1234, NULL, "Text2");
fprintf (stdout, "** Test error with two strings and two args\n");
Error (NULL, 0, 1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
//
// Test parser prints
//
fprintf (stdout, "** Test parser errors\n");
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserError (1234, NULL, NULL);
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserError (1234, "Text1", NULL);
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserError (1234, NULL, "Text2");
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserError (1234, "Text1", "Text2");
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserError (1234, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
fprintf (stdout, "** Test parser warnings\n");
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserWarning (4321, NULL, NULL);
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserWarning (4321, "Text1", NULL);
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserWarning (4321, NULL, "Text2");
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserWarning (4321, "Text1", "Text2");
ParserSetPosition (__FILE__, __LINE__ + 1);
ParserWarning (4321, "Text1", "Text2 %s 0x%X", ArgStr, ArgInt);
}
#endif

View File

@@ -0,0 +1,135 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
EfiUtilityMsgs.h
Abstract:
Defines and prototypes for common EFI utility error and debug messages.
--*/
#ifndef _EFI_UTILITY_MSGS_H_
#define _EFI_UTILITY_MSGS_H_
//
// Status codes returned by EFI utility programs and functions
//
#define STATUS_SUCCESS 0
#define STATUS_WARNING 1
#define STATUS_ERROR 2
#define VOID void
typedef int STATUS;
#ifdef __cplusplus
extern "C" {
#endif
//
// When we call Error() or Warning(), the module keeps track of the worst
// case reported. GetUtilityStatus() will get the worst-case results, which
// can be used as the return value from the app.
//
STATUS
GetUtilityStatus (
void
);
//
// If someone prints an error message and didn't specify a source file name,
// then we print the utility name instead. However they must tell us the
// utility name early on via this function.
//
void
SetUtilityName (
INT8 *ProgramName
)
;
void
Error (
INT8 *FileName,
UINT32 LineNumber,
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
void
Warning (
INT8 *FileName,
UINT32 LineNumber,
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
void
DebugMsg (
INT8 *FileName,
UINT32 LineNumber,
UINT32 MsgLevel,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
void
SetDebugMsgMask (
UINT32 MsgMask
)
;
void
ParserSetPosition (
INT8 *SourceFileName,
UINT32 LineNum
)
;
void
ParserError (
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
void
ParserWarning (
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
void
SetPrintLimits (
UINT32 NumErrors,
UINT32 NumWarnings,
UINT32 NumWarningsPlusErrors
)
;
#ifdef __cplusplus
}
#endif
#endif // #ifndef _EFI_UTILITY_MSGS_H_

View File

@@ -0,0 +1,786 @@
/*++
Copyright (c) 2004 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
FvLib.c
Abstract:
These functions assist in parsing and manipulating a Firmware Volume.
--*/
//
// Include files
//
#include "FvLib.h"
#include "CommonLib.h"
#include "EfiUtilityMsgs.h"
//
// Module global variables
//
EFI_FIRMWARE_VOLUME_HEADER *mFvHeader = NULL;
UINT32 mFvLength = 0;
//
// External function implementations
//
EFI_STATUS
InitializeFvLib (
IN VOID *Fv,
IN UINT32 FvLength
)
/*++
Routine Description:
This initializes the FV lib with a pointer to the FV and length. It does not
verify the FV in any way.
Arguments:
Fv Buffer containing the FV.
FvLength Length of the FV
Returns:
EFI_SUCCESS Function Completed successfully.
EFI_INVALID_PARAMETER A required parameter was NULL.
--*/
{
//
// Verify input arguments
//
if (Fv == NULL) {
return EFI_INVALID_PARAMETER;
}
mFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) Fv;
mFvLength = FvLength;
return EFI_SUCCESS;
}
EFI_STATUS
GetFvHeader (
OUT EFI_FIRMWARE_VOLUME_HEADER **FvHeader,
OUT UINT32 *FvLength
)
/*++
Routine Description:
This function returns a pointer to the current FV and the size.
Arguments:
FvHeader Pointer to the FV buffer.
FvLength Length of the FV
Returns:
EFI_SUCCESS Function Completed successfully.
EFI_INVALID_PARAMETER A required parameter was NULL.
EFI_ABORTED The library needs to be initialized.
--*/
{
//
// Verify library has been initialized.
//
if (mFvHeader == NULL || mFvLength == 0) {
return EFI_ABORTED;
}
//
// Verify input arguments
//
if (FvHeader == NULL) {
return EFI_INVALID_PARAMETER;
}
*FvHeader = mFvHeader;
return EFI_SUCCESS;
}
EFI_STATUS
GetNextFile (
IN EFI_FFS_FILE_HEADER *CurrentFile,
OUT EFI_FFS_FILE_HEADER **NextFile
)
/*++
Routine Description:
This function returns the next file. If the current file is NULL, it returns
the first file in the FV. If the function returns EFI_SUCCESS and the file
pointer is NULL, then there are no more files in the FV.
Arguments:
CurrentFile Pointer to the current file, must be within the current FV.
NextFile Pointer to the next file in the FV.
Returns:
EFI_SUCCESS Function completed successfully.
EFI_INVALID_PARAMETER A required parameter was NULL or is out of range.
EFI_ABORTED The library needs to be initialized.
--*/
{
EFI_STATUS Status;
//
// Verify library has been initialized.
//
if (mFvHeader == NULL || mFvLength == 0) {
return EFI_ABORTED;
}
//
// Verify input arguments
//
if (NextFile == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Verify FV header
//
Status = VerifyFv (mFvHeader);
if (EFI_ERROR (Status)) {
return EFI_ABORTED;
}
//
// Get first file
//
if (CurrentFile == NULL) {
CurrentFile = (EFI_FFS_FILE_HEADER *) ((UINTN) mFvHeader + mFvHeader->HeaderLength);
//
// Verify file is valid
//
Status = VerifyFfsFile (CurrentFile);
if (EFI_ERROR (Status)) {
//
// no files in this FV
//
*NextFile = NULL;
return EFI_SUCCESS;
} else {
//
// Verify file is in this FV.
//
if ((UINTN) CurrentFile + GetLength (CurrentFile->Size) > (UINTN) mFvHeader + mFvLength) {
*NextFile = NULL;
return EFI_SUCCESS;
}
*NextFile = CurrentFile;
return EFI_SUCCESS;
}
}
//
// Verify current file is in range
//
if (((UINTN) CurrentFile < (UINTN) mFvHeader + mFvHeader->HeaderLength) ||
((UINTN) CurrentFile + GetLength (CurrentFile->Size) > (UINTN) mFvHeader + mFvLength)
) {
return EFI_INVALID_PARAMETER;
}
//
// Get next file, compensate for 8 byte alignment if necessary.
//
*NextFile = (EFI_FFS_FILE_HEADER *) (((UINTN) CurrentFile + GetLength (CurrentFile->Size) + 0x07) & (-1 << 3));
//
// Verify file is in this FV.
//
if (((UINTN) *NextFile + sizeof (EFI_FFS_FILE_HEADER) >= (UINTN) mFvHeader + mFvLength) ||
((UINTN) *NextFile + GetLength ((*NextFile)->Size) > (UINTN) mFvHeader + mFvLength)
) {
*NextFile = NULL;
return EFI_SUCCESS;
}
//
// Verify file is valid
//
Status = VerifyFfsFile (*NextFile);
if (EFI_ERROR (Status)) {
//
// no more files in this FV
//
*NextFile = NULL;
return EFI_SUCCESS;
}
return EFI_SUCCESS;
}
EFI_STATUS
GetFileByName (
IN EFI_GUID *FileName,
OUT EFI_FFS_FILE_HEADER **File
)
/*++
Routine Description:
Find a file by name. The function will return NULL if the file is not found.
Arguments:
FileName The GUID file name of the file to search for.
File Return pointer. In the case of an error, contents are undefined.
Returns:
EFI_SUCCESS The function completed successfully.
EFI_ABORTED An error was encountered.
EFI_INVALID_PARAMETER One of the parameters was NULL.
--*/
{
EFI_FFS_FILE_HEADER *CurrentFile;
EFI_STATUS Status;
//
// Verify library has been initialized.
//
if (mFvHeader == NULL || mFvLength == 0) {
return EFI_ABORTED;
}
//
// Verify input parameters
//
if (FileName == NULL || File == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Verify FV header
//
Status = VerifyFv (mFvHeader);
if (EFI_ERROR (Status)) {
return EFI_ABORTED;
}
//
// Get the first file
//
Status = GetNextFile (NULL, &CurrentFile);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 0, "error parsing the FV", NULL);
return EFI_ABORTED;
}
//
// Loop as long as we have a valid file
//
while (CurrentFile) {
if (!CompareGuid (&CurrentFile->Name, FileName)) {
*File = CurrentFile;
return EFI_SUCCESS;
}
Status = GetNextFile (CurrentFile, &CurrentFile);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 0, "error parsing the FV", NULL);
return EFI_ABORTED;
}
}
//
// File not found in this FV.
//
*File = NULL;
return EFI_SUCCESS;
}
EFI_STATUS
GetFileByType (
IN EFI_FV_FILETYPE FileType,
IN UINTN Instance,
OUT EFI_FFS_FILE_HEADER **File
)
/*++
Routine Description:
Find a file by type and instance. An instance of 1 is the first instance.
The function will return NULL if a matching file cannot be found.
File type EFI_FV_FILETYPE_ALL means any file type is valid.
Arguments:
FileType Type of file to search for.
Instance Instace of the file type to return.
File Return pointer. In the case of an error, contents are undefined.
Returns:
EFI_SUCCESS The function completed successfully.
EFI_ABORTED An error was encountered.
EFI_INVALID_PARAMETER One of the parameters was NULL.
--*/
{
EFI_FFS_FILE_HEADER *CurrentFile;
EFI_STATUS Status;
UINTN FileCount;
//
// Verify library has been initialized.
//
if (mFvHeader == NULL || mFvLength == 0) {
return EFI_ABORTED;
}
//
// Verify input parameters
//
if (File == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Verify FV header
//
Status = VerifyFv (mFvHeader);
if (EFI_ERROR (Status)) {
return EFI_ABORTED;
}
//
// Initialize the number of matching files found.
//
FileCount = 0;
//
// Get the first file
//
Status = GetNextFile (NULL, &CurrentFile);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 0, "error parsing FV", NULL);
return EFI_ABORTED;
}
//
// Loop as long as we have a valid file
//
while (CurrentFile) {
if (FileType == EFI_FV_FILETYPE_ALL || CurrentFile->Type == FileType) {
FileCount++;
}
if (FileCount == Instance) {
*File = CurrentFile;
return EFI_SUCCESS;
}
Status = GetNextFile (CurrentFile, &CurrentFile);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 0, "error parsing the FV", NULL);
return EFI_ABORTED;
}
}
*File = NULL;
return EFI_SUCCESS;
}
EFI_STATUS
GetSectionByType (
IN EFI_FFS_FILE_HEADER *File,
IN EFI_SECTION_TYPE SectionType,
IN UINTN Instance,
OUT EFI_FILE_SECTION_POINTER *Section
)
/*++
Routine Description:
Find a section in a file by type and instance. An instance of 1 is the first
instance. The function will return NULL if a matching section cannot be found.
The function will not handle encapsulating sections.
Arguments:
File The file to search.
SectionType Type of file to search for.
Instance Instace of the section to return.
Section Return pointer. In the case of an error, contents are undefined.
Returns:
EFI_SUCCESS The function completed successfully.
EFI_ABORTED An error was encountered.
EFI_INVALID_PARAMETER One of the parameters was NULL.
EFI_NOT_FOUND No found.
--*/
{
EFI_FILE_SECTION_POINTER CurrentSection;
EFI_STATUS Status;
UINTN SectionCount;
//
// Verify input parameters
//
if (File == NULL || Instance == 0) {
return EFI_INVALID_PARAMETER;
}
//
// Verify FFS header
//
Status = VerifyFfsFile (File);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 0, "invalid FFS file", NULL);
return EFI_ABORTED;
}
//
// Initialize the number of matching sections found.
//
SectionCount = 0;
//
// Get the first section
//
CurrentSection.CommonHeader = (EFI_COMMON_SECTION_HEADER *) ((UINTN) File + sizeof (EFI_FFS_FILE_HEADER));
//
// Loop as long as we have a valid file
//
while ((UINTN) CurrentSection.CommonHeader < (UINTN) File + GetLength (File->Size)) {
if (CurrentSection.CommonHeader->Type == SectionType) {
SectionCount++;
}
if (SectionCount == Instance) {
*Section = CurrentSection;
return EFI_SUCCESS;
}
//
// Find next section (including compensating for alignment issues.
//
CurrentSection.CommonHeader = (EFI_COMMON_SECTION_HEADER *) ((((UINTN) CurrentSection.CommonHeader) + GetLength (CurrentSection.CommonHeader->Size) + 0x03) & (-1 << 2));
}
//
// Section not found
//
(*Section).Code16Section = NULL;
return EFI_NOT_FOUND;
}
//
// will not parse compressed sections
//
EFI_STATUS
VerifyFv (
IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader
)
/*++
Routine Description:
Verify the current pointer points to a valid FV header.
Arguments:
FvHeader Pointer to an alleged FV file.
Returns:
EFI_SUCCESS The FV header is valid.
EFI_VOLUME_CORRUPTED The FV header is not valid.
EFI_INVALID_PARAMETER A required parameter was NULL.
EFI_ABORTED Operation aborted.
--*/
{
UINT16 Checksum;
//
// Verify input parameters
//
if (FvHeader == NULL) {
return EFI_INVALID_PARAMETER;
}
if (FvHeader->Signature != EFI_FVH_SIGNATURE) {
Error (NULL, 0, 0, "invalid FV header signature", NULL);
return EFI_VOLUME_CORRUPTED;
}
//
// Verify header checksum
//
Checksum = CalculateSum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength / sizeof (UINT16));
if (Checksum != 0) {
Error (NULL, 0, 0, "invalid FV header checksum", NULL);
return EFI_ABORTED;
}
return EFI_SUCCESS;
}
EFI_STATUS
VerifyFfsFile (
IN EFI_FFS_FILE_HEADER *FfsHeader
)
/*++
Routine Description:
Verify the current pointer points to a FFS file header.
Arguments:
FfsHeader Pointer to an alleged FFS file.
Returns:
EFI_SUCCESS The Ffs header is valid.
EFI_NOT_FOUND This "file" is the beginning of free space.
EFI_VOLUME_CORRUPTED The Ffs header is not valid.
EFI_ABORTED The erase polarity is not known.
--*/
{
BOOLEAN ErasePolarity;
EFI_STATUS Status;
EFI_FFS_FILE_HEADER BlankHeader;
UINT8 Checksum;
UINT32 FileLength;
UINT32 OccupiedFileLength;
UINT8 SavedChecksum;
UINT8 SavedState;
UINT8 FileGuidString[80];
UINT32 TailSize;
#if (PI_SPECIFICATION_VERSION < 0x00010000)
EFI_FFS_FILE_TAIL *Tail;
#endif
//
// Verify library has been initialized.
//
if (mFvHeader == NULL || mFvLength == 0) {
return EFI_ABORTED;
}
//
// Verify FV header
//
Status = VerifyFv (mFvHeader);
if (EFI_ERROR (Status)) {
return EFI_ABORTED;
}
//
// Get the erase polarity.
//
Status = GetErasePolarity (&ErasePolarity);
if (EFI_ERROR (Status)) {
return EFI_ABORTED;
}
//
// Check if we have free space
//
if (ErasePolarity) {
memset (&BlankHeader, -1, sizeof (EFI_FFS_FILE_HEADER));
} else {
memset (&BlankHeader, 0, sizeof (EFI_FFS_FILE_HEADER));
}
if (memcmp (&BlankHeader, FfsHeader, sizeof (EFI_FFS_FILE_HEADER)) == 0) {
return EFI_NOT_FOUND;
}
//
// Convert the GUID to a string so we can at least report which file
// if we find an error.
//
PrintGuidToBuffer (&FfsHeader->Name, FileGuidString, sizeof (FileGuidString), TRUE);
if (FfsHeader->Attributes & FFS_ATTRIB_TAIL_PRESENT) {
TailSize = sizeof (EFI_FFS_FILE_TAIL);
} else {
TailSize = 0;
}
//
// Verify file header checksum
//
SavedState = FfsHeader->State;
FfsHeader->State = 0;
SavedChecksum = FfsHeader->IntegrityCheck.Checksum.File;
FfsHeader->IntegrityCheck.Checksum.File = 0;
Checksum = CalculateSum8 ((UINT8 *) FfsHeader, sizeof (EFI_FFS_FILE_HEADER));
FfsHeader->State = SavedState;
FfsHeader->IntegrityCheck.Checksum.File = SavedChecksum;
if (Checksum != 0) {
Error (NULL, 0, 0, FileGuidString, "invalid FFS file header checksum");
return EFI_ABORTED;
}
//
// Verify file checksum
//
if (FfsHeader->Attributes & FFS_ATTRIB_CHECKSUM) {
//
// Verify file data checksum
//
FileLength = GetLength (FfsHeader->Size);
OccupiedFileLength = (FileLength + 0x07) & (-1 << 3);
Checksum = CalculateSum8 ((UINT8 *) FfsHeader, FileLength - TailSize);
Checksum = (UINT8) (Checksum - FfsHeader->State);
if (Checksum != 0) {
Error (NULL, 0, 0, FileGuidString, "invalid FFS file checksum");
return EFI_ABORTED;
}
} else {
//
// File does not have a checksum
// Verify contents are 0x5A as spec'd
//
if (FfsHeader->IntegrityCheck.Checksum.File != FFS_FIXED_CHECKSUM) {
Error (NULL, 0, 0, FileGuidString, "invalid fixed FFS file header checksum");
return EFI_ABORTED;
}
}
#if (PI_SPECIFICATION_VERSION < 0x00010000)
//
// Check if the tail is present and verify it if it is.
//
if (FfsHeader->Attributes & FFS_ATTRIB_TAIL_PRESENT) {
//
// Verify tail is complement of integrity check field in the header.
//
Tail = (EFI_FFS_FILE_TAIL *) ((UINTN) FfsHeader + GetLength (FfsHeader->Size) - sizeof (EFI_FFS_FILE_TAIL));
if (FfsHeader->IntegrityCheck.TailReference != (EFI_FFS_FILE_TAIL)~(*Tail)) {
Error (NULL, 0, 0, FileGuidString, "invalid FFS file tail");
return EFI_ABORTED;
}
}
#endif
return EFI_SUCCESS;
}
UINT32
GetLength (
UINT8 *ThreeByteLength
)
/*++
Routine Description:
Converts a three byte length value into a UINT32.
Arguments:
ThreeByteLength Pointer to the first of the 3 byte length.
Returns:
UINT32 Size of the section
--*/
{
UINT32 Length;
if (ThreeByteLength == NULL) {
return 0;
}
Length = *((UINT32 *) ThreeByteLength);
Length = Length & 0x00FFFFFF;
return Length;
}
EFI_STATUS
GetErasePolarity (
OUT BOOLEAN *ErasePolarity
)
/*++
Routine Description:
This function returns with the FV erase polarity. If the erase polarity
for a bit is 1, the function return TRUE.
Arguments:
ErasePolarity A pointer to the erase polarity.
Returns:
EFI_SUCCESS The function completed successfully.
EFI_INVALID_PARAMETER One of the input parameters was invalid.
EFI_ABORTED Operation aborted.
--*/
{
EFI_STATUS Status;
//
// Verify library has been initialized.
//
if (mFvHeader == NULL || mFvLength == 0) {
return EFI_ABORTED;
}
//
// Verify FV header
//
Status = VerifyFv (mFvHeader);
if (EFI_ERROR (Status)) {
return EFI_ABORTED;
}
//
// Verify input parameters.
//
if (ErasePolarity == NULL) {
return EFI_INVALID_PARAMETER;
}
if (mFvHeader->Attributes & EFI_FVB_ERASE_POLARITY) {
*ErasePolarity = TRUE;
} else {
*ErasePolarity = FALSE;
}
return EFI_SUCCESS;
}
UINT8
GetFileState (
IN BOOLEAN ErasePolarity,
IN EFI_FFS_FILE_HEADER *FfsHeader
)
/*++
Routine Description:
This function returns a the highest state bit in the FFS that is set.
It in no way validate the FFS file.
Arguments:
ErasePolarity The erase polarity for the file state bits.
FfsHeader Pointer to a FFS file.
Returns:
UINT8 The hightest set state of the file.
--*/
{
UINT8 FileState;
UINT8 HighestBit;
FileState = FfsHeader->State;
if (ErasePolarity) {
FileState = (UINT8)~FileState;
}
HighestBit = 0x80;
while (HighestBit != 0 && (HighestBit & FileState) == 0) {
HighestBit >>= 1;
}
return HighestBit;
}

View File

@@ -0,0 +1,177 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
FvLib.h
Abstract:
These functions assist in parsing and manipulating a Firmware Volume.
--*/
#ifndef _EFI_FV_LIB_H
#define _EFI_FV_LIB_H
//
// Include files
//
#include "TianoCommon.h"
#include "EfiFirmwareVolumeHeader.h"
#include "EfiFirmwareFileSystem.h"
#include <string.h>
EFI_STATUS
InitializeFvLib (
IN VOID *Fv,
IN UINT32 FvLength
)
;
EFI_STATUS
GetFvHeader (
OUT EFI_FIRMWARE_VOLUME_HEADER **FvHeader,
OUT UINT32 *FvLength
)
;
EFI_STATUS
GetNextFile (
IN EFI_FFS_FILE_HEADER *CurrentFile,
OUT EFI_FFS_FILE_HEADER **NextFile
)
;
EFI_STATUS
GetFileByName (
IN EFI_GUID *FileName,
OUT EFI_FFS_FILE_HEADER **File
)
;
EFI_STATUS
GetFileByType (
IN EFI_FV_FILETYPE FileType,
IN UINTN Instance,
OUT EFI_FFS_FILE_HEADER **File
)
;
EFI_STATUS
GetSectionByType (
IN EFI_FFS_FILE_HEADER *File,
IN EFI_SECTION_TYPE SectionType,
IN UINTN Instance,
OUT EFI_FILE_SECTION_POINTER *Section
)
;
//
// will not parse compressed sections
//
EFI_STATUS
VerifyFv (
IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader
)
;
EFI_STATUS
VerifyFfsFile (
IN EFI_FFS_FILE_HEADER *FfsHeader
)
;
/*++
Routine Description:
Verify the current pointer points to a FFS file header.
Arguments:
FfsHeader Pointer to an alleged FFS file.
Returns:
EFI_SUCCESS The Ffs header is valid.
EFI_NOT_FOUND This "file" is the beginning of free space.
EFI_VOLUME_CORRUPTED The Ffs header is not valid.
--*/
UINT32
GetLength (
UINT8 *ThreeByteLength
)
;
/*++
Routine Description:
Converts a three byte length value into a UINT32.
Arguments:
ThreeByteLength Pointer to the first of the 3 byte length.
Returns:
UINT32 Size of the section
--*/
EFI_STATUS
GetErasePolarity (
OUT BOOLEAN *ErasePolarity
)
;
/*++
Routine Description:
This function returns with the FV erase polarity. If the erase polarity
for a bit is 1, the function return TRUE.
Arguments:
ErasePolarity A pointer to the erase polarity.
Returns:
EFI_SUCCESS The function completed successfully.
EFI_INVALID_PARAMETER One of the input parameters was invalid.
--*/
UINT8
GetFileState (
IN BOOLEAN ErasePolarity,
IN EFI_FFS_FILE_HEADER *FfsHeader
)
;
/*++
Routine Description:
This function returns a the highest state bit in the FFS that is set.
It in no way validate the FFS file.
Arguments:
ErasePolarity The erase polarity for the file state bits.
FfsHeader Pointer to a FFS file.
Returns:
UINT8 The hightest set state of the file.
--*/
#endif

View File

@@ -0,0 +1,145 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name: makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
TARGET_NAME = Common
TARGET_SRC_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
TARGET_LIB = $(EDK_TOOLS_OUTPUT)\Common.lib
TARGET_SOURCE_DIR = $(COMMON_SOURCE)
OBJECTS = "$(EDK_TOOLS_OUTPUT)\ParseInf.obj" \
"$(EDK_TOOLS_OUTPUT)\EfiCompress.obj" \
"$(EDK_TOOLS_OUTPUT)\TianoCompress.obj" \
"$(EDK_TOOLS_OUTPUT)\Decompress.obj" \
"$(EDK_TOOLS_OUTPUT)\crc32.obj" \
"$(EDK_TOOLS_OUTPUT)\CommonLib.obj" \
"$(EDK_TOOLS_OUTPUT)\PeCoffLoader.obj" \
"$(EDK_TOOLS_OUTPUT)\PeCoffLoaderEx.obj" \
"$(EDK_TOOLS_OUTPUT)\FvLib.obj" \
"$(EDK_TOOLS_OUTPUT)\EfiUtilityMsgs.obj" \
"$(EDK_TOOLS_OUTPUT)\SimpleFileParsing.obj" \
"$(EDK_TOOLS_OUTPUT)\MyAlloc.obj"
#
# Build targets
#
all: $(TARGET_LIB)
#
# Object targets
#
"$(EDK_TOOLS_OUTPUT)\ParseInf.obj": "$(TARGET_SOURCE_DIR)\ParseInf.c" "$(TARGET_SOURCE_DIR)\ParseInf.h" $(EDK_SOURCE)\Foundation\Include\TianoCommon.h
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\ParseInf.c" /Fo"$(EDK_TOOLS_OUTPUT)\ParseInf.obj"
"$(EDK_TOOLS_OUTPUT)\MyAlloc.obj": "$(TARGET_SOURCE_DIR)\MyAlloc.c" "$(TARGET_SOURCE_DIR)\MyAlloc.h" $(EDK_SOURCE)\Foundation\Include\TianoCommon.h
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\MyAlloc.c" /Fo"$(EDK_TOOLS_OUTPUT)\MyAlloc.obj"
"$(EDK_TOOLS_OUTPUT)\EfiCompress.obj": "$(TARGET_SOURCE_DIR)\EfiCompress.c" "$(TARGET_SOURCE_DIR)\Compress.h" $(EDK_SOURCE)\Foundation\Include\TianoCommon.h
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\EfiCompress.c" /Fo"$(EDK_TOOLS_OUTPUT)\EfiCompress.obj"
"$(EDK_TOOLS_OUTPUT)\TianoCompress.obj": "$(TARGET_SOURCE_DIR)\TianoCompress.c" "$(TARGET_SOURCE_DIR)\Compress.h" $(EDK_SOURCE)\Foundation\Include\TianoCommon.h
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\TianoCompress.c" /Fo"$(EDK_TOOLS_OUTPUT)\TianoCompress.obj"
"$(EDK_TOOLS_OUTPUT)\Decompress.obj": "$(TARGET_SOURCE_DIR)\Decompress.c" "$(TARGET_SOURCE_DIR)\Decompress.h" $(EDK_SOURCE)\Foundation\Include\TianoCommon.h
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\Decompress.c" /Fo"$(EDK_TOOLS_OUTPUT)\Decompress.obj"
"$(EDK_TOOLS_OUTPUT)\crc32.obj": "$(TARGET_SOURCE_DIR)\crc32.c" "$(TARGET_SOURCE_DIR)\crc32.h" $(EDK_SOURCE)\Foundation\Include\TianoCommon.h
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\crc32.c" /Fo"$(EDK_TOOLS_OUTPUT)\crc32.obj"
"$(EDK_TOOLS_OUTPUT)\CommonLib.obj": "$(TARGET_SOURCE_DIR)\CommonLib.c" "$(TARGET_SOURCE_DIR)\CommonLib.h" $(EDK_SOURCE)\Foundation\Include\TianoCommon.h
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\CommonLib.c" /Fo"$(EDK_TOOLS_OUTPUT)\CommonLib.obj"
"$(EDK_TOOLS_OUTPUT)\PeCoffLoader.obj": "$(EDK_SOURCE)\Foundation\Include\TianoCommon.h" "$(EDK_SOURCE)\Foundation\Library\Pei\PeiLib\$(PROCESSOR)\PeCoffLoaderEx.h" "$(EDK_SOURCE)\Foundation\Library\Pei\PeiLib\PeCoffLoader.c"
#
# This tool is built differently based on the target processor architecture.
# PE32/PE32+ headers are different for IA32 and IPF, so copy the correct file
# to the tools directory and include it in the build.
# Also copy PeCoffLoaderEx.h because it contains the checks for valid image
# type.
#
@copy "$(EDK_SOURCE)\Foundation\Include\$(PROCESSOR)\EfiPeOptionalHeader.h" $(EDK_TOOLS_OUTPUT)
@copy "$(EDK_SOURCE)\Foundation\Library\Pei\PeiLib\$(PROCESSOR)\PeCoffLoaderEx.h" $(EDK_TOOLS_OUTPUT)
$(CC) -I $(EDK_TOOLS_OUTPUT) $(C_FLAGS) -I "$(EDK_SOURCE)\Foundation\Library\Pei\PeiLib\$(PROCESSOR)" "$(EDK_SOURCE)\Foundation\Library\Pei\PeiLib\PeCoffLoader.c" /Fo"$(EDK_TOOLS_OUTPUT)\PeCoffLoader.obj"
"$(EDK_TOOLS_OUTPUT)\PeCoffLoaderEx.obj": "$(EDK_SOURCE)\Foundation\Library\Pei\PeiLib\$(PROCESSOR)\PeCoffLoaderEx.c"
$(CC) $(C_FLAGS) "$(EDK_SOURCE)\Foundation\Library\Pei\PeiLib\$(PROCESSOR)\PeCoffLoaderEx.c" /Fo"$(EDK_TOOLS_OUTPUT)\PeCoffLoaderEx.obj"
"$(EDK_TOOLS_OUTPUT)\FvLib.obj": "$(TARGET_SOURCE_DIR)\FvLib.c" "$(TARGET_SOURCE_DIR)\FvLib.h" $(EDK_SOURCE)\Sample\Include\Efi2WinNt.h $(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareFileSystem.h "$(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareVolumeHeader.h"
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\FvLib.c" /Fo"$(EDK_TOOLS_OUTPUT)\FvLib.obj"
"$(EDK_TOOLS_OUTPUT)\EfiUtilityMsgs.obj": "$(TARGET_SOURCE_DIR)\EfiUtilityMsgs.c" "$(TARGET_SOURCE_DIR)\EfiUtilityMsgs.h"
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\EfiUtilityMsgs.c" /Fo"$(EDK_TOOLS_OUTPUT)\EfiUtilityMsgs.obj"
"$(EDK_TOOLS_OUTPUT)\SimpleFileParsing.obj" : "$(TARGET_SOURCE_DIR)\SimpleFileParsing.c" "$(TARGET_SOURCE_DIR)\SimpleFileParsing.h"
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\SimpleFileParsing.c" /Fo"$(EDK_TOOLS_OUTPUT)\SimpleFileParsing.obj"
#
# Build LIB
#
#
# Add Binary Build description for this lib.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).lib))
$(TARGET_LIB): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).lib
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).lib $(TARGET_LIB) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME)Obj.pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME)Obj.pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Obj.pdb /Y
!ELSE
$(TARGET_LIB): $(OBJECTS)
$(LIB_EXE) $(LIB_FLAGS) $(OBJECTS) /OUT:$(TARGET_LIB)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_LIB) copy $(TARGET_LIB) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).lib /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Obj.pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Obj.pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME)Obj.pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\ParseInf.* del /q $(EDK_TOOLS_OUTPUT)\ParseInf.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\ParsePeim.* del /q $(EDK_TOOLS_OUTPUT)\ParsePeim.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\EfiCompress.* del /q $(EDK_TOOLS_OUTPUT)\EfiCompress.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\TianoCompress.* del /q $(EDK_TOOLS_OUTPUT)\TianoCompress.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\Decompress.* del /q $(EDK_TOOLS_OUTPUT)\Decompress.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\crc32.* del /q $(EDK_TOOLS_OUTPUT)\crc32.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\CommonLib.* del /q $(EDK_TOOLS_OUTPUT)\CommonLib.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\PeCoffLoader.* del /q $(EDK_TOOLS_OUTPUT)\PeCoffLoader.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\PeCoffLoaderEx.* del /q $(EDK_TOOLS_OUTPUT)\PeCoffLoaderEx.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\FvLib.* del /q $(EDK_TOOLS_OUTPUT)\FvLib.* > NUL
@if exist $(TARGET_LIB) del $(TARGET_LIB)

View File

@@ -0,0 +1,516 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
MyAlloc.c
Abstract:
File for memory allocation tracking functions.
--*/
#include "MyAlloc.h"
#if USE_MYALLOC
//
// Get back to original alloc/free calls.
//
#undef malloc
#undef calloc
#undef realloc
#undef free
//
// Start of allocation list.
//
static MY_ALLOC_STRUCT *MyAllocData = NULL;
//
//
//
static UINT32 MyAllocHeadMagik = MYALLOC_HEAD_MAGIK;
static UINT32 MyAllocTailMagik = MYALLOC_TAIL_MAGIK;
//
// ////////////////////////////////////////////////////////////////////////////
//
//
VOID
MyCheck (
BOOLEAN Final,
UINT8 File[],
UINTN Line
)
// *++
// Description:
//
// Check for corruptions in the allocated memory chain. If a corruption
// is detection program operation stops w/ an exit(1) call.
//
// Parameters:
//
// Final := When FALSE, MyCheck() returns if the allocated memory chain
// has not been corrupted. When TRUE, MyCheck() returns if there
// are no un-freed allocations. If there are un-freed allocations,
// they are displayed and exit(1) is called.
//
//
// File := Set to __FILE__ by macro expansion.
//
// Line := Set to __LINE__ by macro expansion.
//
// Returns:
//
// n/a
//
// --*/
//
{
MY_ALLOC_STRUCT *Tmp;
//
// Check parameters.
//
if (File == NULL || Line == 0) {
printf (
"\nMyCheck(Final=%u, File=%xh, Line=%u)"
"Invalid parameter(s).\n",
Final,
File,
Line
);
exit (1);
}
if (strlen (File) == 0) {
printf (
"\nMyCheck(Final=%u, File=%s, Line=%u)"
"Invalid parameter.\n",
Final,
File,
Line
);
exit (1);
}
//
// Check structure contents.
//
for (Tmp = MyAllocData; Tmp != NULL; Tmp = Tmp->Next) {
if (memcmp(Tmp->Buffer, &MyAllocHeadMagik, sizeof MyAllocHeadMagik) ||
memcmp(&Tmp->Buffer[Tmp->Size + sizeof(UINT32)], &MyAllocTailMagik, sizeof MyAllocTailMagik)) {
break;
}
}
//
// If Tmp is not NULL, the structure is corrupt.
//
if (Tmp != NULL) {
printf (
"\nMyCheck(Final=%u, File=%s, Line=%u)""\nStructure corrupted!"
"\nFile=%s, Line=%u, nSize=%u, Head=%xh, Tail=%xh\n",
Final,
File,
Line,
Tmp->File,
Tmp->Line,
Tmp->Size,
*(UINT32 *) (Tmp->Buffer),
*(UINT32 *) (&Tmp->Buffer[Tmp->Size + sizeof (UINT32)])
);
exit (1);
}
//
// If Final is TRUE, display the state of the structure chain.
//
if (Final) {
if (MyAllocData != NULL) {
printf (
"\nMyCheck(Final=%u, File=%s, Line=%u)"
"\nSome allocated items have not been freed.\n",
Final,
File,
Line
);
for (Tmp = MyAllocData; Tmp != NULL; Tmp = Tmp->Next) {
printf (
"File=%s, Line=%u, nSize=%u, Head=%xh, Tail=%xh\n",
Tmp->File,
Tmp->Line,
Tmp->Size,
*(UINT32 *) (Tmp->Buffer),
*(UINT32 *) (&Tmp->Buffer[Tmp->Size + sizeof (UINT32)])
);
}
}
}
}
//
// ////////////////////////////////////////////////////////////////////////////
//
//
VOID *
MyAlloc (
UINTN Size,
UINT8 File[],
UINTN Line
)
// *++
// Description:
//
// Allocate a new link in the allocation chain along with enough storage
// for the File[] string, requested Size and alignment overhead. If
// memory cannot be allocated or the allocation chain has been corrupted,
// exit(1) will be called.
//
// Parameters:
//
// Size := Number of bytes (UINT8) requested by the called.
// Size cannot be zero.
//
// File := Set to __FILE__ by macro expansion.
//
// Line := Set to __LINE__ by macro expansion.
//
// Returns:
//
// Pointer to the caller's buffer.
//
// --*/
//
{
MY_ALLOC_STRUCT *Tmp;
UINTN Len;
//
// Check for invalid parameters.
//
if (Size == 0 || File == NULL || Line == 0) {
printf (
"\nMyAlloc(Size=%u, File=%xh, Line=%u)"
"\nInvalid parameter(s).\n",
Size,
File,
Line
);
exit (1);
}
Len = strlen (File);
if (Len == 0) {
printf (
"\nMyAlloc(Size=%u, File=%s, Line=%u)"
"\nInvalid parameter.\n",
Size,
File,
Line
);
exit (1);
}
//
// Check the allocation list for corruption.
//
MyCheck (0, __FILE__, __LINE__);
//
// Allocate a new entry.
//
Tmp = calloc (
1,
sizeof (MY_ALLOC_STRUCT) + Len + 1 + sizeof (UINT64) + Size + (sizeof MyAllocHeadMagik) + (sizeof MyAllocTailMagik)
);
if (Tmp == NULL) {
printf (
"\nMyAlloc(Size=%u, File=%s, Line=%u)"
"\nOut of memory.\n",
Size,
File,
Line
);
exit (1);
}
//
// Fill in the new entry.
//
Tmp->File = ((UINT8 *) Tmp) + sizeof (MY_ALLOC_STRUCT);
strcpy (Tmp->File, File);
Tmp->Line = Line;
Tmp->Size = Size;
Tmp->Buffer = (UINT8 *) (((UINTN) Tmp + Len + 9) &~7);
memcpy (Tmp->Buffer, &MyAllocHeadMagik, sizeof MyAllocHeadMagik);
memcpy (
&Tmp->Buffer[Size + sizeof (UINT32)],
&MyAllocTailMagik,
sizeof MyAllocTailMagik
);
Tmp->Next = MyAllocData;
Tmp->Cksum = (UINTN) Tmp + (UINTN) (Tmp->Next) + Tmp->Line + Tmp->Size + (UINTN) (Tmp->File) + (UINTN) (Tmp->Buffer);
MyAllocData = Tmp;
return Tmp->Buffer + sizeof (UINT32);
}
//
// ////////////////////////////////////////////////////////////////////////////
//
//
VOID *
MyRealloc (
VOID *Ptr,
UINTN Size,
UINT8 File[],
UINTN Line
)
// *++
// Description:
//
// This does a MyAlloc(), memcpy() and MyFree(). There is no optimization
// for shrinking or expanding buffers. An invalid parameter will cause
// MyRealloc() to fail with a call to exit(1).
//
// Parameters:
//
// Ptr := Pointer to the caller's buffer to be re-allocated.
//
// Size := Size of new buffer. Size cannot be zero.
//
// File := Set to __FILE__ by macro expansion.
//
// Line := Set to __LINE__ by macro expansion.
//
// Returns:
//
// Pointer to new caller's buffer.
//
// --*/
//
{
MY_ALLOC_STRUCT *Tmp;
VOID *Buffer;
//
// Check for invalid parameter(s).
//
if (Size == 0 || File == NULL || Line == 0) {
printf (
"\nMyRealloc(Ptr=%xh, Size=%u, File=%xh, Line=%u)"
"\nInvalid parameter(s).\n",
Ptr,
Size,
File,
Line
);
exit (1);
}
if (strlen (File) == 0) {
printf (
"\nMyRealloc(Ptr=%xh, Size=%u, File=%s, Line=%u)"
"\nInvalid parameter.\n",
Ptr,
Size,
File,
Line
);
exit (1);
}
//
// Find existing buffer in allocation list.
//
if (Ptr == NULL) {
Tmp = NULL;
} else if (&MyAllocData->Buffer[sizeof (UINT32)] == Ptr) {
Tmp = MyAllocData;
} else {
for (Tmp = MyAllocData;; Tmp = Tmp->Next) {
if (Tmp->Next == NULL) {
printf (
"\nMyRealloc(Ptr=%xh, Size=%u, File=%s, Line=%u)"
"\nCould not find buffer.\n",
Ptr,
Size,
File,
Line
);
exit (1);
}
Tmp = Tmp->Next;
}
}
//
// Allocate new buffer, copy old data, free old buffer.
//
Buffer = MyAlloc (Size, File, Line);
if (Buffer != NULL && Tmp != NULL) {
memcpy (
Buffer,
&Tmp->Buffer[sizeof (UINT32)],
((Size <= Tmp->Size) ? Size : Tmp->Size)
);
MyFree (Ptr, __FILE__, __LINE__);
}
return Buffer;
}
//
// ////////////////////////////////////////////////////////////////////////////
//
//
VOID
MyFree (
VOID *Ptr,
UINT8 File[],
UINTN Line
)
// *++
// Description:
//
// Release a previously allocated buffer. Invalid parameters will cause
// MyFree() to fail with an exit(1) call.
//
// Parameters:
//
// Ptr := Pointer to the caller's buffer to be freed.
// A NULL pointer will be ignored.
//
// File := Set to __FILE__ by macro expansion.
//
// Line := Set to __LINE__ by macro expansion.
//
// Returns:
//
// n/a
//
// --*/
//
{
MY_ALLOC_STRUCT *Tmp;
MY_ALLOC_STRUCT *Tmp2;
//
// Check for invalid parameter(s).
//
if (File == NULL || Line == 0) {
printf (
"\nMyFree(Ptr=%xh, File=%xh, Line=%u)"
"\nInvalid parameter(s).\n",
Ptr,
File,
Line
);
exit (1);
}
if (strlen (File) == 0) {
printf (
"\nMyFree(Ptr=%xh, File=%s, Line=%u)"
"\nInvalid parameter.\n",
Ptr,
File,
Line
);
exit (1);
}
//
// Freeing NULL is always valid.
//
if (Ptr == NULL) {
return ;
}
//
// Fail if nothing is allocated.
//
if (MyAllocData == NULL) {
printf (
"\nMyFree(Ptr=%xh, File=%s, Line=%u)"
"\nCalled before memory allocated.\n",
Ptr,
File,
Line
);
exit (1);
}
//
// Check for corrupted allocation list.
//
MyCheck (0, __FILE__, __LINE__);
//
// Need special check for first item in list.
//
if (&MyAllocData->Buffer[sizeof (UINT32)] == Ptr) {
//
// Unlink first item in list.
//
Tmp = MyAllocData;
MyAllocData = MyAllocData->Next;
} else {
//
// Walk list looking for matching item.
//
for (Tmp = MyAllocData;; Tmp = Tmp->Next) {
//
// Fail if end of list is reached.
//
if (Tmp->Next == NULL) {
printf (
"\nMyFree(Ptr=%xh, File=%s, Line=%u)\n"
"\nNot found.\n",
Ptr,
File,
Line
);
exit (1);
}
//
// Leave loop when match is found.
//
if (&Tmp->Next->Buffer[sizeof (UINT32)] == Ptr) {
break;
}
}
//
// Unlink item from list.
//
Tmp2 = Tmp->Next;
Tmp->Next = Tmp->Next->Next;
Tmp = Tmp2;
}
//
// Release item.
//
free (Tmp);
}
#endif /* USE_MYALLOC */
/* eof - MyAlloc.c */

View File

@@ -0,0 +1,222 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
MyAlloc.h
Abstract:
Header file for memory allocation tracking functions.
--*/
#ifndef _MYALLOC_H_
#define _MYALLOC_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Tiano.h"
//
// Default operation is to use the memory allocation tracking functions.
// To over-ride add "#define USE_MYALLOC 0" to your program header and/or
// source files as needed. Or, just do not include this header file in
// your project.
//
#ifndef USE_MYALLOC
#define USE_MYALLOC 1
#endif
#if USE_MYALLOC
//
// Replace C library allocation routines with MyAlloc routines.
//
#define malloc(size) MyAlloc ((size), __FILE__, __LINE__)
#define calloc(count, size) MyAlloc ((count) * (size), __FILE__, __LINE__)
#define realloc(ptr, size) MyRealloc ((ptr), (size), __FILE__, __LINE__)
#define free(ptr) MyFree ((ptr), __FILE__, __LINE__)
#define alloc_check(final) MyCheck ((final), __FILE__, __LINE__)
//
// Structure for checking/tracking memory allocations.
//
typedef struct MyAllocStruct {
UINTN Cksum;
struct MyAllocStruct *Next;
UINTN Line;
UINTN Size;
UINT8 *File;
UINT8 *Buffer;
} MY_ALLOC_STRUCT;
//
// Cksum := (UINTN)This + (UINTN)Next + Line + Size + (UINTN)File +
// (UINTN)Buffer;
//
// Next := Pointer to next allocation structure in the list.
//
// Line := __LINE__
//
// Size := Size of allocation request.
//
// File := Pointer to __FILE__ string stored immediately following
// MY_ALLOC_STRUCT in memory.
//
// Buffer := Pointer to UINT32 aligned storage immediately following
// the NULL terminated __FILE__ string. This is UINT32
// aligned because the underflow signature is 32-bits and
// this will place the first caller address on a 64-bit
// boundary.
//
//
// Signatures used to check for buffer overflow/underflow conditions.
//
#define MYALLOC_HEAD_MAGIK 0xBADFACED
#define MYALLOC_TAIL_MAGIK 0xDEADBEEF
VOID
MyCheck (
BOOLEAN Final,
UINT8 File[],
UINTN Line
)
;
//
// *++
// Description:
//
// Check for corruptions in the allocated memory chain. If a corruption
// is detection program operation stops w/ an exit(1) call.
//
// Parameters:
//
// Final := When FALSE, MyCheck() returns if the allocated memory chain
// has not been corrupted. When TRUE, MyCheck() returns if there
// are no un-freed allocations. If there are un-freed allocations,
// they are displayed and exit(1) is called.
//
//
// File := Set to __FILE__ by macro expansion.
//
// Line := Set to __LINE__ by macro expansion.
//
// Returns:
//
// n/a
//
// --*/
//
VOID *
MyAlloc (
UINTN Size,
UINT8 File[],
UINTN Line
)
;
//
// *++
// Description:
//
// Allocate a new link in the allocation chain along with enough storage
// for the File[] string, requested Size and alignment overhead. If
// memory cannot be allocated or the allocation chain has been corrupted,
// exit(1) will be called.
//
// Parameters:
//
// Size := Number of bytes (UINT8) requested by the called.
// Size cannot be zero.
//
// File := Set to __FILE__ by macro expansion.
//
// Line := Set to __LINE__ by macro expansion.
//
// Returns:
//
// Pointer to the caller's buffer.
//
// --*/
//
VOID *
MyRealloc (
VOID *Ptr,
UINTN Size,
UINT8 File[],
UINTN Line
)
;
//
// *++
// Description:
//
// This does a MyAlloc(), memcpy() and MyFree(). There is no optimization
// for shrinking or expanding buffers. An invalid parameter will cause
// MyRealloc() to fail with a call to exit(1).
//
// Parameters:
//
// Ptr := Pointer to the caller's buffer to be re-allocated.
// Ptr cannot be NULL.
//
// Size := Size of new buffer. Size cannot be zero.
//
// File := Set to __FILE__ by macro expansion.
//
// Line := Set to __LINE__ by macro expansion.
//
// Returns:
//
// Pointer to new caller's buffer.
//
// --*/
//
VOID
MyFree (
VOID *Ptr,
UINT8 File[],
UINTN Line
)
;
//
// *++
// Description:
//
// Release a previously allocated buffer. Invalid parameters will cause
// MyFree() to fail with an exit(1) call.
//
// Parameters:
//
// Ptr := Pointer to the caller's buffer to be freed.
// A NULL pointer will be ignored.
//
// File := Set to __FILE__ by macro expansion.
//
// Line := Set to __LINE__ by macro expansion.
//
// Returns:
//
// n/a
//
// --*/
//
#else /* USE_MYALLOC */
//
// Nothing to do when USE_MYALLOC is zero.
//
#define alloc_check(final)
#endif /* USE_MYALLOC */
#endif /* _MYALLOC_H_ */
/* eof - MyAlloc.h */

View File

@@ -0,0 +1,625 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
ParseInf.c
Abstract:
This contains some useful functions for parsing INF files.
--*/
#include "ParseInf.h"
#include <assert.h>
#include <string.h>
#include <ctype.h>
CHAR8 *
ReadLine (
IN MEMORY_FILE *InputFile,
IN OUT CHAR8 *InputBuffer,
IN UINTN MaxLength
)
/*++
Routine Description:
This function reads a line, stripping any comments.
The function reads a string from the input stream argument and stores it in
the input string. ReadLine reads characters from the current file position
to and including the first newline character, to the end of the stream, or
until the number of characters read is equal to MaxLength - 1, whichever
comes first. The newline character, if read, is replaced with a \0.
Arguments:
InputFile Memory file image.
InputBuffer Buffer to read into, must be _MAX_PATH size.
MaxLength The maximum size of the input buffer.
Returns:
NULL if error or EOF
InputBuffer otherwise
--*/
{
CHAR8 *CharPtr;
CHAR8 *EndOfLine;
UINTN CharsToCopy;
//
// Verify input parameters are not null
//
assert (InputBuffer);
assert (InputFile->FileImage);
assert (InputFile->Eof);
assert (InputFile->CurrentFilePointer);
//
// Check for end of file condition
//
if (InputFile->CurrentFilePointer >= InputFile->Eof) {
return NULL;
}
//
// Find the next newline char
//
EndOfLine = strchr (InputFile->CurrentFilePointer, '\n');
//
// Determine the number of characters to copy.
//
if (EndOfLine == 0) {
//
// If no newline found, copy to the end of the file.
//
CharsToCopy = InputFile->Eof - InputFile->CurrentFilePointer;
} else if (EndOfLine >= InputFile->Eof) {
//
// If the newline found was beyond the end of file, copy to the eof.
//
CharsToCopy = InputFile->Eof - InputFile->CurrentFilePointer;
} else {
//
// Newline found in the file.
//
CharsToCopy = EndOfLine - InputFile->CurrentFilePointer;
}
//
// If the end of line is too big for the current buffer, set it to the max
// size of the buffer (leaving room for the \0.
//
if (CharsToCopy > MaxLength - 1) {
CharsToCopy = MaxLength - 1;
}
//
// Copy the line.
//
memcpy (InputBuffer, InputFile->CurrentFilePointer, CharsToCopy);
//
// Add the null termination over the 0x0D
//
InputBuffer[CharsToCopy - 1] = '\0';
//
// Increment the current file pointer (include the 0x0A)
//
InputFile->CurrentFilePointer += CharsToCopy + 1;
//
// Strip any comments
//
CharPtr = strstr (InputBuffer, "//");
if (CharPtr != 0) {
CharPtr[0] = 0;
}
//
// Return the string
//
return InputBuffer;
}
BOOLEAN
FindSection (
IN MEMORY_FILE *InputFile,
IN CHAR8 *Section
)
/*++
Routine Description:
This function parses a file from the beginning to find a section.
The section string may be anywhere within a line.
Arguments:
InputFile Memory file image.
Section Section to search for
Returns:
FALSE if error or EOF
TRUE if section found
--*/
{
CHAR8 InputBuffer[_MAX_PATH];
CHAR8 *CurrentToken;
//
// Verify input is not NULL
//
assert (InputFile->FileImage);
assert (InputFile->Eof);
assert (InputFile->CurrentFilePointer);
assert (Section);
//
// Rewind to beginning of file
//
InputFile->CurrentFilePointer = InputFile->FileImage;
//
// Read lines until the section is found
//
while (InputFile->CurrentFilePointer < InputFile->Eof) {
//
// Read a line
//
ReadLine (InputFile, InputBuffer, _MAX_PATH);
//
// Check if the section is found
//
CurrentToken = strstr (InputBuffer, Section);
if (CurrentToken != NULL) {
return TRUE;
}
}
return FALSE;
}
EFI_STATUS
FindToken (
IN MEMORY_FILE *InputFile,
IN CHAR8 *Section,
IN CHAR8 *Token,
IN UINTN Instance,
OUT CHAR8 *Value
)
/*++
Routine Description:
Finds a token value given the section and token to search for.
Arguments:
InputFile Memory file image.
Section The section to search for, a string within [].
Token The token to search for, e.g. EFI_PEIM_RECOVERY, followed by an = in the INF file.
Instance The instance of the token to search for. Zero is the first instance.
Value The string that holds the value following the =. Must be _MAX_PATH in size.
Returns:
EFI_SUCCESS Value found.
EFI_ABORTED Format error detected in INF file.
EFI_INVALID_PARAMETER Input argument was null.
EFI_LOAD_ERROR Error reading from the file.
EFI_NOT_FOUND Section/Token/Value not found.
--*/
{
CHAR8 InputBuffer[_MAX_PATH];
CHAR8 *CurrentToken;
BOOLEAN ParseError;
BOOLEAN ReadError;
UINTN Occurrance;
//
// Check input parameters
//
if (InputFile->FileImage == NULL ||
InputFile->Eof == NULL ||
InputFile->CurrentFilePointer == NULL ||
Section == NULL ||
strlen (Section) == 0 ||
Token == NULL ||
strlen (Token) == 0 ||
Value == NULL
) {
return EFI_INVALID_PARAMETER;
}
//
// Initialize error codes
//
ParseError = FALSE;
ReadError = FALSE;
//
// Initialize our instance counter for the search token
//
Occurrance = 0;
if (FindSection (InputFile, Section)) {
//
// Found the desired section, find and read the desired token
//
do {
//
// Read a line from the file
//
if (ReadLine (InputFile, InputBuffer, _MAX_PATH) == NULL) {
//
// Error reading from input file
//
ReadError = TRUE;
break;
}
//
// Get the first non-whitespace string
//
CurrentToken = strtok (InputBuffer, " \t\n");
if (CurrentToken == NULL) {
//
// Whitespace line found (or comment) so continue
//
CurrentToken = InputBuffer;
continue;
}
//
// Make sure we have not reached the end of the current section
//
if (CurrentToken[0] == '[') {
break;
}
//
// Compare the current token with the desired token
//
if (strcmp (CurrentToken, Token) == 0) {
//
// Found it
//
//
// Check if it is the correct instance
//
if (Instance == Occurrance) {
//
// Copy the contents following the =
//
CurrentToken = strtok (NULL, "= \t\n");
if (CurrentToken == NULL) {
//
// Nothing found, parsing error
//
ParseError = TRUE;
} else {
//
// Copy the current token to the output value
//
strcpy (Value, CurrentToken);
return EFI_SUCCESS;
}
} else {
//
// Increment the occurrance found
//
Occurrance++;
}
}
} while (
!ParseError &&
!ReadError &&
InputFile->CurrentFilePointer < InputFile->Eof &&
CurrentToken[0] != '[' &&
Occurrance <= Instance
);
}
//
// Distinguish between read errors and INF file format errors.
//
if (ReadError) {
return EFI_LOAD_ERROR;
}
if (ParseError) {
return EFI_ABORTED;
}
return EFI_NOT_FOUND;
}
EFI_STATUS
StringToGuid (
IN CHAR8 *AsciiGuidBuffer,
OUT EFI_GUID *GuidBuffer
)
/*++
Routine Description:
Converts a string to an EFI_GUID. The string must be in the
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format.
Arguments:
AsciiGuidBuffer - pointer to ascii string
GuidBuffer - pointer to destination Guid
Returns:
EFI_ABORTED Could not convert the string
EFI_SUCCESS The string was successfully converted
EFI_INVALID_PARAMETER Input parameter is invalid.
--*/
{
INT32 Index;
UINTN Data1;
UINTN Data2;
UINTN Data3;
UINTN Data4[8];
if (AsciiGuidBuffer == NULL || GuidBuffer == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Scan the guid string into the buffer
//
Index = sscanf (
AsciiGuidBuffer,
"%08x-%04x-%04x-%02x%02x-%02hx%02hx%02hx%02hx%02hx%02hx",
&Data1,
&Data2,
&Data3,
&Data4[0],
&Data4[1],
&Data4[2],
&Data4[3],
&Data4[4],
&Data4[5],
&Data4[6],
&Data4[7]
);
//
// Verify the correct number of items were scanned.
//
if (Index != 11) {
printf ("ERROR: Malformed GUID \"%s\".\n\n", AsciiGuidBuffer);
return EFI_ABORTED;
}
//
// Copy the data into our GUID.
//
GuidBuffer->Data1 = (UINT32) Data1;
GuidBuffer->Data2 = (UINT16) Data2;
GuidBuffer->Data3 = (UINT16) Data3;
GuidBuffer->Data4[0] = (UINT8) Data4[0];
GuidBuffer->Data4[1] = (UINT8) Data4[1];
GuidBuffer->Data4[2] = (UINT8) Data4[2];
GuidBuffer->Data4[3] = (UINT8) Data4[3];
GuidBuffer->Data4[4] = (UINT8) Data4[4];
GuidBuffer->Data4[5] = (UINT8) Data4[5];
GuidBuffer->Data4[6] = (UINT8) Data4[6];
GuidBuffer->Data4[7] = (UINT8) Data4[7];
return EFI_SUCCESS;
}
EFI_STATUS
AsciiStringToUint64 (
IN CONST CHAR8 *AsciiString,
IN BOOLEAN IsHex,
OUT UINT64 *ReturnValue
)
/*++
Routine Description:
Converts a null terminated ascii string that represents a number into a
UINT64 value. A hex number may be preceeded by a 0x, but may not be
succeeded by an h. A number without 0x or 0X is considered to be base 10
unless the IsHex input is true.
Arguments:
AsciiString The string to convert.
IsHex Force the string to be treated as a hex number.
ReturnValue The return value.
Returns:
EFI_SUCCESS Number successfully converted.
EFI_ABORTED Invalid character encountered.
--*/
{
UINT8 Index;
UINT64 HexNumber;
CHAR8 CurrentChar;
//
// Initialize the result
//
HexNumber = 0;
//
// Add each character to the result
//
if (IsHex || (AsciiString[0] == '0' && (AsciiString[1] == 'x' || AsciiString[1] == 'X'))) {
//
// Verify string is a hex number
//
for (Index = 2; Index < strlen (AsciiString); Index++) {
if (isxdigit (AsciiString[Index]) == 0) {
return EFI_ABORTED;
}
}
//
// Convert the hex string.
//
for (Index = 2; AsciiString[Index] != '\0'; Index++) {
CurrentChar = AsciiString[Index];
HexNumber *= 16;
if (CurrentChar >= '0' && CurrentChar <= '9') {
HexNumber += CurrentChar - '0';
} else if (CurrentChar >= 'a' && CurrentChar <= 'f') {
HexNumber += CurrentChar - 'a' + 10;
} else if (CurrentChar >= 'A' && CurrentChar <= 'F') {
HexNumber += CurrentChar - 'A' + 10;
} else {
//
// Unrecognized character
//
return EFI_ABORTED;
}
}
*ReturnValue = HexNumber;
} else {
//
// Verify string is a number
//
for (Index = 0; Index < strlen (AsciiString); Index++) {
if (isdigit (AsciiString[Index]) == 0) {
return EFI_ABORTED;
}
}
*ReturnValue = atol (AsciiString);
}
return EFI_SUCCESS;
};
CHAR8 *
ReadLineInStream (
IN FILE *InputFile,
IN OUT CHAR8 *InputBuffer
)
/*++
Routine Description:
This function reads a line, stripping any comments.
// BUGBUG: This is obsolete once genmake goes away...
Arguments:
InputFile Stream pointer.
InputBuffer Buffer to read into, must be _MAX_PATH size.
Returns:
NULL if error or EOF
InputBuffer otherwise
--*/
{
CHAR8 *CharPtr;
//
// Verify input parameters are not null
//
assert (InputFile);
assert (InputBuffer);
//
// Read a line
//
if (fgets (InputBuffer, _MAX_PATH, InputFile) == NULL) {
return NULL;
}
//
// Strip any comments
//
CharPtr = strstr (InputBuffer, "//");
if (CharPtr != 0) {
CharPtr[0] = 0;
}
CharPtr = strstr (InputBuffer, "#");
if (CharPtr != 0) {
CharPtr[0] = 0;
}
//
// Return the string
//
return InputBuffer;
}
BOOLEAN
FindSectionInStream (
IN FILE *InputFile,
IN CHAR8 *Section
)
/*++
Routine Description:
This function parses a stream file from the beginning to find a section.
The section string may be anywhere within a line.
// BUGBUG: This is obsolete once genmake goes away...
Arguments:
InputFile Stream pointer.
Section Section to search for
Returns:
FALSE if error or EOF
TRUE if section found
--*/
{
CHAR8 InputBuffer[_MAX_PATH];
CHAR8 *CurrentToken;
//
// Verify input is not NULL
//
assert (InputFile);
assert (Section);
//
// Rewind to beginning of file
//
if (fseek (InputFile, 0, SEEK_SET) != 0) {
return FALSE;
}
//
// Read lines until the section is found
//
while (feof (InputFile) == 0) {
//
// Read a line
//
ReadLineInStream (InputFile, InputBuffer);
//
// Check if the section is found
//
CurrentToken = strstr (InputBuffer, Section);
if (CurrentToken != NULL) {
return TRUE;
}
}
return FALSE;
}

View File

@@ -0,0 +1,233 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
ParseInf.h
Abstract:
Header file for helper functions useful for parsing INF files.
--*/
#ifndef _EFI_PARSE_INF_H
#define _EFI_PARSE_INF_H
#include "TianoCommon.h"
#include <stdio.h>
#include <stdlib.h>
//
// Common data structures
//
typedef struct {
CHAR8 *FileImage;
CHAR8 *Eof;
CHAR8 *CurrentFilePointer;
} MEMORY_FILE;
//
// Functions declarations
//
CHAR8 *
ReadLine (
IN MEMORY_FILE *InputFile,
IN OUT CHAR8 *InputBuffer,
IN UINT32 MaxLength
)
;
/*++
Routine Description:
This function reads a line, stripping any comments.
The function reads a string from the input stream argument and stores it in
the input string. ReadLine reads characters from the current file position
to and including the first newline character, to the end of the stream, or
until the number of characters read is equal to MaxLength - 1, whichever
comes first. The newline character, if read, is replaced with a \0.
Arguments:
InputFile Memory file image.
InputBuffer Buffer to read into, must be _MAX_PATH size.
MaxLength The maximum size of the input buffer.
Returns:
NULL if error or EOF
InputBuffer otherwise
--*/
BOOLEAN
FindSection (
IN MEMORY_FILE *InputFile,
IN CHAR8 *Section
)
;
/*++
Routine Description:
This function parses a file from the beginning to find a section.
The section string may be anywhere within a line.
Arguments:
InputFile Memory file image.
Section Section to search for
Returns:
FALSE if error or EOF
TRUE if section found
--*/
EFI_STATUS
FindToken (
IN MEMORY_FILE *InputFile,
IN CHAR8 *Section,
IN CHAR8 *Token,
IN UINTN Instance,
OUT CHAR8 *Value
)
;
/*++
Routine Description:
Finds a token value given the section and token to search for.
Arguments:
InputFile Memory file image.
Section The section to search for, a string within [].
Token The token to search for, e.g. EFI_PEIM_RECOVERY, followed by an = in the INF file.
Instance The instance of the token to search for. Zero is the first instance.
Value The string that holds the value following the =. Must be _MAX_PATH in size.
Returns:
EFI_SUCCESS Value found.
EFI_ABORTED Format error detected in INF file.
EFI_INVALID_PARAMETER Input argument was null.
EFI_LOAD_ERROR Error reading from the file.
EFI_NOT_FOUND Section/Token/Value not found.
--*/
EFI_STATUS
StringToGuid (
IN CHAR8 *AsciiGuidBuffer,
OUT EFI_GUID *GuidBuffer
)
;
/*++
Routine Description:
Converts a string to an EFI_GUID. The string must be in the
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx format.
Arguments:
GuidBuffer - pointer to destination Guid
AsciiGuidBuffer - pointer to ascii string
Returns:
EFI_ABORTED Could not convert the string
EFI_SUCCESS The string was successfully converted
--*/
EFI_STATUS
AsciiStringToUint64 (
IN CONST CHAR8 *AsciiString,
IN BOOLEAN IsHex,
OUT UINT64 *ReturnValue
)
;
/*++
Routine Description:
Converts a null terminated ascii string that represents a number into a
UINT64 value. A hex number may be preceeded by a 0x, but may not be
succeeded by an h. A number without 0x or 0X is considered to be base 10
unless the IsHex input is true.
Arguments:
AsciiString The string to convert.
IsHex Force the string to be treated as a hex number.
ReturnValue The return value.
Returns:
EFI_SUCCESS Number successfully converted.
EFI_ABORTED Invalid character encountered.
--*/
CHAR8 *
ReadLineInStream (
IN FILE *InputFile,
IN OUT CHAR8 *InputBuffer
)
;
/*++
Routine Description:
This function reads a line, stripping any comments.
Arguments:
InputFile Stream pointer.
InputBuffer Buffer to read into, must be _MAX_PATH size.
Returns:
NULL if error or EOF
InputBuffer otherwise
--*/
BOOLEAN
FindSectionInStream (
IN FILE *InputFile,
IN CHAR8 *Section
)
;
/*++
Routine Description:
This function parses a stream file from the beginning to find a section.
The section string may be anywhere within a line.
Arguments:
InputFile Stream pointer.
Section Section to search for
Returns:
FALSE if error or EOF
TRUE if section found
--*/
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,118 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
SimpleFileParsing.h
Abstract:
Function prototypes and defines for the simple file parsing routines.
--*/
#ifndef _SIMPLE_FILE_PARSING_H_
#define _SIMPLE_FILE_PARSING_H_
#define T_CHAR char
STATUS
SFPInit (
VOID
)
;
STATUS
SFPOpenFile (
char *FileName
)
;
BOOLEAN
SFPIsKeyword (
T_CHAR *Str
)
;
BOOLEAN
SFPIsToken (
T_CHAR *Str
)
;
BOOLEAN
SFPGetNextToken (
T_CHAR *Str,
unsigned int Len
)
;
BOOLEAN
SFPGetGuidToken (
T_CHAR *Str,
UINT32 Len
)
;
#define PARSE_GUID_STYLE_5_FIELDS 0
BOOLEAN
SFPGetGuid (
int GuidStyle,
EFI_GUID *Value
)
;
BOOLEAN
SFPSkipToToken (
T_CHAR *Str
)
;
BOOLEAN
SFPGetNumber (
unsigned int *Value
)
;
BOOLEAN
SFPGetQuotedString (
T_CHAR *Str,
int Length
)
;
BOOLEAN
SFPIsEOF (
VOID
)
;
STATUS
SFPCloseFile (
VOID
)
;
unsigned
int
SFPGetLineNumber (
VOID
)
;
T_CHAR *
SFPGetFileName (
VOID
)
;
#endif // #ifndef _SIMPLE_FILE_PARSING_H_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,146 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
CustomizedCompress.c
Abstract:
Header file for Customized compression routine
--*/
#include "TianoCommon.h"
EFI_STATUS
SetCustomizedCompressionType (
IN CHAR8 *Type
)
/*++
Routine Description:
The implementation of Customized SetCompressionType().
Arguments:
Type - The type if compression.
Returns:
EFI_SUCCESS - The type has been set.
EFI_UNSUPPORTED - This type is unsupported.
--*/
{
return EFI_UNSUPPORTED;
}
EFI_STATUS
CustomizedGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
)
/*++
Routine Description:
The implementation of Customized GetInfo().
Arguments:
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
DstSize - The size of destination buffer.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successull retrieved.
EFI_INVALID_PARAMETER - The source data is corrupted
EFI_UNSUPPORTED - The operation is unsupported.
--*/
{
return EFI_UNSUPPORTED;
}
EFI_STATUS
CustomizedDecompress (
IN VOID *Source,
IN UINT32 SrcSize,
IN OUT VOID *Destination,
IN UINT32 DstSize,
IN OUT VOID *Scratch,
IN UINT32 ScratchSize
)
/*++
Routine Description:
The implementation of Customized Decompress().
Arguments:
This - The protocol instance pointer
Source - The source buffer containing the compressed data.
SrcSize - The size of source buffer
Destination - The destination buffer to store the decompressed data
DstSize - The size of destination buffer.
Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data.
ScratchSize - The size of scratch buffer.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
EFI_UNSUPPORTED - The operation is unsupported.
--*/
{
return EFI_UNSUPPORTED;
}
EFI_STATUS
CustomizedCompress (
IN UINT8 *SrcBuffer,
IN UINT32 SrcSize,
IN UINT8 *DstBuffer,
IN OUT UINT32 *DstSize
)
/*++
Routine Description:
The Customized compression routine.
Arguments:
SrcBuffer - The buffer storing the source data
SrcSize - The size of source data
DstBuffer - The buffer to store the compressed data
DstSize - On input, the size of DstBuffer; On output,
the size of the actual compressed data.
Returns:
EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. In this case,
DstSize contains the size needed.
EFI_SUCCESS - Compression is successful.
EFI_UNSUPPORTED - The operation is unsupported.
--*/
{
return EFI_UNSUPPORTED;
}

View File

@@ -0,0 +1,82 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name: makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
TARGET_NAME = CustomizedCompress
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
TARGET_LIB = $(EDK_TOOLS_OUTPUT)\CustomizedCompress.lib
OBJECTS = "$(EDK_TOOLS_OUTPUT)\CustomizedCompress.obj"
#
# Build targets
#
all: $(TARGET_LIB)
#
# Object targets
#
"$(EDK_TOOLS_OUTPUT)\CustomizedCompress.obj": "$(TARGET_SOURCE_DIR)\CustomizedCompress.c" $(EDK_SOURCE)\Foundation\Include\EfiCommon.h
$(CC) $(C_FLAGS) "$(TARGET_SOURCE_DIR)\CustomizedCompress.c" /Fo"$(EDK_TOOLS_OUTPUT)\CustomizedCompress.obj"
#
# Build LIB
#
#
# Add Binary Build description for this lib.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).lib))
$(TARGET_LIB): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).lib
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).lib $(TARGET_LIB) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME)Obj.pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME)Obj.pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Obj.pdb /Y
!ELSE
$(TARGET_LIB): $(OBJECTS)
$(LIB_EXE) $(LIB_FLAGS) $(OBJECTS) /OUT:$(TARGET_LIB)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_LIB) copy $(TARGET_LIB) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).lib /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Obj.pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Obj.pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME)Obj.pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\CustomizedCompress.* del /q $(EDK_TOOLS_OUTPUT)\CustomizedCompress.* > NUL
@if exist $(TARGET_LIB) del $(TARGET_LIB)

View File

@@ -0,0 +1,386 @@
/*++
Copyright 2006 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
EfiCompressMain.c
Abstract:
--*/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include "TianoCommon.h"
#include "Compress.h"
typedef enum {
EFI_COMPRESS = 1,
TIANO_COMPRESS = 2
} COMPRESS_TYPE;
typedef struct _COMPRESS_ACTION_LIST {
struct _COMPRESS_ACTION_LIST *NextAction;
INT32 CompressType;
CHAR8 *InFileName;
CHAR8 *OutFileName;
} COMPRESS_ACTION_LIST;
STATIC
BOOLEAN
ParseCommandLine (
INT32 argc,
CHAR8 *argv[],
COMPRESS_ACTION_LIST **ActionListHead
)
/*++
Routine Description:
Parse command line options
Arguments:
argc - number of arguments passed into the command line.
argv[] - files to compress and files to output compressed data to.
Options - Point to COMMAND_LINE_OPTIONS, receiving command line options.
Returns:
BOOLEAN: TRUE for a successful parse.
--*/
;
STATIC
VOID
Usage (
CHAR8 *ExeName
)
/*++
Routine Description:
Print usage.
Arguments:
ExeName - Application's full path
--*/
;
STATIC
BOOLEAN
ProcessFile (
CHAR8 *InFileName,
CHAR8 *OutFileName,
COMPRESS_TYPE CompressType
)
/*++
Routine Description:
Compress InFileName to OutFileName using algorithm specified by CompressType.
Arguments:
InFileName - Input file to compress
OutFileName - Output file compress to
CompressType - Compress algorithm, can be EFI_COMPRESS or TIANO_COMPRESS
Returns:
BOOLEAN: TRUE for compress file successfully
--*/
;
int
main (
INT32 argc,
CHAR8 *argv[]
)
/*++
Routine Description:
Compresses the input files
Arguments:
argc - number of arguments passed into the command line.
argv[] - files to compress and files to output compressed data to.
Returns:
int: 0 for successful execution of the function.
--*/
{
COMPRESS_ACTION_LIST *ActionList;
COMPRESS_ACTION_LIST *NextAction;
UINT32 ActionCount;
UINT32 SuccessCount;
ActionList = NULL;
ActionCount = SuccessCount = 0;
if (!ParseCommandLine (argc, argv, &ActionList)) {
Usage (*argv);
return 1;
}
while (ActionList != NULL) {
++ActionCount;
if (ProcessFile (
ActionList->InFileName,
ActionList->OutFileName,
ActionList->CompressType)
) {
++SuccessCount;
}
NextAction = ActionList;
ActionList = ActionList->NextAction;
free (NextAction);
}
fprintf (stdout, "\nCompressed %d files, %d succeed!\n", ActionCount, SuccessCount);
if (SuccessCount < ActionCount) {
return 1;
}
return 0;
}
STATIC
BOOLEAN
ParseCommandLine (
INT32 argc,
CHAR8 *argv[],
COMPRESS_ACTION_LIST **ActionListHead
)
{
COMPRESS_TYPE CurrentType;
COMPRESS_ACTION_LIST **Action;
Action = ActionListHead;
CurrentType = EFI_COMPRESS; // default compress algorithm
// Skip Exe Name
--argc;
++argv;
while (argc > 0) {
if (strcmp (*argv, "-h") == 0 || strcmp (*argv, "-?") == 0) {
//
// 1. Directly return, help message will be printed.
//
return FALSE;
} else if (strncmp (*argv, "-t", 2) == 0) {
//
// 2. Specifying CompressType
//
if (_stricmp ((*argv)+2, "EFI") == 0) {
CurrentType = EFI_COMPRESS;
} else if (_stricmp ((*argv)+2, "Tiano") == 0) {
CurrentType = TIANO_COMPRESS;
} else {
fprintf (stdout, " ERROR: CompressType %s not supported!\n", (*argv)+2);
return FALSE;
}
} else {
//
// 3. Current parameter is *FileName
//
if (*Action == NULL) {
//
// need to create a new action item
//
*Action = (COMPRESS_ACTION_LIST*) malloc (sizeof **Action);
if (*Action == NULL) {
fprintf (stdout, " ERROR: malloc failed!\n");
return FALSE;
}
memset (*Action, 0, sizeof **Action);
(*Action)->CompressType = CurrentType;
}
//
// Assignment to InFileName and OutFileName in order
//
if ((*Action)->InFileName == NULL) {
(*Action)->InFileName = *argv;
} else {
(*Action)->OutFileName = *argv;
Action = &(*Action)->NextAction;
}
}
--argc;
++argv;
}
if (*Action != NULL) {
assert ((*Action)->InFileName != NULL);
fprintf (stdout, " ERROR: Compress OutFileName not specified with InFileName: %s!\n", (*Action)->InFileName);
return FALSE;
}
if (*ActionListHead == NULL) {
return FALSE;
}
return TRUE;
}
STATIC
BOOLEAN
ProcessFile (
CHAR8 *InFileName,
CHAR8 *OutFileName,
COMPRESS_TYPE CompressType
)
{
EFI_STATUS Status;
FILE *InFileP;
FILE *OutFileP;
UINT32 SrcSize;
UINT32 DstSize;
UINT8 *SrcBuffer;
UINT8 *DstBuffer;
COMPRESS_FUNCTION CompressFunc;
SrcBuffer = DstBuffer = NULL;
InFileP = OutFileP = NULL;
fprintf (stdout, "%s --> %s\n", InFileName, OutFileName);
if ((OutFileP = fopen (OutFileName, "wb")) == NULL) {
fprintf (stdout, " ERROR: Can't open output file %s for write!\n", OutFileName);
goto ErrorHandle;
}
if ((InFileP = fopen (InFileName, "rb")) == NULL) {
fprintf (stdout, " ERROR: Can't open input file %s for read!\n", InFileName);
goto ErrorHandle;
}
//
// Get the size of source file
//
fseek (InFileP, 0, SEEK_END);
SrcSize = ftell (InFileP);
rewind (InFileP);
//
// Read in the source data
//
if ((SrcBuffer = malloc (SrcSize)) == NULL) {
fprintf (stdout, " ERROR: Can't allocate memory!\n");
goto ErrorHandle;
}
if (fread (SrcBuffer, 1, SrcSize, InFileP) != SrcSize) {
fprintf (stdout, " ERROR: Can't read from source!\n");
goto ErrorHandle;
}
//
// Choose the right compress algorithm
//
CompressFunc = (CompressType == EFI_COMPRESS) ? EfiCompress : TianoCompress;
//
// Get destination data size and do the compression
//
DstSize = 0;
Status = CompressFunc (SrcBuffer, SrcSize, DstBuffer, &DstSize);
if (Status != EFI_BUFFER_TOO_SMALL) {
fprintf (stdout, " Error: Compress failed: %x!\n", Status);
goto ErrorHandle;
}
if ((DstBuffer = malloc (DstSize)) == NULL) {
fprintf (stdout, " ERROR: Can't allocate memory!\n");
goto ErrorHandle;
}
Status = CompressFunc (SrcBuffer, SrcSize, DstBuffer, &DstSize);
if (EFI_ERROR (Status)) {
fprintf (stdout, " ERROR: Compress Error!\n");
goto ErrorHandle;
}
fprintf (stdout, " Orig Size = %ld\tComp Size = %ld\n", SrcSize, DstSize);
if (DstBuffer == NULL) {
fprintf (stdout, " ERROR: No destination to write to!\n");
goto ErrorHandle;
}
//
// Write out the result
//
if (fwrite (DstBuffer, 1, DstSize, OutFileP) != DstSize) {
fprintf (stdout, " ERROR: Can't write to destination file!\n");
goto ErrorHandle;
}
return TRUE;
ErrorHandle:
if (SrcBuffer) {
free (SrcBuffer);
}
if (DstBuffer) {
free (DstBuffer);
}
if (InFileP) {
fclose (InFileP);
}
if (OutFileP) {
fclose (OutFileP);
}
return FALSE;
}
VOID
Usage (
CHAR8 *ExeName
)
{
fprintf (
stdout,
"\n"
"Usage: %s [-tCompressType] InFileName OutFileName\n"
" %*c [[-tCompressType] InFileName OutFileName ...]\n"
"\n"
"where:\n"
" CompressType - optional compress algorithm (EFI | Tiano), case insensitive.\n"
" If ommitted, compress type specified ahead is used, \n"
" default is EFI\n"
" e.g.: EfiCompress a.in a.out -tTiano b.in b.out \\ \n"
" c.in c.out -tEFI d.in d.out\n"
" a.in and d.in are compressed using EFI compress algorithm\n"
" b.in and c.in are compressed using Tiano compress algorithm\n"
" InFileName - input file path\n"
" OutFileName - output file path\n",
ExeName, strlen(ExeName), ' '
);
}

View File

@@ -0,0 +1,89 @@
#/*++
#
# Copyright (c) 2006 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=EfiCompress
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\EfiCompressMain.c"
TARGET_EXE_INCLUDE = "$(COMMON_SOURCE)\Compress.h"
TARGET_EXE_LIBS = "$(EDK_TOOLS_OUTPUT)\Common.lib"
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\EfiCompressMain.obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\EfiCompressMain.obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\EfiCompressMain.obj $(TARGET_EXE_LIBS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\EfiCompressMain.obj $(TARGET_EXE_LIBS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Main.* del /q $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Main.* > NUL

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,85 @@
#/*++
#
# Copyright (c) 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the EfiRom utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Target specific information
#
TARGET_NAME = EfiRom
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
#
# Build targets
#
all: $(TARGET_EXE)
OBJECTS = $(EDK_TOOLS_OUTPUT)\EfiRom.obj \
$(EDK_TOOLS_OUTPUT)\EfiCompress.obj
#
# Build the EXE by compiling the source files, then linking the resultant
# object files together.
#
$(EDK_TOOLS_OUTPUT)\EfiRom.obj : $(TARGET_SOURCE_DIR)\EfiRom.c
$(CC) $(C_FLAGS) $(TARGET_SOURCE_DIR)\EfiRom.c /Fo$@
$(EDK_TOOLS_OUTPUT)\EfiCompress.obj : $(EDK_TOOLS_SOURCE)\Common\EfiCompress.c
$(CC) $(C_FLAGS) $(EDK_TOOLS_SOURCE)\Common\EfiCompress.c /Fo$@
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(OBJECTS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,96 @@
#/*++
#
# Copyright (c) 2006 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the EfildrImage utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=EfildrImage
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\EfildrImage.c"
TARGET_EXE_INCLUDE =
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,188 @@
/*++
Copyright 2006 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
efildrimage.c
Abstract:
Creates and EFILDR image.
This tool combines several PE Image files together using following format denoted as EBNF:
FILE := EFILDR_HEADER
EFILDR_IMAGE +
<PeImageFileContent> +
The order of EFILDR_IMAGE is same as the order of placing PeImageFileContent.
Revision History
--*/
#include <windows.h>
#include <stdio.h>
#include "Tiano.h"
#define MAX_PE_IMAGES 63
#define FILE_TYPE_FIXED_LOADER 0
#define FILE_TYPE_RELOCATABLE_PE_IMAGE 1
typedef struct {
UINT32 CheckSum;
UINT32 Offset;
UINT32 Length;
UINT8 FileName[52];
} EFILDR_IMAGE;
typedef struct {
UINT32 Signature;
UINT32 HeaderCheckSum;
UINT32 FileLength;
UINT32 NumberOfImages;
} EFILDR_HEADER;
VOID
Usage (
VOID
)
{
printf ("Usage: EfiLdrImage OutImage LoaderImage PeImage1 PeImage2 ... PeImageN");
exit (1);
}
ULONG
FCopyFile (
FILE *in,
FILE *out
)
/*++
Routine Description:
Write all the content of input file to output file.
Arguments:
in - input file pointer
out - output file pointer
Return:
ULONG : file size of input file
--*/
{
ULONG filesize, offset, length;
UCHAR Buffer[8*1024];
fseek (in, 0, SEEK_END);
filesize = ftell(in);
fseek (in, 0, SEEK_SET);
offset = 0;
while (offset < filesize) {
length = sizeof(Buffer);
if (filesize-offset < length) {
length = filesize-offset;
}
fread (Buffer, length, 1, in);
fwrite (Buffer, length, 1, out);
offset += length;
}
return filesize;
}
int
main (
int argc,
char *argv[]
)
/*++
Routine Description:
Arguments:
Returns:
--*/
{
ULONG i;
ULONG filesize;
FILE *fpIn, *fpOut;
EFILDR_HEADER EfiLdrHeader;
EFILDR_IMAGE EfiLdrImage[MAX_PE_IMAGES];
if (argc < 4) {
Usage();
}
//
// Open output file for write
//
fpOut = fopen(argv[1], "w+b");
if (!fpOut) {
printf ("efildrimage: Could not open output file %s\n", argv[1]);
exit(1);
}
memset (&EfiLdrHeader, 0, sizeof (EfiLdrHeader));
memset (&EfiLdrImage, 0, sizeof (EFILDR_IMAGE) * (argc - 2));
memcpy (&EfiLdrHeader.Signature, "EFIL", 4);
EfiLdrHeader.FileLength = sizeof(EFILDR_HEADER) + sizeof(EFILDR_IMAGE)*(argc-2);
//
// Skip the file header first
//
fseek (fpOut, EfiLdrHeader.FileLength, SEEK_SET);
//
// copy all the input files to the output file
//
for(i=2;i<(ULONG)argc;i++) {
//
// Copy the content of PeImage file to output file
//
fpIn = fopen (argv[i], "rb");
if (!fpIn) {
printf ("efildrimage: Could not open input file %s\n", argv[i-2]);
exit(1);
}
filesize = FCopyFile (fpIn, fpOut);
fclose(fpIn);
//
// And in the same time update the EfiLdrHeader and EfiLdrImage array
//
EfiLdrImage[i-2].Offset = EfiLdrHeader.FileLength;
EfiLdrImage[i-2].Length = filesize;
strncpy (EfiLdrImage[i-2].FileName, argv[i], sizeof (EfiLdrImage[i-2].FileName) - 1);
EfiLdrHeader.FileLength += filesize;
EfiLdrHeader.NumberOfImages++;
}
//
// Write the image header to the output file finally
//
fseek (fpOut, 0, SEEK_SET);
fwrite (&EfiLdrHeader, sizeof(EFILDR_HEADER) , 1, fpOut);
fwrite (&EfiLdrImage , sizeof(EFILDR_IMAGE)*(argc-2), 1, fpOut);
fclose (fpOut);
printf ("Created %s\n", argv[1]);
return 0;
}

View File

@@ -0,0 +1,86 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name: makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=FwImage
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\FwImage.c"
TARGET_EXE_INCLUDE = "$(EDK_SOURCE)\Foundation\Include\TianoCommon.h" \
"$(EDK_SOURCE)\Foundation\Efi\Include\EfiImage.h"
OBJECTS = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE) : $(OBJECTS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,587 @@
/*++
Copyright (c) 2004 - 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
fwimage.c
Abstract:
Converts a pe32/pe32+ image to an FW image type
--*/
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "TianoCommon.h"
#include "EfiImage.h"
#include "EfiUtilityMsgs.c"
#define UTILITY_NAME "FwImage"
typedef union {
IMAGE_NT_HEADERS32 PeHeader32;
IMAGE_NT_HEADERS64 PeHeader64;
} PE_HEADER;
VOID
Usage (
VOID
)
{
printf ("Usage: " UTILITY_NAME " {-t time-date} {-e} {-r} [APPLICATION|BS_DRIVER|RT_DRIVER|SAL_RT_DRIVER|COMBINED_PEIM_DRIVER|SECURITY_CORE|PEI_CORE|PE32_PEIM|RELOCATABLE_PEIM] peimage [outimage]\n");
printf (" -t: Add Time Stamp for output image\n");
printf (" -e: Not clear ExceptionTable for output image\n");
printf (" -r: Not strip zero pending of .reloc for output image\n");
}
static
STATUS
FReadFile (
FILE *in,
VOID **Buffer,
UINTN *Length
)
{
fseek (in, 0, SEEK_END);
*Length = ftell (in);
*Buffer = malloc (*Length);
fseek (in, 0, SEEK_SET);
fread (*Buffer, *Length, 1, in);
return STATUS_SUCCESS;
}
static
STATUS
FWriteFile (
FILE *out,
VOID *Buffer,
UINTN Length
)
{
fseek (out, 0, SEEK_SET);
fwrite (Buffer, Length, 1, out);
if ((ULONG) ftell (out) != Length) {
Error (NULL, 0, 0, "write error", NULL);
return STATUS_ERROR;
}
free (Buffer);
return STATUS_SUCCESS;
}
VOID
ZeroExceptionTable (
IN UINT8 *FileBuffer,
IN EFI_IMAGE_DOS_HEADER *DosHdr,
IN PE_HEADER *PeHdr
)
{
UINT32 PdataSize;
UINT32 PdataOffset;
UINT32 PdataRVASize;
UINT32 PdataRVA;
UINT32 SectionOffset;
UINT16 SectionNumber;
UINT32 SectionNameSize;
EFI_IMAGE_SECTION_HEADER *Section;
PdataSize = 0;
PdataOffset = 0;
PdataRVASize = 0;
PdataRVA = 0;
SectionOffset = 0;
//
// Search .pdata section
//
if (PeHdr->PeHeader32.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
if ((PeHdr->PeHeader32.OptionalHeader.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_EXCEPTION) &&
(PeHdr->PeHeader32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress != 0) &&
(PeHdr->PeHeader32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size != 0)) {
PdataRVA = PeHdr->PeHeader32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress;
PdataRVASize = PeHdr->PeHeader32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size;
PeHdr->PeHeader32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress = 0;
PeHdr->PeHeader32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size = 0;
SectionOffset = sizeof(PeHdr->PeHeader32);
}
} else {
if ((PeHdr->PeHeader64.OptionalHeader.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_EXCEPTION) &&
(PeHdr->PeHeader64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress != 0) &&
(PeHdr->PeHeader64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size != 0)) {
PdataRVA = PeHdr->PeHeader64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress;
PdataRVASize = PeHdr->PeHeader64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size;
PeHdr->PeHeader64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress = 0;
PeHdr->PeHeader64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size = 0;
SectionOffset = sizeof(PeHdr->PeHeader64);
}
}
if ((PdataRVASize != 0) && (PdataRVA != 0)) {
SectionNumber = PeHdr->PeHeader32.FileHeader.NumberOfSections;
SectionNameSize = sizeof(Section->Name);
while (SectionNumber > 0) {
Section = (EFI_IMAGE_SECTION_HEADER *) &FileBuffer[DosHdr->e_lfanew + SectionOffset];
if (strcmp (Section->Name, ".pdata") == 0) {
//
// Zero .pdata Section Header Name
//
memset (
FileBuffer + DosHdr->e_lfanew + SectionOffset,
0,
SectionNameSize);
//
// Zero .pdata Secton raw data
//
PdataOffset = Section->PointerToRawData;
PdataSize = Section->SizeOfRawData;
memset (FileBuffer + PdataOffset, 0, PdataSize);
break;
}
SectionNumber--;
SectionOffset += sizeof(EFI_IMAGE_SECTION_HEADER);
}
}
return ;
}
VOID
StripZeroPendingReloc (
IN UINT8 *FileBuffer,
IN OUT UINTN *FileLength,
IN EFI_IMAGE_DOS_HEADER *DosHdr,
IN PE_HEADER *PeHdr
)
{
EFI_IMAGE_OPTIONAL_HEADER32 *Optional32;
EFI_IMAGE_OPTIONAL_HEADER64 *Optional64;
EFI_IMAGE_SECTION_HEADER *SectionHeader;
UINTN AllignedRelocSize;
UINTN Index;
if (PeHdr->PeHeader32.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
Optional32 = (EFI_IMAGE_OPTIONAL_HEADER32 *)&PeHdr->PeHeader32.OptionalHeader;
if ((Optional32->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) &&
(Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size != 0)) {
SectionHeader = (EFI_IMAGE_SECTION_HEADER *)(FileBuffer + DosHdr->e_lfanew + sizeof(UINT32) + sizeof (EFI_IMAGE_FILE_HEADER) + PeHdr->PeHeader32.FileHeader.SizeOfOptionalHeader);
for (Index = 0; Index < PeHdr->PeHeader32.FileHeader.NumberOfSections; Index++, SectionHeader++) {
//
// Look for the Section Header that starts as the same virtual address as the Base Relocation Data Directory
//
if (strcmp (SectionHeader->Name, ".reloc") == 0) {
SectionHeader->Misc.VirtualSize = Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
AllignedRelocSize = (Optional32->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size +
Optional32->FileAlignment - 1) & (~(Optional32->FileAlignment - 1));
//
// Check to see if there is zero padding at the end of the base relocations
//
if (AllignedRelocSize < SectionHeader->SizeOfRawData) {
//
// Check to see if the base relocations are at the end of the file
//
if (SectionHeader->PointerToRawData + SectionHeader->SizeOfRawData == Optional32->SizeOfImage) {
//
// All the required conditions are met to strip the zero padding of the end of the base relocations section
//
Optional32->SizeOfImage -= (SectionHeader->SizeOfRawData - AllignedRelocSize);
Optional32->SizeOfInitializedData -= (SectionHeader->SizeOfRawData - AllignedRelocSize);
SectionHeader->SizeOfRawData = AllignedRelocSize;
*FileLength = Optional32->SizeOfImage;
}
}
}
}
}
} else {
Optional64 = (EFI_IMAGE_OPTIONAL_HEADER64 *)&PeHdr->PeHeader64.OptionalHeader;
if ((Optional64->NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) &&
(Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size != 0)) {
SectionHeader = (EFI_IMAGE_SECTION_HEADER *)(FileBuffer + DosHdr->e_lfanew + sizeof(UINT32) + sizeof (EFI_IMAGE_FILE_HEADER) + PeHdr->PeHeader64.FileHeader.SizeOfOptionalHeader);
for (Index = 0; Index < PeHdr->PeHeader64.FileHeader.NumberOfSections; Index++, SectionHeader++) {
//
// Look for the Section Header that starts as the same virtual address as the Base Relocation Data Directory
//
if (strcmp (SectionHeader->Name, ".reloc") == 0) {
SectionHeader->Misc.VirtualSize = Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
AllignedRelocSize = (Optional64->DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size +
Optional64->FileAlignment - 1) & (~(Optional64->FileAlignment - 1));
//
// Check to see if there is zero padding at the end of the base relocations
//
if (AllignedRelocSize < SectionHeader->SizeOfRawData) {
//
// Check to see if the base relocations are at the end of the file
//
if (SectionHeader->PointerToRawData + SectionHeader->SizeOfRawData == Optional64->SizeOfImage) {
//
// All the required conditions are met to strip the zero padding of the end of the base relocations section
//
Optional64->SizeOfImage -= (SectionHeader->SizeOfRawData - AllignedRelocSize);
Optional64->SizeOfInitializedData -= (SectionHeader->SizeOfRawData - AllignedRelocSize);
SectionHeader->SizeOfRawData = AllignedRelocSize;
*FileLength = Optional64->SizeOfImage;
}
}
}
}
}
}
}
int
main (
int argc,
char *argv[]
)
/*++
Routine Description:
Main function.
Arguments:
argc - Number of command line parameters.
argv - Array of pointers to command line parameter strings.
Returns:
STATUS_SUCCESS - Utility exits successfully.
STATUS_ERROR - Some error occurred during execution.
--*/
{
ULONG Type;
PUCHAR Ext;
PUCHAR p;
PUCHAR pe;
PUCHAR OutImageName;
UCHAR outname[500];
FILE *fpIn;
FILE *fpOut;
EFI_IMAGE_DOS_HEADER *DosHdr;
PE_HEADER *PeHdr;
time_t TimeStamp;
struct tm TimeStruct;
EFI_IMAGE_DOS_HEADER BackupDosHdr;
ULONG Index;
BOOLEAN TimeStampPresent;
BOOLEAN NeedClearExceptionTable;
BOOLEAN NeedStripZeroPendingReloc;
UINT8 *FileBuffer;
UINTN FileLength;
EFI_IMAGE_OPTIONAL_HEADER32 *Optional32;
EFI_IMAGE_OPTIONAL_HEADER64 *Optional64;
SetUtilityName (UTILITY_NAME);
//
// Assign to fix compile warning
//
OutImageName = NULL;
Type = 0;
Ext = 0;
TimeStamp = 0;
TimeStampPresent = FALSE;
NeedClearExceptionTable = TRUE;
NeedStripZeroPendingReloc = TRUE;
//
// Look for -t time-date option first. If the time is "0", then
// skip it.
//
if ((argc > 2) && !strcmp (argv[1], "-t")) {
TimeStampPresent = TRUE;
if (strcmp (argv[2], "0") != 0) {
//
// Convert the string to a value
//
memset ((char *) &TimeStruct, 0, sizeof (TimeStruct));
if (sscanf(
argv[2], "%d/%d/%d,%d:%d:%d",
&TimeStruct.tm_mon, /* months since January - [0,11] */
&TimeStruct.tm_mday, /* day of the month - [1,31] */
&TimeStruct.tm_year, /* years since 1900 */
&TimeStruct.tm_hour, /* hours since midnight - [0,23] */
&TimeStruct.tm_min, /* minutes after the hour - [0,59] */
&TimeStruct.tm_sec /* seconds after the minute - [0,59] */
) != 6) {
Error (NULL, 0, 0, argv[2], "failed to convert to mm/dd/yyyy,hh:mm:ss format");
return STATUS_ERROR;
}
//
// Now fixup some of the fields
//
TimeStruct.tm_mon--;
TimeStruct.tm_year -= 1900;
//
// Sanity-check values?
// Convert
//
TimeStamp = mktime (&TimeStruct);
if (TimeStamp == (time_t) - 1) {
Error (NULL, 0, 0, argv[2], "failed to convert time");
return STATUS_ERROR;
}
}
//
// Skip over the args
//
argc -= 2;
argv += 2;
}
//
// Look for -e option.
//
if ((argc > 1) && !strcmp (argv[1], "-e")) {
NeedClearExceptionTable = FALSE;
//
// Skip over the args
//
argc -= 1;
argv += 1;
}
//
// Look for -r option
//
if ((argc > 1) && !strcmp (argv[1], "-r")) {
NeedStripZeroPendingReloc = FALSE;
//
// Skip over the args
//
argc -= 1;
argv += 1;
}
//
// Check for enough args
//
if (argc < 3) {
Usage ();
return STATUS_ERROR;
}
if (argc == 4) {
OutImageName = argv[3];
}
//
// Get new image type
//
p = argv[1];
if (*p == '/' || *p == '\\') {
p += 1;
}
if (_stricmp (p, "app") == 0 || _stricmp (p, "APPLICATION") == 0) {
Type = EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION;
Ext = ".efi";
} else if (_stricmp (p, "bsdrv") == 0 || _stricmp (p, "BS_DRIVER") == 0) {
Type = EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER;
Ext = ".efi";
} else if (_stricmp (p, "rtdrv") == 0 || _stricmp (p, "RT_DRIVER") == 0) {
Type = EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER;
Ext = ".efi";
} else if (_stricmp (p, "rtdrv") == 0 || _stricmp (p, "SAL_RT_DRIVER") == 0) {
Type = EFI_IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER;
Ext = ".efi";
} else if (_stricmp (p, "SECURITY_CORE") == 0) {
Type = EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER;
Ext = ".sec";
} else if (_stricmp (p, "peim") == 0 ||
_stricmp (p, "PEI_CORE") == 0 ||
_stricmp (p, "PE32_PEIM") == 0 ||
_stricmp (p, "RELOCATABLE_PEIM") == 0 ||
_stricmp (p, "combined_peim_driver") == 0
) {
Type = EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER;
Ext = ".pei";
} else {
Usage ();
return STATUS_ERROR;
}
//
// open source file
//
fpIn = fopen (argv[2], "rb");
if (!fpIn) {
Error (NULL, 0, 0, argv[2], "failed to open input file for reading");
return STATUS_ERROR;
}
FReadFile (fpIn, (VOID **)&FileBuffer, &FileLength);
//
// Read the dos & pe hdrs of the image
//
DosHdr = (EFI_IMAGE_DOS_HEADER *) FileBuffer;
if (DosHdr->e_magic != IMAGE_DOS_SIGNATURE) {
Error (NULL, 0, 0, argv[2], "DOS header signature not found in source image");
fclose (fpIn);
return STATUS_ERROR;
}
PeHdr = (PE_HEADER *)(FileBuffer + DosHdr->e_lfanew);
if (PeHdr->PeHeader32.Signature != IMAGE_NT_SIGNATURE) {
Error (NULL, 0, 0, argv[2], "PE header signature not found in source image");
fclose (fpIn);
return STATUS_ERROR;
}
//
// open output file
//
strcpy (outname, argv[2]);
pe = NULL;
for (p = outname; *p; p++) {
if (*p == '.') {
pe = p;
}
}
if (!pe) {
pe = p;
}
strcpy (pe, Ext);
if (!OutImageName) {
OutImageName = outname;
}
fpOut = fopen (OutImageName, "w+b");
if (!fpOut) {
Error (NULL, 0, 0, OutImageName, "could not open output file for writing");
fclose (fpIn);
return STATUS_ERROR;
}
//
// Zero all unused fields of the DOS header
//
memcpy (&BackupDosHdr, DosHdr, sizeof (EFI_IMAGE_DOS_HEADER));
memset (DosHdr, 0, sizeof (EFI_IMAGE_DOS_HEADER));
DosHdr->e_magic = BackupDosHdr.e_magic;
DosHdr->e_lfanew = BackupDosHdr.e_lfanew;
for (Index = sizeof (EFI_IMAGE_DOS_HEADER); Index < (ULONG) DosHdr->e_lfanew; Index++) {
FileBuffer[Index] = (UINT8) DosHdr->e_cp;
}
//
// Modify some fields in the PE header
//
//
// TimeDateStamp's offset is fixed for PE32/32+
//
if (TimeStampPresent) {
PeHdr->PeHeader32.FileHeader.TimeDateStamp = (UINT32) TimeStamp;
}
//
// PE32/32+ has different optional header layout
// Determine format is PE32 or PE32+ before modification
//
if (PeHdr->PeHeader32.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
//
// PE32 image
//
Optional32 = (EFI_IMAGE_OPTIONAL_HEADER32 *)&PeHdr->PeHeader32.OptionalHeader;
Optional32->MajorLinkerVersion = 0;
Optional32->MinorLinkerVersion = 0;
Optional32->MajorOperatingSystemVersion = 0;
Optional32->MinorOperatingSystemVersion = 0;
Optional32->MajorImageVersion = 0;
Optional32->MinorImageVersion = 0;
Optional32->MajorSubsystemVersion = 0;
Optional32->MinorSubsystemVersion = 0;
Optional32->Win32VersionValue = 0;
Optional32->CheckSum = 0;
Optional32->SizeOfStackReserve = 0;
Optional32->SizeOfStackCommit = 0;
Optional32->SizeOfHeapReserve = 0;
Optional32->SizeOfHeapCommit = 0;
Optional32->Subsystem = (USHORT) Type;
//
// Strip zero padding at the end of the .reloc section
//
if (NeedStripZeroPendingReloc) {
StripZeroPendingReloc (FileBuffer, &FileLength, DosHdr, PeHdr);
}
} else if (PeHdr->PeHeader32.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
//
// PE32+ image
//
Optional64 = (EFI_IMAGE_OPTIONAL_HEADER64 *)&PeHdr->PeHeader64.OptionalHeader;
Optional64->MajorLinkerVersion = 0;
Optional64->MinorLinkerVersion = 0;
Optional64->MajorOperatingSystemVersion = 0;
Optional64->MinorOperatingSystemVersion = 0;
Optional64->MajorImageVersion = 0;
Optional64->MinorImageVersion = 0;
Optional64->MajorSubsystemVersion = 0;
Optional64->MinorSubsystemVersion = 0;
Optional64->Win32VersionValue = 0;
Optional64->CheckSum = 0;
Optional64->SizeOfStackReserve = 0;
Optional64->SizeOfStackCommit = 0;
Optional64->SizeOfHeapReserve = 0;
Optional64->SizeOfHeapCommit = 0;
Optional64->Subsystem = (USHORT) Type;
//
// Strip zero padding at the end of the .reloc section
//
if (NeedStripZeroPendingReloc) {
StripZeroPendingReloc (FileBuffer, &FileLength, DosHdr, PeHdr);
}
} else {
Error (NULL, 0, 0, argv[2], "Unsupported PE image");
fclose (fpIn);
fclose (fpOut);
return STATUS_ERROR;
}
//
// Zero PDATA section for smaller binary size after compression
//
if (NeedClearExceptionTable) {
ZeroExceptionTable (FileBuffer, DosHdr, PeHdr);
}
FWriteFile (fpOut, FileBuffer, FileLength);
//
// Done
//
fclose (fpIn);
fclose (fpOut);
return STATUS_SUCCESS;
}

View File

@@ -0,0 +1,467 @@
/*++
Copyright (c) 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenAprioriFile.c
Abstract:
Given an input file containing a list of GUIDs (or Guided file names),
convert the file to an Apriori file consumable by the dispatcher.
--*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "EfiCommon.h"
#include "ParseInf.h"
#include "CommonLib.h" // for compare guid
#include "EfiUtilityMsgs.h"
#define MAX_LINE_LEN 200
#define MAX_PATH 200
//
// typedef unsigned int STATUS;
// #define STATUS_SUCCESS 0
// #define STATUS_WARNING 1
// #define STATUS_ERROR 2
//
#define UTILITY_NAME "GenAprioriFile"
//
// Here's all our globals.
//
static struct {
FILE *BinFptr; // output dependencies to this file
INT8 *AprioriFileName;
INT8 *OutputFileName;
BOOLEAN Intelligent;
BOOLEAN Verbose;
BOOLEAN NullTerminate;
} mGlobals;
static
STATUS
ProcessArgs (
int Argc,
char *Argv[]
);
static
BOOLEAN
IsCommentLine (
INT8 *Line
);
static
void
Usage (
VOID
);
int
main (
int Argc,
char *Argv[]
)
/*++
Routine Description:
Call the routine to parse the command-line options, then process the
Apriori list file and generate the GUID file.
Arguments:
Standard C main() argc and argv.
Returns:
0 if successful
nonzero otherwise
--*/
// GC_TODO: Argc - add argument and description to function comment
// GC_TODO: ] - add argument and description to function comment
{
STATUS Status;
FILE *AprioriFptr;
FILE *BinFptr;
INT8 Line[MAX_LINE_LEN];
EFI_GUID Guid;
EFI_GUID GuidIn;
EFI_GUID ZeroGuid;
UINT32 LineCounter;
//
// Initialize the error printing routines
//
SetUtilityName (UTILITY_NAME);
//
// Clear our globals
//
memset ((char *) &mGlobals, 0, sizeof (mGlobals));
memset ((char *) &ZeroGuid, 0, sizeof (ZeroGuid));
AprioriFptr = NULL;
BinFptr = NULL;
//
// Process the command-line arguments
//
Status = ProcessArgs (Argc, Argv);
if (Status != STATUS_SUCCESS) {
return Status;
}
//
// If arguments were ok, then open the Apriori file and process it.
//
if ((AprioriFptr = fopen (mGlobals.AprioriFileName, "r")) == NULL) {
Error (NULL, 0, 0, mGlobals.AprioriFileName, "failed to open file for reading");
goto FinishUp;
}
//
// If -i intelligent option specified, then attempt to read and
// existing output file and see if we'd be creating an identical file.
//
if (mGlobals.Intelligent) {
if ((BinFptr = fopen (mGlobals.OutputFileName, "rb")) == NULL) {
if (mGlobals.Verbose) {
DebugMsg (NULL, 0, 0, "Creating new apriori file -- no existing file", NULL);
}
goto CreateFile;
}
//
// Read lines from the input file until done. Convert each to a guid, then
// read a guid from the input file and compare them.
//
while (fgets (Line, sizeof (Line), AprioriFptr) != NULL) {
if (IsCommentLine (Line)) {
continue;
}
//
// Convert to a guid
//
if (StringToGuid (Line, &Guid) != EFI_SUCCESS) {
if (mGlobals.Verbose) {
DebugMsg (NULL, 0, 0, "failed to read GUID from input text file -- creating new file", NULL);
}
goto CreateFile;
}
//
// Read guid from input file, then compare
//
if (fread (&GuidIn, sizeof (GuidIn), 1, BinFptr) != 1) {
if (mGlobals.Verbose) {
DebugMsg (NULL, 0, 0, "failed to read GUID from input binary file -- creating new file", NULL);
}
goto CreateFile;
}
if (CompareGuid (&Guid, &GuidIn) != 0) {
if (mGlobals.Verbose) {
DebugMsg (NULL, 0, 0, "GUID comparison failed -- creating new file", NULL);
}
goto CreateFile;
}
}
//
// May be one more NULL guid in the binary file
//
if (mGlobals.NullTerminate) {
if (fread (&GuidIn, sizeof (GuidIn), 1, BinFptr) != 1) {
if (mGlobals.Verbose) {
DebugMsg (NULL, 0, 0, "failed to read NULL GUID from input binary file -- creating new file", NULL);
}
goto CreateFile;
}
if (CompareGuid (&GuidIn, &ZeroGuid) != 0) {
if (mGlobals.Verbose) {
DebugMsg (NULL, 0, 0, "NULL GUID comparison failed -- creating new file", NULL);
}
goto CreateFile;
}
}
//
// Make sure we're at the end of both files.
//
if ((fgets (Line, sizeof (Line), AprioriFptr) != NULL) || (fread (&GuidIn, 1, 1, BinFptr) != 0)) {
if (mGlobals.Verbose) {
DebugMsg (NULL, 0, 0, "file sizes different, -i test failed -- creating new file", NULL);
}
goto CreateFile;
}
if (mGlobals.Verbose) {
DebugMsg (NULL, 0, 0, "existing file would be unchanged -- keeping existing apriori file", NULL);
}
goto FinishUp;
}
CreateFile:
//
// Rewind the Apriori file in case -i was specified. Also
// try to close the output file for the case where we prescanned
// it (again, because of -i).
//
rewind (AprioriFptr);
if (BinFptr != NULL) {
fclose (BinFptr);
}
//
// Open the output file
//
if ((BinFptr = fopen (mGlobals.OutputFileName, "wb")) == NULL) {
Error (NULL, 0, 0, mGlobals.OutputFileName, "could not open input file");
goto FinishUp;
}
//
// Read lines until we're done
//
LineCounter = 0;
while (fgets (Line, sizeof (Line), AprioriFptr) != NULL) {
LineCounter++;
if (IsCommentLine (Line)) {
continue;
}
//
// Convert to a GUID
//
if (StringToGuid (Line, &Guid) != EFI_SUCCESS) {
Error (mGlobals.AprioriFileName, LineCounter, 0, "failed to convert GUID", NULL);
goto FinishUp;
}
//
// Write the guid to the output file
//
if (fwrite (&Guid, sizeof (Guid), 1, BinFptr) != 1) {
Error (NULL, 0, 0, mGlobals.OutputFileName, "failed to write GUID to output file");
goto FinishUp;
}
}
//
// Write a null guid out to terminate the list
//
if (mGlobals.NullTerminate) {
memset ((void *) &Guid, 0, sizeof (Guid));
if (fwrite (&Guid, sizeof (Guid), 1, BinFptr) != 1) {
Error (NULL, 0, 0, mGlobals.OutputFileName, "failed to write NULL termination GUID to output file");
}
}
FinishUp:
if (AprioriFptr != NULL) {
fclose (AprioriFptr);
}
if (BinFptr != NULL) {
fclose (BinFptr);
}
return GetUtilityStatus ();
}
static
BOOLEAN
IsCommentLine (
INT8 *Line
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
Line - GC_TODO: add argument description
Returns:
GC_TODO: add return values
--*/
{
for (; isspace (*Line) && *Line; Line++)
;
//
// Allow # or // comments
//
if ((*Line == '#') || ((*Line == '/') && (*(Line + 1) == '/')) || (*Line == '\n') || (*Line == 0)) {
return TRUE;
}
return FALSE;
}
//
// Process the command-line arguments
//
static
STATUS
ProcessArgs (
int Argc,
char *Argv[]
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
Argc - GC_TODO: add argument description
] - GC_TODO: add argument description
Returns:
GC_TODO: add return values
--*/
{
//
// Skip program name
//
Argc--;
Argv++;
//
// Process until no more args
//
while (Argc) {
//
// -f AprioriFile
//
if (_stricmp (Argv[0], "-f") == 0) {
//
// check for one more arg
//
if (Argc > 1) {
mGlobals.AprioriFileName = Argv[1];
} else {
Error (NULL, 0, 0, NULL, "missing filename with %s", Argv[0]);
Usage ();
return STATUS_ERROR;
}
Argc--;
Argv++;
} else if (_stricmp (Argv[0], "-i") == 0) {
//
// intelligent creation of output file. That is to say, if
// there's already a file there, and it's the same as what
// we'd create, then don't re-create. This is to support
// incremental builds (that is to say, running nmake a second time
// does nothing).
//
mGlobals.Intelligent = TRUE;
} else if (_stricmp (Argv[0], "-v") == 0) {
mGlobals.Verbose = TRUE;
} else if (_stricmp (Argv[0], "-null") == 0) {
mGlobals.NullTerminate = TRUE;
} else if (_stricmp (Argv[0], "-o") == 0) {
//
// -o OutputFileName
// check for one more arg
//
if (Argc > 1) {
mGlobals.OutputFileName = Argv[1];
} else {
Error (NULL, 0, 0, NULL, "missing filename argument with %s", Argv[0]);
Usage ();
return STATUS_ERROR;
}
Argc--;
Argv++;
} else if ((_stricmp (Argv[0], "-h") == 0) || (strcmp (Argv[0], "-?") == 0)) {
Usage ();
return STATUS_ERROR;
} else {
Error (NULL, 0, 0, Argv[0], "unrecognized option");
Usage ();
return STATUS_ERROR;
}
Argc--;
Argv++;
}
//
// Had to specify the apriori input file and output file names
//
if (mGlobals.AprioriFileName == NULL) {
Error (NULL, 0, 0, "must specify -f AprioriFile", NULL);
Usage ();
return STATUS_ERROR;
}
if (mGlobals.OutputFileName == NULL) {
Error (NULL, 0, 0, "must specify -o OutputFile", NULL);
Usage ();
return STATUS_ERROR;
}
return STATUS_SUCCESS;
}
static
void
Usage (
VOID
)
/*++
Routine Description:
Print usage information for this utility.
Arguments:
None.
Returns:
Nothing.
--*/
{
int Index;
static const char *Str[] = {
UTILITY_NAME " -- create an Apriori file consumable by the DXE dispatcher",
" Usage: "UTILITY_NAME " [Options]",
" Options include:",
" -h or -? for this help information",
" -f AprioriFile parse the GUID'ed files in AprioriFile (required)",
" -o OutputFile write output to OutputFile (required)",
" -i for intelligent re-creation of OutputFile",
" -null to terminate the output file with a NULL GUID",
" -v verbose option",
"",
NULL
};
for (Index = 0; Str[Index] != NULL; Index++) {
fprintf (stdout, "%s\n", Str[Index]);
}
}

View File

@@ -0,0 +1,78 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# makefile
#
# Abstract:
#
# makefile for building the GenAproriFile utility.
#
# Revision History
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Target specific information
#
TARGET_NAME = GenAprioriFile
TARGET_SRC_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\GenAprioriFile.exe
LIBS = $(EDK_TOOLS_OUTPUT)\Common.lib
#
# Build targets
#
all: $(TARGET_EXE)
OBJECTS = $(EDK_TOOLS_OUTPUT)\GenAprioriFile.obj
#
# Compile each source file
#
$(EDK_TOOLS_OUTPUT)\GenAprioriFile.obj : $(TARGET_SRC_DIR)\GenAprioriFile.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(TARGET_SRC_DIR)\GenAprioriFile.c /Fo$@
#
# Add Binary Build description for this tools.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(OBJECTS) $(LIBS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Lib.* del /q $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Lib.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del /q $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,58 @@
#include "fat.h"
#include <stdio.h>
INTN
GetDrvNumOffset (
IN VOID *BootSector
)
{
FAT_BPB_STRUCT *FatBpb;
UINTN RootDirSectors;
UINTN FATSz;
UINTN TotSec;
UINTN DataSec;
UINTN CountOfClusters;
FatBpb = (FAT_BPB_STRUCT *) BootSector;
//
// Check FAT type algorithm from FAT spec
//
RootDirSectors = ((FatBpb->Fat12_16.BPB_RootEntCnt * sizeof(FAT_DIRECTORY_ENTRY)) +
(FatBpb->Fat12_16.BPB_BytsPerSec - 1)) / FatBpb->Fat12_16.BPB_BytsPerSec;
if (FatBpb->Fat12_16.BPB_FATSz16 != 0) {
FATSz = FatBpb->Fat12_16.BPB_FATSz16;
} else {
FATSz = FatBpb->Fat32.BPB_FATSz32;
}
if (FATSz == 0) {
fprintf (stderr, "ERROR: FAT: BPB_FATSz16, BPB_FATSz32 - 0, expected - Non-Zero\n");
return -1;
}
if (FatBpb->Fat12_16.BPB_TotSec16 != 0) {
TotSec = FatBpb->Fat12_16.BPB_TotSec16;
} else {
TotSec = FatBpb->Fat12_16.BPB_TotSec32;
}
if (TotSec == 0) {
fprintf (stderr, "ERROR: FAT: BPB_TotSec16, BPB_TotSec32 - 0, expected - Non-Zero\n");
return -1;
}
DataSec = TotSec - (
FatBpb->Fat12_16.BPB_RsvdSecCnt +
FatBpb->Fat12_16.BPB_NumFATs * FATSz +
RootDirSectors
);
CountOfClusters = DataSec / FatBpb->Fat12_16.BPB_SecPerClus;
if (CountOfClusters < FAT_MAX_FAT16_CLUSTER) {
return (INTN) ((UINTN) &FatBpb->Fat12_16.BS_DrvNum - (UINTN) FatBpb);
} else {
return (INTN) ((UINTN) &FatBpb->Fat32.BS_DrvNum - (UINTN) FatBpb);
}
}

View File

@@ -0,0 +1,158 @@
/*++
Copyright 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
fat.h
Abstract:
Revision History
--*/
#ifndef _FAT_BPB_H_
#define _FAT_BPB_H_
#include "Tiano.h"
#pragma pack(1)
typedef struct {
//
// Fat common field
//
UINT8 BS_jmpBoot[3];
CHAR8 BS_OEMName[8];
UINT16 BPB_BytsPerSec;
UINT8 BPB_SecPerClus;
UINT16 BPB_RsvdSecCnt;
UINT8 BPB_NumFATs;
UINT16 BPB_RootEntCnt;
UINT16 BPB_TotSec16;
UINT8 BPB_Media;
UINT16 BPB_FATSz16;
UINT16 BPB_SecPerTrk;
UINT16 BPB_NumHeads;
UINT32 BPB_HiddSec;
UINT32 BPB_TotSec32;
//
// Fat12/16 specific field
//
UINT8 BS_DrvNum;
UINT8 BS_Reserved1;
UINT8 BS_BootSig;
UINT32 BS_VolID;
CHAR8 BS_VolLab[11];
CHAR8 BS_FilSysType[8];
//
// Boot Code and Data
//
UINT8 Reserved[448];
//
// Fat common signature - 0xAA55
//
UINT16 Signature;
} FAT12_16_BPB_STRUCT;
typedef struct {
//
// Fat common field
//
UINT8 BS_jmpBoot[3];
CHAR8 BS_OEMName[8];
UINT16 BPB_BytsPerSec;
UINT8 BPB_SecPerClus;
UINT16 BPB_RsvdSecCnt;
UINT8 BPB_NumFATs;
UINT16 BPB_RootEntCnt;
UINT16 BPB_TotSec16;
UINT8 BPB_Media;
UINT16 BPB_FATSz16;
UINT16 BPB_SecPerTrk;
UINT16 BPB_NumHeads;
UINT32 BPB_HiddSec;
UINT32 BPB_TotSec32;
//
// Fat32 specific field
//
UINT32 BPB_FATSz32;
UINT16 BPB_ExtFlags;
UINT16 BPB_FSVer;
UINT32 BPB_RootClus;
UINT16 BPB_FSInfo;
UINT16 BPB_BkBootSec;
UINT8 BPB_Reserved[12];
UINT8 BS_DrvNum;
UINT8 BS_Reserved1;
UINT8 BS_BootSig;
UINT32 BS_VolID;
CHAR8 BS_VolLab[11];
CHAR8 BS_FilSysType[8];
//
// Boot Code and Data
//
UINT8 Reserved[420];
//
// Fat common signature - 0xAA55
//
UINT16 Signature;
} FAT32_BPB_STRUCT;
typedef union {
FAT12_16_BPB_STRUCT Fat12_16;
FAT32_BPB_STRUCT Fat32;
} FAT_BPB_STRUCT;
typedef enum {
FatTypeUnknown,
FatTypeFat12,
FatTypeFat16,
FatTypeFat32,
FatTypeMax
} FAT_TYPE;
typedef struct {
CHAR8 DIR_Name[11];
UINT8 DIR_Attr;
UINT8 DIR_NTRes;
UINT8 DIR_CrtTimeTenth;
UINT16 DIR_CrtTime;
UINT16 DIR_CrtDate;
UINT16 DIR_LstAccDate;
UINT16 DIR_FstClusHI;
UINT16 DIR_WrtTime;
UINT16 DIR_WrtDate;
UINT16 DIR_FstClusLO;
UINT32 DIR_FileSize;
} FAT_DIRECTORY_ENTRY;
#pragma pack()
#define FAT_MAX_FAT12_CLUSTER 0xFF5
#define FAT_MAX_FAT16_CLUSTER 0xFFF5
#define FAT_BS_SIGNATURE 0xAA55
#define FAT_BS_BOOTSIG 0x29
#define FAT_BS_JMP1 0xEB
#define FAT_BS_JMP2 0xE9
#define FAT_FILSYSTYPE "FAT "
#define FAT12_FILSYSTYPE "FAT12 "
#define FAT16_FILSYSTYPE "FAT16 "
#define FAT32_FILSYSTYPE "FAT32 "
#endif

View File

@@ -0,0 +1,652 @@
/*++
Copyright 2006 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
genbootsector.c
Abstract:
Reading/writing MBR/DBR.
NOTE:
If we write MBR to disk, we just update the MBR code and the partition table wouldn't be over written.
If we process DBR, we will patch MBR to set first partition active if no active partition exists.
--*/
#include <windows.h>
#include <stdio.h>
#include <string.h>
#define MAX_DRIVE 26
#define PARTITION_TABLE_OFFSET 0x1BE
#define SIZE_OF_PARTITION_ENTRY 0x10
#define PARTITION_ENTRY_STARTLBA_OFFSET 8
#define PARTITION_ENTRY_NUM 4
INT
GetDrvNumOffset (
IN VOID *BootSector
);
typedef enum {
PatchTypeUnknown,
PatchTypeFloppy,
PatchTypeIde,
PatchTypeUsb,
} PATCH_TYPE;
typedef enum {
ErrorSuccess,
ErrorFileCreate,
ErrorFileReadWrite,
ErrorNoMbr,
ErrorFatType
} ERROR_STATUS;
CHAR *ErrorStatusDesc[] = {
"Success",
"Failed to create files",
"Failed to read/write files",
"No MBR exists",
"Failed to detect Fat type"
};
typedef struct _DRIVE_TYPE_DESC {
UINT Type;
CHAR *Description;
} DRIVE_TYPE_DESC;
#define DRIVE_TYPE_ITEM(x) {x, #x}
DRIVE_TYPE_DESC DriveTypeDesc[] = {
DRIVE_TYPE_ITEM (DRIVE_UNKNOWN),
DRIVE_TYPE_ITEM (DRIVE_NO_ROOT_DIR),
DRIVE_TYPE_ITEM (DRIVE_REMOVABLE),
DRIVE_TYPE_ITEM (DRIVE_FIXED),
DRIVE_TYPE_ITEM (DRIVE_REMOTE),
DRIVE_TYPE_ITEM (DRIVE_CDROM),
DRIVE_TYPE_ITEM (DRIVE_RAMDISK),
(UINT) -1, NULL
};
typedef struct _DRIVE_INFO {
CHAR VolumeLetter;
DRIVE_TYPE_DESC *DriveType;
UINT DiskNumber;
} DRIVE_INFO;
#define BOOT_SECTOR_LBA_OFFSET 0x1FA
#define IsLetter(x) (((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z'))
BOOL
GetDriveInfo (
CHAR VolumeLetter,
DRIVE_INFO *DriveInfo
)
/*++
Routine Description:
Get drive information including disk number and drive type,
where disknumber is useful for reading/writing disk raw data.
NOTE: Floppy disk doesn't have disk number but it doesn't matter because
we can reading/writing floppy disk without disk number.
Arguments:
VolumeLetter : volume letter, e.g.: C for C:, A for A:
DriveInfo : pointer to DRIVE_INFO structure receiving drive information.
Return:
TRUE : successful
FALSE : failed
--*/
{
HANDLE VolumeHandle;
STORAGE_DEVICE_NUMBER StorageDeviceNumber;
DWORD BytesReturned;
BOOL Success;
UINT DriveType;
UINT Index;
CHAR RootPath[] = "X:\\"; // "X:\" -> for GetDriveType
CHAR VolumeAccessPath[] = "\\\\.\\X:"; // "\\.\X:" -> to open the volume
RootPath[0] = VolumeAccessPath[4] = VolumeLetter;
DriveType = GetDriveType(RootPath);
if (DriveType != DRIVE_REMOVABLE && DriveType != DRIVE_FIXED) {
return FALSE;
}
DriveInfo->VolumeLetter = VolumeLetter;
VolumeHandle = CreateFile (
VolumeAccessPath,
0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL
);
if (VolumeHandle == INVALID_HANDLE_VALUE) {
fprintf (
stderr,
"ERROR: CreateFile failed: Volume = %s, LastError = 0x%x\n",
VolumeAccessPath,
GetLastError ()
);
return FALSE;
}
//
// Get Disk Number. It should fail when operating on floppy. That's ok
// because Disk Number is only needed when operating on Hard or USB disk.
//
// To direct write to disk:
// for USB and HD: use path = \\.\PHYSICALDRIVEx, where x is Disk Number
// for floppy: use path = \\.\X:, where X can be A or B
//
Success = DeviceIoControl(
VolumeHandle,
IOCTL_STORAGE_GET_DEVICE_NUMBER,
NULL,
0,
&StorageDeviceNumber,
sizeof(StorageDeviceNumber),
&BytesReturned,
NULL
);
//
// DeviceIoControl should fail if Volume is floppy or network drive.
//
if (!Success) {
DriveInfo->DiskNumber = (UINT) -1;
} else if (StorageDeviceNumber.DeviceType != FILE_DEVICE_DISK) {
//
// Only care about the disk.
//
return FALSE;
} else{
DriveInfo->DiskNumber = StorageDeviceNumber.DeviceNumber;
}
CloseHandle(VolumeHandle);
//
// Fill in the type string
//
DriveInfo->DriveType = NULL;
for (Index = 0; DriveTypeDesc[Index].Description != NULL; Index ++) {
if (DriveType == DriveTypeDesc[Index].Type) {
DriveInfo->DriveType = &DriveTypeDesc[Index];
break;
}
}
if (DriveInfo->DriveType == NULL) {
//
// Should have a type.
//
fprintf (stderr, "ERROR: fetal error!!!\n");
return FALSE;
}
return TRUE;
}
VOID
ListDrive (
VOID
)
/*++
Routine Description:
List every drive in current system and their information.
--*/
{
UINT Index;
DRIVE_INFO DriveInfo;
UINT Mask = GetLogicalDrives();
for (Index = 0; Index < MAX_DRIVE; Index++) {
if (((Mask >> Index) & 0x1) == 1) {
if (GetDriveInfo ('A' + (CHAR) Index, &DriveInfo)) {
if (Index < 2) {
// Floppy will occupy 'A' and 'B'
fprintf (
stdout,
"%c: - Type: %s\n",
DriveInfo.VolumeLetter,
DriveInfo.DriveType->Description
);
}
else {
fprintf (
stdout,
"%c: - DiskNum: %d, Type: %s\n",
DriveInfo.VolumeLetter,
DriveInfo.DiskNumber,
DriveInfo.DriveType->Description
);
}
}
}
}
}
INT
GetBootSectorOffset (
HANDLE DiskHandle,
BOOL WriteToDisk,
PATCH_TYPE PatchType
)
/*++
Description:
Get the offset of boot sector.
For non-MBR disk, offset is just 0
for disk with MBR, offset needs to be caculated by parsing MBR
NOTE: if no one is active, we will patch MBR to select first partition as active.
Arguments:
DiskHandle : HANDLE of disk
WriteToDisk : TRUE indicates writing
PatchType : PatchTypeFloppy, PatchTypeIde, PatchTypeUsb
Return:
-1 : failed
o.w. : Offset to boot sector
--*/
{
BYTE DiskPartition[0x200];
DWORD BytesReturn;
DWORD DbrOffset;
DWORD Index;
BOOL HasMbr;
DbrOffset = 0;
HasMbr = FALSE;
SetFilePointer(DiskHandle, 0, NULL, FILE_BEGIN);
if (!ReadFile (DiskHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
return -1;
}
//
// Check Signature, Jmp, and Boot Indicator.
// if all pass, we assume MBR found.
//
// Check Signature: 55AA
if ((DiskPartition[0x1FE] == 0x55) && (DiskPartition[0x1FF] == 0xAA)) {
// Check Jmp: (EB ?? 90) or (E9 ?? ??)
if (((DiskPartition[0] != 0xEB) || (DiskPartition[2] != 0x90)) &&
(DiskPartition[0] != 0xE9)) {
// Check Boot Indicator: 0x00 or 0x80
// Boot Indicator is the first byte of Partition Entry
HasMbr = TRUE;
for (Index = 0; Index < PARTITION_ENTRY_NUM; ++Index) {
if ((DiskPartition[PARTITION_TABLE_OFFSET + Index * SIZE_OF_PARTITION_ENTRY] & 0x7F) != 0) {
HasMbr = FALSE;
break;
}
}
}
}
if (HasMbr) {
//
// Skip MBR
//
for (Index = 0; Index < PARTITION_ENTRY_NUM; Index++) {
//
// Found Boot Indicator.
//
if (DiskPartition[PARTITION_TABLE_OFFSET + (Index * SIZE_OF_PARTITION_ENTRY)] == 0x80) {
DbrOffset = *(DWORD *)&DiskPartition[PARTITION_TABLE_OFFSET + (Index * SIZE_OF_PARTITION_ENTRY) + PARTITION_ENTRY_STARTLBA_OFFSET];
break;
}
}
//
// If no boot indicator, we manually select 1st partition, and patch MBR.
//
if (Index == PARTITION_ENTRY_NUM) {
DbrOffset = *(DWORD *)&DiskPartition[PARTITION_TABLE_OFFSET + PARTITION_ENTRY_STARTLBA_OFFSET];
if (WriteToDisk && (PatchType == PatchTypeUsb)) {
SetFilePointer(DiskHandle, 0, NULL, FILE_BEGIN);
DiskPartition[PARTITION_TABLE_OFFSET] = 0x80;
WriteFile (DiskHandle, DiskPartition, 0x200, &BytesReturn, NULL);
}
}
}
return DbrOffset;
}
ERROR_STATUS
ProcessBsOrMbr (
CHAR *DiskName,
CHAR *FileName,
BOOL WriteToDisk,
PATCH_TYPE PatchType,
BOOL ProcessMbr
)
/*++
Routine Description:
Writing or reading boot sector or MBR according to the argument.
Arguments:
DiskName : Win32 API recognized string name of disk
FileName : file name
WriteToDisk : TRUE is to write content of file to disk, otherwise, reading content of disk to file
PatchType : PatchTypeFloppy, PatchTypeIde, PatchTypeUsb
ProcessMbr : TRUE is to process MBR, otherwise, processing boot sector
Return:
ErrorSuccess
ErrorFileCreate
ErrorFileReadWrite
ErrorNoMbr
ErrorFatType
--*/
{
BYTE DiskPartition[0x200];
BYTE DiskPartitionBackup[0x200];
HANDLE DiskHandle;
HANDLE FileHandle;
DWORD BytesReturn;
DWORD DbrOffset;
INT DrvNumOffset;
DiskHandle = CreateFile (
DiskName,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (DiskHandle == INVALID_HANDLE_VALUE) {
return ErrorFileCreate;
}
FileHandle = CreateFile (
FileName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (FileHandle == INVALID_HANDLE_VALUE) {
return ErrorFileCreate;
}
DbrOffset = 0;
//
// Skip potential MBR for Ide & USB disk
//
if ((PatchType == PatchTypeIde) || (PatchType == PatchTypeUsb)) {
//
// Even user just wants to process MBR, we get offset of boot sector here to validate the disk
// if disk have MBR, DbrOffset should be greater than 0
//
DbrOffset = GetBootSectorOffset (DiskHandle, WriteToDisk, PatchType);
if (!ProcessMbr) {
//
// 1. Process boot sector, set file pointer to the beginning of boot sector
//
SetFilePointer (DiskHandle, DbrOffset * 0x200, NULL, FILE_BEGIN);
} else if(DbrOffset == 0) {
//
// If user want to process Mbr, but no Mbr exists, simply return FALSE
//
return ErrorNoMbr;
} else {
//
// 2. Process MBR, set file pointer to 0
//
SetFilePointer (DiskHandle, 0, NULL, FILE_BEGIN);
}
}
//
// [File Pointer is pointed to beginning of Mbr or Dbr]
//
if (WriteToDisk) {
//
// Write
//
if (!ReadFile (FileHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
return ErrorFileReadWrite;
}
if (ProcessMbr) {
//
// Use original partition table
//
if (!ReadFile (DiskHandle, DiskPartitionBackup, 0x200, &BytesReturn, NULL)) {
return ErrorFileReadWrite;
}
memcpy (DiskPartition + 0x1BE, DiskPartitionBackup + 0x1BE, 0x40);
SetFilePointer (DiskHandle, 0, NULL, FILE_BEGIN);
}
if (!WriteFile (DiskHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
return ErrorFileReadWrite;
}
} else {
//
// Read
//
if (!ReadFile (DiskHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
return ErrorFileReadWrite;
}
if (PatchType == PatchTypeUsb) {
// Manually set BS_DrvNum to 0x80 as window's format.exe has a bug which will clear this field discarding USB disk's MBR.
// offset of BS_DrvNum is 0x24 for FAT12/16
// 0x40 for FAT32
//
DrvNumOffset = GetDrvNumOffset (DiskPartition);
if (DrvNumOffset == -1) {
return ErrorFatType;
}
//
// Some legacy BIOS require 0x80 discarding MBR.
// Question left here: is it needed to check Mbr before set 0x80?
//
DiskPartition[DrvNumOffset] = ((DbrOffset > 0) ? 0x80 : 0);
}
if (PatchType == PatchTypeIde) {
//
// Patch LBAOffsetForBootSector
//
*(DWORD *)&DiskPartition [BOOT_SECTOR_LBA_OFFSET] = DbrOffset;
}
if (!WriteFile (FileHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
return ErrorFileReadWrite;
}
}
CloseHandle (FileHandle);
CloseHandle (DiskHandle);
return ErrorSuccess;
}
VOID
PrintUsage (
CHAR* AppName
)
{
fprintf (
stdout,
"Usage: %s [OPTIONS]...\n"
"Copy file content from/to bootsector.\n"
"\n"
" -l list disks\n"
" -if=FILE specified an input, can be files or disks\n"
" -of=FILE specified an output, can be files or disks\n"
" -mbr process MBR also\n"
" -h print this message\n"
"\n"
"FILE providing a volume plus a colon (X:), indicates a disk\n"
"FILE providing other format, indicates a file\n",
AppName
);
}
INT
main (
INT argc,
CHAR *argv[]
)
{
CHAR *AppName;
INT Index;
BOOL ProcessMbr;
CHAR VolumeLetter;
CHAR *FilePath;
BOOL WriteToDisk;
DRIVE_INFO DriveInfo;
PATCH_TYPE PatchType;
ERROR_STATUS Status;
CHAR FloppyPathTemplate[] = "\\\\.\\%c:";
CHAR DiskPathTemplate[] = "\\\\.\\PHYSICALDRIVE%u";
CHAR DiskPath[MAX_PATH];
AppName = *argv;
argv ++;
argc --;
ProcessMbr = FALSE;
WriteToDisk = TRUE;
FilePath = NULL;
VolumeLetter = 0;
//
// Parse command line
//
for (Index = 0; Index < argc; Index ++) {
if (_stricmp (argv[Index], "-l") == 0) {
ListDrive ();
return 0;
}
else if (_stricmp (argv[Index], "-mbr") == 0) {
ProcessMbr = TRUE;
}
else if ((_strnicmp (argv[Index], "-if=", 4) == 0) ||
(_strnicmp (argv[Index], "-of=", 4) == 0)
) {
if (argv[Index][6] == '\0' && argv[Index][5] == ':' && IsLetter (argv[Index][4])) {
VolumeLetter = argv[Index][4];
if (_strnicmp (argv[Index], "-if=", 4) == 0) {
WriteToDisk = FALSE;
}
}
else {
FilePath = &argv[Index][4];
}
}
else {
PrintUsage (AppName);
return 1;
}
}
//
// Check parameter
//
if (VolumeLetter == 0) {
fprintf (stderr, "ERROR: Volume isn't provided!\n");
PrintUsage (AppName);
return 1;
}
if (FilePath == NULL) {
fprintf (stderr, "ERROR: File isn't pvovided!\n");
PrintUsage (AppName);
return 1;
}
PatchType = PatchTypeUnknown;
if ((VolumeLetter == 'A') || (VolumeLetter == 'a') ||
(VolumeLetter == 'B') || (VolumeLetter == 'b')
) {
//
// Floppy
//
sprintf (DiskPath, FloppyPathTemplate, VolumeLetter);
PatchType = PatchTypeFloppy;
}
else {
//
// Hard/USB disk
//
if (!GetDriveInfo (VolumeLetter, &DriveInfo)) {
fprintf (stderr, "ERROR: GetDriveInfo - 0x%x\n", GetLastError ());
return 1;
}
//
// Shouldn't patch my own hard disk, but can read it.
// very safe then:)
//
if (DriveInfo.DriveType->Type == DRIVE_FIXED && WriteToDisk) {
fprintf (stderr, "ERROR: Write to local harddisk - permission denied!\n");
return 1;
}
sprintf (DiskPath, DiskPathTemplate, DriveInfo.DiskNumber);
if (DriveInfo.DriveType->Type == DRIVE_REMOVABLE) {
PatchType = PatchTypeUsb;
}
else if (DriveInfo.DriveType->Type == DRIVE_FIXED) {
PatchType = PatchTypeIde;
}
}
if (PatchType == PatchTypeUnknown) {
fprintf (stderr, "ERROR: PatchType unknown!\n");
return 1;
}
//
// Process DBR (Patch or Read)
//
Status = ProcessBsOrMbr (DiskPath, FilePath, WriteToDisk, PatchType, ProcessMbr);
if (Status == ErrorSuccess) {
fprintf (
stdout,
"%s %s: successfully!\n",
WriteToDisk ? "Write" : "Read",
ProcessMbr ? "MBR" : "DBR"
);
return 0;
} else {
fprintf (
stderr,
"%s: %s %s: failed - %s (LastError: 0x%x)!\n",
(Status == ErrorNoMbr) ? "WARNING" : "ERROR",
WriteToDisk ? "Write" : "Read",
ProcessMbr ? "MBR" : "DBR",
ErrorStatusDesc[Status],
GetLastError ()
);
return 1;
}
}

View File

@@ -0,0 +1,99 @@
#/*++
#
# Copyright (c) 2006 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the GenBootsector utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=GenBootsector
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\GenBootsector.c"
TARGET_EXE_INCLUDE =
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\GetDrvNumOffset.obj: $(TARGET_SOURCE_DIR)\GenBootsector.c $(TARGET_SOURCE_DIR)\fat.h
$(CC) $(C_FLAGS) $(INC) $(TARGET_SOURCE_DIR)\GetDrvNumOffset.c /Fo$(EDK_TOOLS_OUTPUT)\GetDrvNumOffset.obj
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(EDK_TOOLS_OUTPUT)\GetDrvNumOffset.obj
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) user32.lib advapi32.lib /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(EDK_TOOLS_OUTPUT)\GetDrvNumOffset.obj
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\GetDrvNumOffset.* del $(EDK_TOOLS_OUTPUT)\GetDrvNumOffset.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,299 @@
/*++
Copyright (c) 2004 - 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenCRC32Section.c
Abstract:
This file contains functions required to generate a Firmware File System
file. The code is compliant with the Tiano C Coding standards.
--*/
#include "TianoCommon.h"
#include "EfiFirmwareFileSystem.h"
#include "EfiFirmwareVolumeHeader.h"
#include "ParseInf.h"
#include "crc32.h"
#include "EfiUtilityMsgs.h"
#include "GenCRC32Section.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "CommonLib.h"
#include EFI_PROTOCOL_DEFINITION (GuidedSectionExtraction)
#define TOOLVERSION "0.2"
#define UTILITY_NAME "GenCrc32Section"
EFI_GUID gEfiCrc32SectionGuid = EFI_CRC32_GUIDED_SECTION_EXTRACTION_PROTOCOL_GUID;
EFI_STATUS
SignSectionWithCrc32 (
IN OUT UINT8 *FileBuffer,
IN OUT UINT32 *BufferSize,
IN UINT32 DataSize
)
/*++
Routine Description:
Signs the section with CRC32 and add GUIDed section header for the
signed data. data stays in same location (overwrites source data).
Arguments:
FileBuffer - Buffer containing data to sign
BufferSize - On input, the size of FileBuffer. On output, the size of
actual section data (including added section header).
DataSize - Length of data to Sign
Key - Key to use when signing. Currently only CRC32 is supported.
Returns:
EFI_SUCCESS - Successful
EFI_OUT_OF_RESOURCES - Not enough resource to complete the operation.
--*/
{
UINT32 Crc32Checksum;
EFI_STATUS Status;
UINT32 TotalSize;
CRC32_SECTION_HEADER Crc32Header;
UINT8 *SwapBuffer;
Crc32Checksum = 0;
SwapBuffer = NULL;
if (DataSize == 0) {
*BufferSize = 0;
return EFI_SUCCESS;
}
Status = CalculateCrc32 (FileBuffer, DataSize, &Crc32Checksum);
if (EFI_ERROR (Status)) {
return Status;
}
TotalSize = DataSize + CRC32_SECTION_HEADER_SIZE;
Crc32Header.GuidSectionHeader.CommonHeader.Type = EFI_SECTION_GUID_DEFINED;
Crc32Header.GuidSectionHeader.CommonHeader.Size[0] = (UINT8) (TotalSize & 0xff);
Crc32Header.GuidSectionHeader.CommonHeader.Size[1] = (UINT8) ((TotalSize & 0xff00) >> 8);
Crc32Header.GuidSectionHeader.CommonHeader.Size[2] = (UINT8) ((TotalSize & 0xff0000) >> 16);
memcpy (&(Crc32Header.GuidSectionHeader.SectionDefinitionGuid), &gEfiCrc32SectionGuid, sizeof (EFI_GUID));
Crc32Header.GuidSectionHeader.Attributes = EFI_GUIDED_SECTION_AUTH_STATUS_VALID;
Crc32Header.GuidSectionHeader.DataOffset = CRC32_SECTION_HEADER_SIZE;
Crc32Header.CRC32Checksum = Crc32Checksum;
SwapBuffer = (UINT8 *) malloc (DataSize);
if (SwapBuffer == NULL) {
return EFI_OUT_OF_RESOURCES;
}
memcpy (SwapBuffer, FileBuffer, DataSize);
memcpy (FileBuffer, &Crc32Header, CRC32_SECTION_HEADER_SIZE);
memcpy (FileBuffer + CRC32_SECTION_HEADER_SIZE, SwapBuffer, DataSize);
//
// Make sure section ends on a DWORD boundary
//
while ((TotalSize & 0x03) != 0) {
FileBuffer[TotalSize] = 0;
TotalSize++;
}
*BufferSize = TotalSize;
if (SwapBuffer != NULL) {
free (SwapBuffer);
}
return EFI_SUCCESS;
}
VOID
PrintUsage (
VOID
)
{
printf ("Usage:\n");
printf (UTILITY_NAME " -i \"inputfile1\" \"inputfile2\" -o \"outputfile\" \n");
printf (" -i \"inputfile\":\n ");
printf (" specifies the input files that would be signed to CRC32 Guided section.\n");
printf (" -o \"outputfile\":\n");
printf (" specifies the output file that is a CRC32 Guided section.\n");
}
INT32
ReadFilesContentsIntoBuffer (
IN CHAR8 *argv[],
IN INT32 Start,
IN OUT UINT8 **FileBuffer,
IN OUT UINT32 *BufferSize,
OUT UINT32 *ContentSize,
IN INT32 MaximumArguments
)
{
INT32 Index;
CHAR8 *FileName;
FILE *InputFile;
UINT8 Temp;
UINT32 Size;
FileName = NULL;
InputFile = NULL;
Size = 0;
Index = 0;
//
// read all input files into one file buffer
//
while (argv[Start + Index][0] != '-') {
FileName = argv[Start + Index];
InputFile = fopen (FileName, "rb");
if (InputFile == NULL) {
Error (NULL, 0, 0, FileName, "failed to open input binary file");
return -1;
}
fread (&Temp, sizeof (UINT8), 1, InputFile);
while (!feof (InputFile)) {
(*FileBuffer)[Size++] = Temp;
fread (&Temp, sizeof (UINT8), 1, InputFile);
}
fclose (InputFile);
InputFile = NULL;
//
// Make sure section ends on a DWORD boundary
//
while ((Size & 0x03) != 0) {
(*FileBuffer)[Size] = 0;
Size++;
}
Index++;
if (Index == MaximumArguments) {
break;
}
}
*ContentSize = Size;
return Index;
}
INT32
main (
INT32 argc,
CHAR8 *argv[]
)
{
FILE *OutputFile;
UINT8 *FileBuffer;
UINT32 BufferSize;
EFI_STATUS Status;
UINT32 ContentSize;
CHAR8 *OutputFileName;
INT32 ReturnValue;
INT32 Index;
OutputFile = NULL;
FileBuffer = NULL;
ContentSize = 0;
OutputFileName = NULL;
SetUtilityName (UTILITY_NAME);
if (argc == 1) {
PrintUsage ();
return -1;
}
BufferSize = 1024 * 1024 * 16;
FileBuffer = (UINT8 *) malloc (BufferSize * sizeof (UINT8));
if (FileBuffer == NULL) {
Error (NULL, 0, 0, "memory allocation failed", NULL);
return -1;
}
ZeroMem (FileBuffer, BufferSize);
for (Index = 0; Index < argc; Index++) {
if (_strcmpi (argv[Index], "-i") == 0) {
ReturnValue = ReadFilesContentsIntoBuffer (
argv,
(Index + 1),
&FileBuffer,
&BufferSize,
&ContentSize,
(argc - (Index + 1))
);
if (ReturnValue == -1) {
Error (NULL, 0, 0, "failed to read file contents", NULL);
return -1;
}
Index += ReturnValue;
}
if (_strcmpi (argv[Index], "-o") == 0) {
OutputFileName = argv[Index + 1];
}
}
OutputFile = fopen (OutputFileName, "wb");
if (OutputFile == NULL) {
Error (NULL, 0, 0, OutputFileName, "failed to open output binary file");
free (FileBuffer);
return -1;
}
/*
//
// make sure section ends on a DWORD boundary ??
//
while ( (Size & 0x03) != 0 ) {
FileBuffer[Size] = 0;
Size ++;
}
*/
Status = SignSectionWithCrc32 (FileBuffer, &BufferSize, ContentSize);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 0, "failed to sign section", NULL);
free (FileBuffer);
fclose (OutputFile);
return -1;
}
ContentSize = fwrite (FileBuffer, sizeof (UINT8), BufferSize, OutputFile);
if (ContentSize != BufferSize) {
Error (NULL, 0, 0, "failed to write output buffer", NULL);
ReturnValue = -1;
} else {
ReturnValue = 0;
}
free (FileBuffer);
fclose (OutputFile);
return ReturnValue;
}

View File

@@ -0,0 +1,43 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenCRC32Section.h
Abstract:
Header file for GenFfsFile. Mainly defines the header of section
header for CRC32 GUID defined sections. Share with GenSection.c
--*/
//
// Module Coded to Tiano Coding Conventions
//
#ifndef _EFI_GEN_CRC32_SECTION_H
#define _EFI_GEN_CRC32_SECTION_H
//
// External Files Referenced
//
#include "TianoCommon.h"
#include "EfiImageFormat.h"
typedef struct {
EFI_GUID_DEFINED_SECTION GuidSectionHeader;
UINT32 CRC32Checksum;
} CRC32_SECTION_HEADER;
#define EFI_SECTION_CRC32_GUID_DEFINED 0
#define CRC32_SECTION_HEADER_SIZE (sizeof (CRC32_SECTION_HEADER))
#endif

View File

@@ -0,0 +1,85 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name: makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=GenCRC32Section
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\GenCRC32Section.c"
TARGET_EXE_INCLUDE = "$(EDK_SOURCE)\Foundation\Include\TianoCommon.h" \
"$(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareFileSystem.h" \
"$(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareVolumeHeader.h" \
"$(EDK_TOOLS_COMMON)\ParseInf.h"
TARGET_EXE_LIBS = "$(EDK_TOOLS_OUTPUT)\Common.lib"
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(TARGET_EXE_LIBS) $(TARGET_DLL)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(TARGET_LIB) $(TARGET_EXE_LIBS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,890 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
DepexParser.c
Abstract:
Validate Dependency Expression syntax
recursive descent Algorithm
The original BNF grammar(taken from "Pre EFI Initialization Core Interface Specification
draft review 0.9") is thus:
<depex> ::= BEFORE <guid> END
| AFTER <guid> END
| SOR <bool> END
| <bool> END
<bool> ::= <bool> AND <term>
| <bool> OR <term>
| <term>
<term> ::= NOT <factor>
| <factor>
<factor> ::= <bool>
| TRUE
| FALSE
| GUID
<guid> ::= '{' <hex32> ',' <hex16> ',' <hex16> ','
<hex8> ',' <hex8> ',' <hex8> ',' <hex8> ','
<hex8> ',' <hex8> ',' <hex8> ',' <hex8> '}'
<hex32> ::= <hexprefix> <hexvalue>
<hex16> ::= <hexprefix> <hexvalue>
<hex8> ::= <hexprefix> <hexvalue>
<hexprefix>::= '0' 'x'
| '0' 'X'
<hexvalue> ::= <hexdigit> <hexvalue>
| <hexdigit>
<hexdigit> ::= [0-9]
| [a-f]
| [A-F]
After cleaning left recursive and parentheses supported, the BNF grammar used in this module is thus:
<depex> ::= BEFORE <guid>
| AFTER <guid>
| SOR <bool>
| <bool>
<bool> ::= <term><rightbool>
<rightbool>::= AND <term><rightbool>
| OR <term><rightbool>
| ''
<term> ::= NOT <factor>
| <factor>
<factor> ::= '('<bool>')'<rightfactor>
| NOT <factor> <rightbool> <rightfactor>
| TRUE <rightfactor>
| FALSE <rightfactor>
| END <rightfactor>
| <guid> <rightfactor>
<rightfactor> ::=AND <term><rightbool> <rightfactor>
| OR <term><rightbool> <rightfactor>
| ''
<guid> ::= '{' <hex32> ',' <hex16> ',' <hex16> ','
<hex8> ',' <hex8> ',' <hex8> ',' <hex8> ','
<hex8> ',' <hex8> ',' <hex8> ',' <hex8> '}'
<hex32> ::= <hexprefix> <hexvalue>
<hex16> ::= <hexprefix> <hexvalue>
<hex8> ::= <hexprefix> <hexvalue>
<hexprefix>::= '0' 'x'
| '0' 'X'
<hexvalue> ::= <hexdigit> <hexvalue>
| <hexdigit>
<hexdigit> ::= [0-9]
| [a-f]
| [A-F]
Note: 1. There's no precedence in operators except parentheses;
2. For hex32, less and equal than 8 bits is valid, more than 8 bits is invalid.
Same constraint for hex16 is 4, hex8 is 2. All hex should contains at least 1 bit.
3. "<factor> ::= '('<bool>')'<rightfactor>" is added to support parentheses;
4. "<factor> ::= GUID" is changed to "<factor> ::= <guid>";
5. "DEPENDENCY_END" is the terminal of the expression. But it has been filtered by caller.
During parsing, "DEPENDENCY_END" will be treated as illegal factor;
This code should build in any environment that supports a standard C-library w/ string
operations and File I/O services.
As an example of usage, consider the following:
The input string could be something like:
NOT ({ 0xce345171, 0xba0b, 0x11d2, 0x8e, 0x4f, 0x0, 0xa0, 0xc9, 0x69, 0x72,
0x3b } AND { 0x964e5b22, 0x6459, 0x11d2, 0x8e, 0x39, 0x0, 0xa0, 0xc9, 0x69,
0x72, 0x3b }) OR { 0x03c4e603, 0xac28, 0x11d3, 0x9a, 0x2d, 0x00, 0x90, 0x27,
0x3f, 0xc1, 0x4d } AND
It's invalid for an extra "AND" in the end.
Complies with Tiano C Coding Standards Document, version 0.33, 16 Aug 2001.
--*/
#include "DepexParser.h"
BOOLEAN
ParseBool (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
);
BOOLEAN
ParseTerm (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
);
BOOLEAN
ParseRightBool (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
);
BOOLEAN
ParseFactor (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
);
VOID
LeftTrim (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Left trim the space, '\n' and '\r' character in string.
The space at the end does not need trim.
Arguments:
Pbegin The pointer to the string
length length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
None
--*/
{
while
(
((*Pindex) < (Pbegin + length)) &&
((strncmp (*Pindex, " ", 1) == 0) || (strncmp (*Pindex, "\n", 1) == 0) || (strncmp (*Pindex, "\r", 1) == 0))
) {
(*Pindex)++;
}
}
BOOLEAN
ParseHexdigit (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse Hex bit in dependency expression.
Arguments:
Pbegin The pointer to the string
length Length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
BOOLEAN If parses a valid hex bit, return TRUE, otherwise FALSE
--*/
{
//
// <hexdigit> ::= [0-9] | [a-f] | [A-F]
//
if (((**Pindex) >= '0' && (**Pindex) <= '9') ||
((**Pindex) >= 'a' && (**Pindex) <= 'f') ||
((**Pindex) >= 'A' && (**Pindex) <= 'F')
) {
(*Pindex)++;
return TRUE;
} else {
return FALSE;
}
}
BOOLEAN
ParseHex32 (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse Hex32 in dependency expression.
Arguments:
Pbegin The pointer to the string
length Length of the string
Pindex The pointer of point to the next parse character in the string
Returns:
BOOLEAN If parses a valid hex32, return TRUE, otherwise FALSE
--*/
{
INT32 Index;
INT8 *Pin;
Index = 0;
Pin = *Pindex;
LeftTrim (Pbegin, length, Pindex);
if ((strncmp (*Pindex, "0x", 2) != 0) && (strncmp (*Pindex, "0X", 2) != 0)) {
return FALSE;
}
(*Pindex) += 2;
while (ParseHexdigit (Pbegin, length, Pindex)) {
Index++;
}
if (Index > 0 && Index <= 8) {
return TRUE;
} else {
*Pindex = Pin;
return FALSE;
}
}
BOOLEAN
ParseHex16 (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse Hex16 in dependency expression.
Arguments:
Pbegin The pointer to the string
length Length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
BOOLEAN If parses a valid hex16, return TRUE, otherwise FALSE
--*/
{
int Index;
INT8 *Pin;
Index = 0;
Pin = *Pindex;
LeftTrim (Pbegin, length, Pindex);
if ((strncmp (*Pindex, "0x", 2) != 0) && (strncmp (*Pindex, "0X", 2) != 0)) {
return FALSE;
}
(*Pindex) += 2;
while (ParseHexdigit (Pbegin, length, Pindex)) {
Index++;
}
if (Index > 0 && Index <= 4) {
return TRUE;
} else {
*Pindex = Pin;
return FALSE;
}
}
BOOLEAN
ParseHex8 (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse Hex8 in dependency expression.
Arguments:
Pbegin The pointer to the string
length Length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
BOOLEAN If parses a valid hex8, return TRUE, otherwise FALSE
--*/
{
int Index;
INT8 *Pin;
Index = 0;
Pin = *Pindex;
LeftTrim (Pbegin, length, Pindex);
if ((strncmp (*Pindex, "0x", 2) != 0) && (strncmp (*Pindex, "0X", 2) != 0)) {
return FALSE;
}
(*Pindex) += 2;
while (ParseHexdigit (Pbegin, length, Pindex)) {
Index++;
}
if (Index > 0 && Index <= 2) {
return TRUE;
} else {
*Pindex = Pin;
return FALSE;
}
}
BOOLEAN
ParseGuid (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse guid in dependency expression.
There can be any number of spaces between '{' and hexword, ',' and hexword,
hexword and ',', hexword and '}'. The hexword include hex32, hex16 and hex8.
Arguments:
Pbegin The pointer to the string
length length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
BOOLEAN If parses a valid guid, return TRUE, otherwise FALSE
--*/
{
INT32 Index;
INT8 *Pin;
Pin = *Pindex;
LeftTrim (Pbegin, length, Pindex);
if (strncmp (*Pindex, "{", 1) != 0) {
return FALSE;
}
(*Pindex)++;
LeftTrim (Pbegin, length, Pindex);
if (!ParseHex32 (Pbegin, length, Pindex)) {
*Pindex = Pin;
return FALSE;
}
LeftTrim (Pbegin, length, Pindex);
if (strncmp (*Pindex, ",", 1) != 0) {
return FALSE;
} else {
(*Pindex)++;
}
for (Index = 0; Index < 2; Index++) {
LeftTrim (Pbegin, length, Pindex);
if (!ParseHex16 (Pbegin, length, Pindex)) {
*Pindex = Pin;
return FALSE;
}
LeftTrim (Pbegin, length, Pindex);
if (strncmp (*Pindex, ",", 1) != 0) {
return FALSE;
} else {
(*Pindex)++;
}
}
for (Index = 0; Index < 7; Index++) {
LeftTrim (Pbegin, length, Pindex);
if (!ParseHex8 (Pbegin, length, Pindex)) {
*Pindex = Pin;
return FALSE;
}
LeftTrim (Pbegin, length, Pindex);
if (strncmp (*Pindex, ",", 1) != 0) {
return FALSE;
} else {
(*Pindex)++;
}
}
LeftTrim (Pbegin, length, Pindex);
if (!ParseHex8 (Pbegin, length, Pindex)) {
*Pindex = Pin;
return FALSE;
}
LeftTrim (Pbegin, length, Pindex);
if (strncmp (*Pindex, "}", 1) != 0) {
return FALSE;
} else {
(*Pindex)++;
}
return TRUE;
}
BOOLEAN
ParseRightFactor (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse rightfactor in bool expression.
Arguments:
Pbegin The pointer to the string
length length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
BOOLEAN If string is a valid rightfactor expression, return TRUE, otherwise FALSE
--*/
{
INT8 *Pin;
Pin = *Pindex;
LeftTrim (Pbegin, length, Pindex);
//
// <rightfactor> ::=AND <term> <rightbool> <rightfactor>
//
if (strncmp (*Pindex, OPERATOR_AND, strlen (OPERATOR_AND)) == 0) {
*Pindex += strlen (OPERATOR_AND);
LeftTrim (Pbegin, length, Pindex);
if (ParseTerm (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (ParseRightBool (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (ParseRightFactor (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
}
} else {
*Pindex = Pin;
}
} else {
*Pindex = Pin;
}
}
//
// <rightfactor> ::=OR <term> <rightbool> <rightfactor>
//
if (strncmp (*Pindex, OPERATOR_OR, strlen (OPERATOR_OR)) == 0) {
*Pindex += strlen (OPERATOR_OR);
LeftTrim (Pbegin, length, Pindex);
if (ParseTerm (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (ParseRightBool (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (ParseRightFactor (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
}
} else {
*Pindex = Pin;
}
} else {
*Pindex = Pin;
}
}
//
// <rightfactor> ::= ''
//
*Pindex = Pin;
return TRUE;
}
BOOLEAN
ParseRightBool (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse rightbool in bool expression.
Arguments:
Pbegin The pointer to the string
length length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
BOOLEAN If string is a valid rightbool expression, return TRUE, otherwise FALSE
--*/
{
INT8 *Pin;
Pin = *Pindex;
LeftTrim (Pbegin, length, Pindex);
//
// <rightbool>::= AND <term><rightbool>
//
if (strncmp (*Pindex, OPERATOR_AND, strlen (OPERATOR_AND)) == 0) {
*Pindex += strlen (OPERATOR_AND);
LeftTrim (Pbegin, length, Pindex);
if (ParseTerm (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (ParseRightBool (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
}
} else {
*Pindex = Pin;
}
}
//
// <rightbool>::= OR <term><rightbool>
//
if (strncmp (*Pindex, OPERATOR_OR, strlen (OPERATOR_OR)) == 0) {
*Pindex += strlen (OPERATOR_OR);
LeftTrim (Pbegin, length, Pindex);
if (ParseTerm (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (ParseRightBool (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
}
} else {
*Pindex = Pin;
}
}
//
// <rightbool>::= ''
//
*Pindex = Pin;
return TRUE;
}
BOOLEAN
ParseFactor (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse factor in bool expression.
Arguments:
Pbegin The pointer to the string
length length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
BOOLEAN If string is a valid factor, return TRUE, otherwise FALSE
--*/
{
INT8 *Pin;
Pin = *Pindex;
LeftTrim (Pbegin, length, Pindex);
//
// <factor> ::= '('<bool>')'<rightfactor>
//
if (strncmp (*Pindex, OPERATOR_LEFT_PARENTHESIS, strlen (OPERATOR_LEFT_PARENTHESIS)) == 0) {
*Pindex += strlen (OPERATOR_LEFT_PARENTHESIS);
LeftTrim (Pbegin, length, Pindex);
if (!ParseBool (Pbegin, length, Pindex)) {
*Pindex = Pin;
} else {
LeftTrim (Pbegin, length, Pindex);
if (strncmp (*Pindex, OPERATOR_RIGHT_PARENTHESIS, strlen (OPERATOR_RIGHT_PARENTHESIS)) == 0) {
*Pindex += strlen (OPERATOR_RIGHT_PARENTHESIS);
LeftTrim (Pbegin, length, Pindex);
if (ParseRightFactor (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
}
}
}
}
//
// <factor> ::= NOT <factor> <rightbool> <rightfactor>
//
if (strncmp (*Pindex, OPERATOR_NOT, strlen (OPERATOR_NOT)) == 0) {
*Pindex += strlen (OPERATOR_NOT);
LeftTrim (Pbegin, length, Pindex);
if (ParseFactor (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (ParseRightBool (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (ParseRightFactor (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
}
} else {
*Pindex = Pin;
}
} else {
*Pindex = Pin;
}
}
//
// <factor> ::= TRUE <rightfactor>
//
if (strncmp (*Pindex, OPERATOR_TRUE, strlen (OPERATOR_TRUE)) == 0) {
*Pindex += strlen (OPERATOR_TRUE);
LeftTrim (Pbegin, length, Pindex);
if (ParseRightFactor (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
}
}
//
// <factor> ::= FALSE <rightfactor>
//
if (strncmp (*Pindex, OPERATOR_FALSE, strlen (OPERATOR_FALSE)) == 0) {
*Pindex += strlen (OPERATOR_FALSE);
LeftTrim (Pbegin, length, Pindex);
if (ParseRightFactor (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
}
}
//
// <factor> ::= <guid> <rightfactor>
//
if (ParseGuid (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (ParseRightFactor (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
return FALSE;
}
} else {
*Pindex = Pin;
return FALSE;
}
}
BOOLEAN
ParseTerm (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse term in bool expression.
Arguments:
Pbegin The pointer to the string
length length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
BOOLEAN If string is a valid term, return TRUE, otherwise FALSE
--*/
{
INT8 *Pin;
Pin = *Pindex;
LeftTrim (Pbegin, length, Pindex);
//
// <term> ::= NOT <factor>
//
if (strncmp (*Pindex, OPERATOR_NOT, strlen (OPERATOR_NOT)) == 0) {
*Pindex += strlen (OPERATOR_NOT);
LeftTrim (Pbegin, length, Pindex);
if (!ParseFactor (Pbegin, length, Pindex)) {
*Pindex = Pin;
} else {
return TRUE;
}
}
//
// <term> ::=<factor>
//
if (ParseFactor (Pbegin, length, Pindex)) {
return TRUE;
} else {
*Pindex = Pin;
return FALSE;
}
}
BOOLEAN
ParseBool (
IN INT8 *Pbegin,
IN UINT32 length,
IN OUT INT8 **Pindex
)
/*++
Routine Description:
Parse bool expression.
Arguments:
Pbegin The pointer to the string
length length of the string
Pindex The pointer of pointer to the next parse character in the string
Returns:
BOOLEAN If string is a valid bool expression, return TRUE, otherwise FALSE
--*/
{
INT8 *Pin;
Pin = *Pindex;
LeftTrim (Pbegin, length, Pindex);
if (ParseTerm (Pbegin, length, Pindex)) {
LeftTrim (Pbegin, length, Pindex);
if (!ParseRightBool (Pbegin, length, Pindex)) {
*Pindex = Pin;
return FALSE;
} else {
return TRUE;
}
} else {
*Pindex = Pin;
return FALSE;
}
}
BOOLEAN
ParseDepex (
IN INT8 *Pbegin,
IN UINT32 length
)
/*++
Routine Description:
Parse whole dependency expression.
Arguments:
Pbegin The pointer to the string
length length of the string
Returns:
BOOLEAN If string is a valid dependency expression, return TRUE, otherwise FALSE
--*/
{
BOOLEAN Result;
INT8 **Pindex;
INT8 *temp;
Result = FALSE;
temp = Pbegin;
Pindex = &temp;
LeftTrim (Pbegin, length, Pindex);
if (strncmp (*Pindex, OPERATOR_BEFORE, strlen (OPERATOR_BEFORE)) == 0) {
(*Pindex) += strlen (OPERATOR_BEFORE);
Result = ParseGuid (Pbegin, length, Pindex);
} else if (strncmp (*Pindex, OPERATOR_AFTER, strlen (OPERATOR_AFTER)) == 0) {
(*Pindex) += strlen (OPERATOR_AFTER);
Result = ParseGuid (Pbegin, length, Pindex);
} else if (strncmp (*Pindex, OPERATOR_SOR, strlen (OPERATOR_SOR)) == 0) {
(*Pindex) += strlen (OPERATOR_SOR);
Result = ParseBool (Pbegin, length, Pindex);
} else {
Result = ParseBool (Pbegin, length, Pindex);
}
LeftTrim (Pbegin, length, Pindex);
return (BOOLEAN) (Result && (*Pindex) >= (Pbegin + length));
}

View File

@@ -0,0 +1,26 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenDepex.h
Abstract:
This file contains the relevant declarations required
to generate a binary Dependency File
Complies with Tiano C Coding Standards Document, version 0.31, 12 Dec 2000.
--*/
// TODO: fix comment to set correct module name: DepexParser.h
#ifndef _EFI_DEPEX_PARSER_H_
#define _EFI_DEPEX_PARSER_H_
#include "GenDepex.h"
#endif

View File

@@ -0,0 +1,912 @@
/*++
Copyright (c) 2004 - 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenDepex.c
Abstract:
Generate Dependency Expression ("GenDepex")
Infix to Postfix Algorithm
This code has been scrubbed to be free of having any EFI core tree dependencies.
It should build in any environment that supports a standard C-library w/ string
operations and File I/O services.
As an example of usage, consider the following:
The input user file could be something like "Sample.DXS" whose contents are
#include "Tiano.h"
DEPENDENCY_START
NOT (DISK_IO_PROTOCOL AND SIMPLE_FILE_SYSTEM_PROTOCOL)
OR EFI_PXE_BASE_CODE_PROTOCOL
DEPENDENCY_END
This file is then washed through the C-preprocessor, viz.,
cl /EP Sample.DXS > Sample.TMP1
This yields the following file "Sample.TMP1" whose contents are
DEPENDENCY_START
NOT ({ 0xce345171, 0xba0b, 0x11d2, 0x8e, 0x4f, 0x0, 0xa0, 0xc9, 0x69, 0x72,
0x3b } AND { 0x964e5b22, 0x6459, 0x11d2, 0x8e, 0x39, 0x0, 0xa0, 0xc9, 0x69,
0x72, 0x3b }) OR { 0x03c4e603, 0xac28, 0x11d3, 0x9a, 0x2d, 0x00, 0x90, 0x27,
0x3f, 0xc1, 0x4d }
DEPENDENCY_END
This file, in turn, will be fed into the utility, viz.,
GenDepex Sample.TMP1 Sample.TMP2
With a file that is 55 bytes long:
55 bytes for the grammar binary
PUSH opcode - 1 byte
GUID Instance - 16 bytes
PUSH opcode - 1 byte
GUID Instance - 16 bytes
AND opcode - 1 byte
NOT opcode - 1 byte
PUSH opcode - 1 byte
GUID Instance - 16 bytes
OR opcode - 1 byte
END opcode - 1 byte
The file "Sample.TMP2" could be fed via a Section-builder utility
(GenSection) that would be used for the creation of a dependency
section file (.DPX) which in turn would be used by a generate FFS
utility (GenFfsFile) to produce a DXE driver/core (.DXE) or
a DXE application (.APP) file.
Complies with Tiano C Coding Standards Document, version 0.31, 12 Dec 2000.
--*/
#include "GenDepex.h"
#define TOOL_NAME "GenDepex"
extern
BOOLEAN
ParseDepex (
IN INT8 *Pbegin,
IN UINT32 length
);
VOID
PrintGenDepexUtilityInfo (
VOID
)
/*++
Routine Description:
Displays the standard utility information to SDTOUT.
Arguments:
None
Returns:
None
--*/
{
printf (
"%s, Tiano Dependency Expression Generation Utility. Version %d.%d.\n",
UTILITY_NAME,
UTILITY_MAJOR_VERSION,
UTILITY_MINOR_VERSION
);
printf ("Copyright (C) 1996-2002 Intel Corporation. All rights reserved.\n\n");
}
VOID
PrintGenDepexUsageInfo (
VOID
)
/*++
Routine Description:
Displays the utility usage syntax to STDOUT.
Arguments:
None
Returns:
None
--*/
{
printf (
"Usage: %s -I <INFILE> -O <OUTFILE> [-P <Optional Boundary for padding up>] \n",
UTILITY_NAME
);
printf (" Where:\n");
printf (" <INFILE> is the input pre-processed dependency text files name.\n");
printf (" <OUTFILE> is the output binary dependency files name.\n");
printf (" <Optional Boundary for padding up> is the padding integer value.\n");
printf (" This is the boundary to align the output file size to.\n");
}
DEPENDENCY_OPCODE
PopOpCode (
IN OUT VOID **Stack
)
/*++
Routine Description:
Pop an element from the Opcode stack.
Arguments:
Stack Current top of the OpCode stack location
Returns:
DEPENDENCY_OPCODE OpCode at the top of the OpCode stack.
Stack New top of the OpCode stack location
--*/
{
DEPENDENCY_OPCODE *OpCodePtr;
OpCodePtr = *Stack;
OpCodePtr--;
*Stack = OpCodePtr;
return *OpCodePtr;
}
VOID
PushOpCode (
IN OUT VOID **Stack,
IN DEPENDENCY_OPCODE OpCode
)
/*++
Routine Description:
Push an element onto the Opcode Stack
Arguments:
Stack Current top of the OpCode stack location
OpCode OpCode to push onto the stack
Returns:
Stack New top of the OpCode stack location
--*/
{
DEPENDENCY_OPCODE *OpCodePtr;
OpCodePtr = *Stack;
*OpCodePtr = OpCode;
OpCodePtr++;
*Stack = OpCodePtr;
}
EFI_STATUS
GenerateDependencyExpression (
IN FILE *InFile,
IN OUT FILE *OutFile,
IN UINT8 Padding OPTIONAL
)
/*++
Routine Description:
This takes the pre-compiled dependency text file and
converts it into a binary dependency file.
The BNF for the dependency expression is as follows
(from the DXE 1.0 Draft specification).
The inputted BNF grammar is thus:
<depex> ::= sor <dep> |
before GUID <dep> |
after GUID <dep> |
<bool>
<dep> ::= <bool> |
<bool> ::= <bool> and <term> |
<bool> or <term> |
<term>
<term> ::= not <factor> |
<factor>
<factor> ::= ( <bool> ) |
<term> <term> |
GUID |
<boolval>
<boolval> ::= true |
false
The outputed binary grammer is thus:
<depex> ::= sor <dep> |
before <depinst> <dep> |
after <depinst> <dep> |
<bool>
<dep> ::= <bool> |
<bool> ::= <bool> and <term> |
<bool> or <term> | <term>
<term> ::= not <factor> |
<factor>
<factor> ::= ( <bool> ) |
<term> <term> |
<boolval> |
<depinst> |
<termval>
<boolval> ::= true |
false
<depinst> ::= push GUID
<termval> ::= end
BugBug: A correct grammer is parsed correctly. A file that violates the
grammer may parse when it should generate an error. There is some
error checking and it covers most of the case when it's an include
of definition issue. An ill formed expresion may not be detected.
Arguments:
InFile - Input pre-compiled text file of the dependency expression.
This needs to be in ASCII.
The file pointer can not be NULL.
OutFile - Binary dependency file.
The file pointer can not be NULL.
Padding - OPTIONAL integer value to pad the output file to.
Returns:
EFI_SUCCESS The function completed successfully.
EFI_INVALID_PARAMETER One of the parameters in the text file was invalid.
EFI_OUT_OF_RESOURCES Unable to allocate memory.
EFI_ABORTED An misc error occurred.
--*/
{
INT8 *Ptrx;
INT8 *Pend;
INT8 *EvaluationStack;
INT8 *StackPtr;
INT8 *Buffer;
INT8 Line[LINESIZE];
UINTN Index;
UINTN OutFileSize;
UINTN FileSize;
UINTN Results;
BOOLEAN NotDone;
BOOLEAN Before_Flag;
BOOLEAN After_Flag;
BOOLEAN Dep_Flag;
BOOLEAN SOR_Flag;
EFI_GUID Guid;
UINTN ArgCountParsed;
DEPENDENCY_OPCODE Opcode;
Before_Flag = FALSE;
After_Flag = FALSE;
Dep_Flag = FALSE;
SOR_Flag = FALSE;
memset (Line, 0, LINESIZE);
OutFileSize = 0;
EvaluationStack = (INT8 *) malloc (EVAL_STACK_SIZE);
if (EvaluationStack != NULL) {
StackPtr = EvaluationStack;
} else {
printf ("Unable to allocate memory to EvaluationStack - Out of resources\n");
return EFI_OUT_OF_RESOURCES;
}
Results = (UINTN) fseek (InFile, 0, SEEK_END);
if (Results != 0) {
printf ("FSEEK failed - Aborted\n");
return EFI_ABORTED;
}
FileSize = ftell (InFile);
if (FileSize == -1L) {
printf ("FTELL failed - Aborted\n");
return EFI_ABORTED;
}
Buffer = (INT8 *) malloc (FileSize + BUFFER_SIZE);
if (Buffer == NULL) {
printf ("Unable to allocate memory to Buffer - Out of resources\n");
free (EvaluationStack);
Results = (UINTN) fclose (InFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
Results = (UINTN) fclose (OutFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
return EFI_OUT_OF_RESOURCES;
}
Results = (UINTN) fseek (InFile, 0, SEEK_SET);
if (Results != 0) {
printf ("FSEEK failed - Aborted\n");
return EFI_ABORTED;
}
fread (Buffer, FileSize, 1, InFile);
Ptrx = Buffer;
Pend = Ptrx + FileSize - strlen (DEPENDENCY_END);
Index = FileSize;
NotDone = TRUE;
while ((Index--) && NotDone) {
if (strncmp (Pend, DEPENDENCY_END, strlen (DEPENDENCY_END)) == 0) {
NotDone = FALSE;
} else {
Pend--;
}
}
if (NotDone) {
printf ("Couldn't find end string %s\n", DEPENDENCY_END);
Results = (UINTN) fclose (InFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
Results = (UINTN) fclose (OutFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
free (Buffer);
free (EvaluationStack);
return EFI_INVALID_PARAMETER;
}
Index = FileSize;
NotDone = TRUE;
while ((Index--) && NotDone) {
if (strncmp (Ptrx, DEPENDENCY_START, strlen (DEPENDENCY_START)) == 0) {
Ptrx += strlen (DEPENDENCY_START);
NotDone = FALSE;
//
// BUGBUG -- should Index be decremented by sizeof(DEPENDENCY_START)?
//
} else {
Ptrx++;
}
}
if (NotDone) {
printf ("Couldn't find start string %s\n", DEPENDENCY_START);
Results = (UINTN) fclose (InFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
Results = (UINTN) fclose (OutFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
free (Buffer);
free (EvaluationStack);
return EFI_INVALID_PARAMETER;
}
//
// validate the syntax of expression
//
if (!ParseDepex (Ptrx, Pend - Ptrx - 1)) {
printf ("The syntax of expression is wrong\n");
Results = (UINTN) fclose (InFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
Results = (UINTN) fclose (OutFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
free (Buffer);
free (EvaluationStack);
return EFI_INVALID_PARAMETER;
}
NotDone = TRUE;
while ((Index--) && NotDone) {
if (*Ptrx == ' ') {
Ptrx++;
} else if (*Ptrx == '\n' || *Ptrx == '\r') {
Ptrx++;
} else if (strncmp (Ptrx, OPERATOR_SOR, strlen (OPERATOR_SOR)) == 0) {
//
// Checks for some invalid dependencies
//
if (Before_Flag) {
printf ("A BEFORE operator was detected.\n");
printf ("There can only be one SOR or one AFTER or one BEFORE operator\n");
return EFI_INVALID_PARAMETER;
} else if (After_Flag) {
printf ("An AFTER operator was detected.\n");
printf ("There can only be one SOR or one AFTER or one BEFORE operator\n");
return EFI_INVALID_PARAMETER;
} else if (SOR_Flag) {
printf ("Another SOR operator was detected.\n");
printf ("There can only be one SOR or one AFTER or one BEFORE operator\n");
return EFI_INVALID_PARAMETER;
} else if (Dep_Flag) {
printf ("The Schedule On Request - SOR operator must be the first operator following DEPENDENCY_START\n");
return EFI_INVALID_PARAMETER;
} else {
//
// BUGBUG - This was not in the spec but is in the CORE code
// An OPERATOR_SOR has to be first - following the DEPENDENCY_START
//
fputc (EFI_DEP_SOR, OutFile);
OutFileSize++;
Ptrx += strlen (OPERATOR_SOR);
SOR_Flag = TRUE;
}
} else if (strncmp (Ptrx, OPERATOR_BEFORE, strlen (OPERATOR_BEFORE)) == 0) {
//
// Checks for some invalid dependencies
//
if (Before_Flag) {
printf ("Another BEFORE operator was detected.\n");
printf ("There can only be one SOR or one AFTER or one BEFORE operator\n");
return EFI_INVALID_PARAMETER;
} else if (After_Flag) {
printf ("An AFTER operator was detected.\n");
printf ("There can only be one SOR or one AFTER or one BEFORE operator\n");
return EFI_INVALID_PARAMETER;
} else if (SOR_Flag) {
printf ("A SOR operator was detected.\n");
printf ("There can only be one SOR or one AFTER or one BEFORE operator\n");
return EFI_INVALID_PARAMETER;
} else if (Dep_Flag) {
printf ("The BEFORE operator must be the first operator following DEPENDENCY_START\n");
return EFI_INVALID_PARAMETER;
} else {
fputc (EFI_DEP_BEFORE, OutFile);
OutFileSize++;
Ptrx += strlen (OPERATOR_BEFORE);
Before_Flag = TRUE;
}
} else if (strncmp (Ptrx, OPERATOR_AFTER, strlen (OPERATOR_AFTER)) == 0) {
//
// Checks for some invalid dependencies
//
if (Before_Flag) {
printf ("A BEFORE operator was detected.\n");
printf ("There can only be one SOR or one AFTER or one BEFORE operator\n");
return EFI_INVALID_PARAMETER;
} else if (After_Flag) {
printf ("Another AFTER operator was detected.\n");
printf ("There can only be one SOR or one AFTER or one BEFORE operator\n");
return EFI_INVALID_PARAMETER;
} else if (SOR_Flag) {
printf ("A SOR operator was detected.\n");
printf ("There can only be one SOR or one AFTER or one BEFORE operator\n");
return EFI_INVALID_PARAMETER;
} else if (Dep_Flag) {
printf ("The AFTER operator must be the first operator following DEPENDENCY_START\n");
return EFI_INVALID_PARAMETER;
} else {
fputc (EFI_DEP_AFTER, OutFile);
OutFileSize++;
Ptrx += strlen (OPERATOR_AFTER);
Dep_Flag = TRUE;
After_Flag = TRUE;
}
} else if (strncmp (Ptrx, OPERATOR_AND, strlen (OPERATOR_AND)) == 0) {
while (StackPtr != EvaluationStack) {
Opcode = PopOpCode ((VOID **) &StackPtr);
if (Opcode != DXE_DEP_LEFT_PARENTHESIS) {
fputc (Opcode, OutFile);
OutFileSize++;
} else {
PushOpCode ((VOID **) &StackPtr, DXE_DEP_LEFT_PARENTHESIS);
break;
}
}
PushOpCode ((VOID **) &StackPtr, EFI_DEP_AND);
Ptrx += strlen (OPERATOR_AND);
Dep_Flag = TRUE;
} else if (strncmp (Ptrx, OPERATOR_OR, strlen (OPERATOR_OR)) == 0) {
while (StackPtr != EvaluationStack) {
Opcode = PopOpCode ((VOID **) &StackPtr);
if (Opcode != DXE_DEP_LEFT_PARENTHESIS) {
fputc (Opcode, OutFile);
OutFileSize++;
} else {
PushOpCode ((VOID **) &StackPtr, DXE_DEP_LEFT_PARENTHESIS);
break;
}
}
PushOpCode ((VOID **) &StackPtr, EFI_DEP_OR);
Ptrx += strlen (OPERATOR_OR);
Dep_Flag = TRUE;
} else if (strncmp (Ptrx, OPERATOR_NOT, strlen (OPERATOR_NOT)) == 0) {
while (StackPtr != EvaluationStack) {
Opcode = PopOpCode ((VOID **) &StackPtr);
if (Opcode != DXE_DEP_LEFT_PARENTHESIS) {
fputc (Opcode, OutFile);
OutFileSize++;
} else {
PushOpCode ((VOID **) &StackPtr, DXE_DEP_LEFT_PARENTHESIS);
break;
}
}
PushOpCode ((VOID **) &StackPtr, EFI_DEP_NOT);
Ptrx += strlen (OPERATOR_NOT);
Dep_Flag = TRUE;
} else if (*Ptrx == '\t') {
printf ("File contains tabs. This violates the coding standard\n");
return EFI_INVALID_PARAMETER;
} else if (*Ptrx == '\n') {
//
// Skip the newline character in the file
//
Ptrx++;
} else if (strncmp (Ptrx, OPERATOR_LEFT_PARENTHESIS, strlen (OPERATOR_LEFT_PARENTHESIS)) == 0) {
PushOpCode ((VOID **) &StackPtr, DXE_DEP_LEFT_PARENTHESIS);
Ptrx += strlen (OPERATOR_LEFT_PARENTHESIS);
Dep_Flag = TRUE;
} else if (strncmp (Ptrx, OPERATOR_RIGHT_PARENTHESIS, strlen (OPERATOR_RIGHT_PARENTHESIS)) == 0) {
while (StackPtr != EvaluationStack) {
Opcode = PopOpCode ((VOID **) &StackPtr);
if (Opcode != DXE_DEP_LEFT_PARENTHESIS) {
fputc (Opcode, OutFile);
OutFileSize++;
} else {
break;
}
}
Ptrx += strlen (OPERATOR_RIGHT_PARENTHESIS);
Dep_Flag = TRUE;
} else if (strncmp (Ptrx, OPERATOR_TRUE, strlen (OPERATOR_TRUE)) == 0) {
fputc (EFI_DEP_TRUE, OutFile);
OutFileSize++;
//
// OutFileSize += sizeof (EFI_DEP_TRUE);
//
Dep_Flag = TRUE;
Ptrx += strlen (OPERATOR_TRUE);
} else if (strncmp (Ptrx, OPERATOR_FALSE, strlen (OPERATOR_FALSE)) == 0) {
fputc (EFI_DEP_FALSE, OutFile);
OutFileSize++;
//
// OutFileSize += sizeof (EFI_DEP_FALSE);
//
Dep_Flag = TRUE;
Ptrx += strlen (OPERATOR_FALSE);
} else if (*Ptrx == '{') {
Ptrx++;
if (*Ptrx == ' ') {
Ptrx++;
}
ArgCountParsed = sscanf (
Ptrx,
"%x, %x, %x, %x, %x, %x, %x, %x, %x, %x, %x",
&Guid.Data1,
&Guid.Data2,
&Guid.Data3,
&Guid.Data4[0],
&Guid.Data4[1],
&Guid.Data4[2],
&Guid.Data4[3],
&Guid.Data4[4],
&Guid.Data4[5],
&Guid.Data4[6],
&Guid.Data4[7]
);
if (ArgCountParsed != 11) {
printf ("We have found an illegal GUID\n");
printf ("Fix your depex\n");
exit (-1);
}
while (*Ptrx != '}') {
Ptrx++;
}
//
// Absorb the closing }
//
Ptrx++;
//
// Don't provide a PUSH Opcode for the Before and After case
//
if ((!Before_Flag) && (!After_Flag)) {
fputc (EFI_DEP_PUSH, OutFile);
OutFileSize++;
}
fwrite (&Guid, sizeof (EFI_GUID), 1, OutFile);
OutFileSize += sizeof (EFI_GUID);
Dep_Flag = TRUE;
} else if (strncmp (Ptrx, DEPENDENCY_END, strlen (DEPENDENCY_END)) == 0) {
NotDone = FALSE;
} else {
//
// Not a valid construct. Null terminate somewhere out there and
// print an error message.
//
*(Ptrx + 20) = 0;
printf (TOOL_NAME " ERROR: Unrecognized input at: \"%s\"...\n", Ptrx);
return EFI_INVALID_PARAMETER;
}
}
//
// DRAIN();
//
while (StackPtr != EvaluationStack) {
fputc (PopOpCode ((VOID **) &StackPtr), OutFile);
OutFileSize++;
}
if (OutFileSize == 0) {
printf ("Grammer contains no operators or constants\n");
return EFI_INVALID_PARAMETER;
}
fputc (EFI_DEP_END, OutFile);
OutFileSize++;
//
// Checks for invalid padding values
//
if (Padding < 0) {
printf ("The inputted padding value was %d\n", Padding);
printf ("The optional padding value can not be less than ZERO\n");
return EFI_INVALID_PARAMETER;
} else if (Padding > 0) {
while ((OutFileSize % Padding) != 0) {
fputc (' ', OutFile);
OutFileSize++;
}
}
Results = (UINTN) fclose (InFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
Results = (UINTN) fclose (OutFile);
if (Results != 0) {
printf ("FCLOSE failed\n");
}
free (Buffer);
free (EvaluationStack);
return EFI_SUCCESS;
} // End GenerateDependencyExpression function
EFI_STATUS
main (
IN UINTN argc,
IN CHAR8 *argv[]
)
/*++
Routine Description:
Parse user entries. Print some rudimentary help
Arguments:
argc The count of input arguments
argv The input arguments string array
Returns:
EFI_SUCCESS The function completed successfully.
EFI_INVALID_PARAMETER One of the input parameters was invalid or one of the parameters in the text file was invalid.
EFI_OUT_OF_RESOURCES Unable to allocate memory.
EFI_ABORTED Unable to open/create a file or a misc error.
--*/
// TODO: ] - add argument and description to function comment
{
FILE *OutFile;
FILE *InFile;
UINT8 Padding;
UINTN Index;
BOOLEAN Input_Flag;
BOOLEAN Output_Flag;
BOOLEAN Pad_Flag;
InFile = NULL;
OutFile = NULL;
Padding = 0;
Input_Flag = FALSE;
Output_Flag = FALSE;
Pad_Flag = FALSE;
//
// Output the calling arguments
//
printf ("\n\n");
for (Index = 0; Index < argc; Index++) {
printf ("%s ", argv[Index]);
}
printf ("\n\n");
if (argc < 5) {
printf ("Not enough arguments\n");
PrintGenDepexUsageInfo ();
return EFI_INVALID_PARAMETER;
}
for (Index = 1; Index < argc - 1; Index++) {
if ((strcmp (argv[Index], "-I") == 0) || (strcmp (argv[Index], "-i") == 0)) {
if (!Input_Flag) {
InFile = fopen (argv[Index + 1], "rb");
Input_Flag = TRUE;
} else {
printf ("GenDepex only allows one INPUT (-I) argument\n");
return EFI_INVALID_PARAMETER;
}
} else if ((strcmp (argv[Index], "-O") == 0) || (strcmp (argv[Index], "-o") == 0)) {
if (!Output_Flag) {
OutFile = fopen (argv[Index + 1], "wb");
Output_Flag = TRUE;
} else {
printf ("GenDepex only allows one OUTPUT (-O) argument\n");
return EFI_INVALID_PARAMETER;
}
} else if ((strcmp (argv[Index], "-P") == 0) || (strcmp (argv[Index], "-p") == 0)) {
if (!Pad_Flag) {
Padding = (UINT8) atoi (argv[Index + 1]);
Pad_Flag = TRUE;
} else {
printf ("GenDepex only allows one PADDING (-P) argument\n");
return EFI_INVALID_PARAMETER;
}
}
}
PrintGenDepexUtilityInfo ();
if (InFile == NULL) {
printf ("Can not open <INFILE> for reading.\n");
PrintGenDepexUsageInfo ();
return EFI_ABORTED;
}
if (OutFile == NULL) {
printf ("Can not open <OUTFILE> for writting.\n");
PrintGenDepexUsageInfo ();
return EFI_ABORTED;
}
return GenerateDependencyExpression (InFile, OutFile, Padding);
}

View File

@@ -0,0 +1,67 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenDepex.h
Abstract:
This file contains the relevant declarations required
to generate a binary Dependency File
Complies with Tiano C Coding Standards Document, version 0.31, 12 Dec 2000.
--*/
#ifndef _EFI_GEN_DEPEX_H
#define _EFI_GEN_DEPEX_H
#include "TianoCommon.h"
#include "EfiDependency.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <malloc.h>
#define DEPENDENCY_START "DEPENDENCY_START"
#define OPERATOR_BEFORE "BEFORE"
#define OPERATOR_AFTER "AFTER"
#define OPERATOR_AND "AND"
#define OPERATOR_OR "OR"
#define OPERATOR_NOT "NOT"
#define OPERATOR_TRUE "TRUE"
#define OPERATOR_FALSE "FALSE"
#define OPERATOR_SOR "SOR"
#define OPERATOR_END "END"
#define OPERATOR_LEFT_PARENTHESIS "("
#define OPERATOR_RIGHT_PARENTHESIS ")"
#define DEPENDENCY_END "DEPENDENCY_END"
#define DXE_DEP_LEFT_PARENTHESIS 0x0a
#define DXE_DEP_RIGHT_PARENTHESIS 0x0b
#define LINESIZE 320
#define SIZE_A_SYMBOL 60
#define DEPENDENCY_OPCODE UINT8
#define EVAL_STACK_SIZE 0x1024
#define BUFFER_SIZE 0x100
//
// Utility Name
//
#define UTILITY_NAME "GenDepex"
//
// Utility version information
//
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 4
#endif

View File

@@ -0,0 +1,100 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name: makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=GenDepex
TARGET_LIB_NAME=DepexParser
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_LIB = $(EDK_TOOLS_OUTPUT)\$(TARGET_LIB_NAME).lib
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_LIB_SOURCE = "$(TARGET_SOURCE_DIR)\DepexParser.c"
TARGET_LIB_INCLUDE = "$(TARGET_SOURCE_DIR)\DepexParser.h"
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\GenDepex.c"
TARGET_EXE_INCLUDE = "$(EDK_SOURCE)\Foundation\Include\TianoCommon.h"
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(TARGET_LIB)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(TARGET_LIB)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
#
# Build LIB
#
$(TARGET_LIB): $(EDK_TOOLS_OUTPUT)\$(TARGET_LIB_NAME).obj
$(LIB_EXE) $(LIB_FLAGS) $(EDK_TOOLS_OUTPUT)\$(TARGET_LIB_NAME).obj /OUT:$(TARGET_LIB)
$(EDK_TOOLS_OUTPUT)\$(TARGET_LIB_NAME).obj: $(TARGET_LIB_SOURCE) $(TARGET_LIB_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_LIB_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_LIB_NAME).obj
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,35 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenFfsFile.h
Abstract:
Header file for GenFfsFile.
--*/
//
// Module Coded to Tiano Coding Conventions
//
#ifndef _EFI_GEN_FFSFILE_H
#define _EFI_GEN_FFSFILE_H
//
// External Files Referenced
//
#include "TianoCommon.h"
#include "EfiImageFormat.h"
#include "MyAlloc.h"
#endif

View File

@@ -0,0 +1,88 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# makefile
#
# Abstract:
#
# This file is used to build the EFI GenFfsFile utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Common information
#
INC=$(INC)
LIBS = $(LIBS) $(EDK_TOOLS_OUTPUT)\CustomizedCompress.lib
#
# Target specific information
#
TARGET_NAME = GenFfsFile
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\GenFfsFile.c"
TARGET_EXE_INCLUDE = "$(EDK_SOURCE)\Foundation\Include\TianoCommon.h" \
"$(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareFileSystem.h" \
"$(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareVolumeHeader.h" \
"$(EDK_TOOLS_COMMON)\ParseInf.h" \
"$(EDK_TOOLS_COMMON)\MyAlloc.h"
TARGET_EXE_LIBS = "$(EDK_TOOLS_OUTPUT)\Common.lib"
C_FLAGS = $(C_FLAGS) -W4
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(LIBS) $(TARGET_EXE_LIBS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj \
$(TARGET_LIB) $(TARGET_EXE_LIBS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,299 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenFvImageExe.c
Abstract:
This contains all code necessary to build the GenFvImage.exe utility.
This utility relies heavily on the GenFvImage Lib. Definitions for both
can be found in the Tiano Firmware Volume Generation Utility
Specification, review draft.
--*/
//
// File included in build
//
#include "GenFvImageExe.h"
#include "CommonLib.h"
#include "EfiUtilityMsgs.h"
VOID
PrintUtilityInfo (
VOID
)
/*++
Routine Description:
Displays the standard utility information to SDTOUT
Arguments:
None
Returns:
None
--*/
{
printf (
"%s - Tiano Firmware Volume Generation Utility."" Version %i.%i\n\n",
UTILITY_NAME,
UTILITY_MAJOR_VERSION,
UTILITY_MINOR_VERSION
);
}
VOID
PrintUsage (
VOID
)
/*++
Routine Description:
Displays the utility usage syntax to STDOUT
Arguments:
None
Returns:
None
--*/
{
printf ("Usage: %s -I FvInfFileName\n", UTILITY_NAME);
printf (" Where:\n");
printf ("\tFvInfFileName is the name of the image description file.\n\n");
}
EFI_STATUS
main (
IN INTN argc,
IN CHAR8 **argv
)
/*++
Routine Description:
This utility uses GenFvImage.Lib to build a firmware volume image.
Arguments:
FvInfFileName The name of an FV image description file.
Arguments come in pair in any order.
-I FvInfFileName
Returns:
EFI_SUCCESS No error conditions detected.
EFI_INVALID_PARAMETER One or more of the input parameters is invalid.
EFI_OUT_OF_RESOURCES A resource required by the utility was unavailable.
Most commonly this will be memory allocation
or file creation.
EFI_LOAD_ERROR GenFvImage.lib could not be loaded.
EFI_ABORTED Error executing the GenFvImage lib.
--*/
{
EFI_STATUS Status;
CHAR8 InfFileName[_MAX_PATH];
CHAR8 *InfFileImage;
UINTN InfFileSize;
UINT8 *FvImage;
UINTN FvImageSize;
UINT8 Index;
CHAR8 FvFileNameBuffer[_MAX_PATH];
CHAR8 *FvFileName;
FILE *FvFile;
FILE *SymFile;
CHAR8 SymFileNameBuffer[_MAX_PATH];
CHAR8 *SymFileName;
UINT8 *SymImage;
UINTN SymImageSize;
CHAR8 *CurrentSymString;
FvFileName = FvFileNameBuffer;
SymFileName = SymFileNameBuffer;
SetUtilityName (UTILITY_NAME);
//
// Display utility information
//
PrintUtilityInfo ();
//
// Verify the correct number of arguments
//
if (argc != MAX_ARGS) {
Error (NULL, 0, 0, "invalid number of input parameters specified", NULL);
PrintUsage ();
return GetUtilityStatus ();
}
//
// Initialize variables
//
strcpy (InfFileName, "");
//
// Parse the command line arguments
//
for (Index = 1; Index < MAX_ARGS; Index += 2) {
//
// Make sure argument pair begin with - or /
//
if (argv[Index][0] != '-' && argv[Index][0] != '/') {
Error (NULL, 0, 0, argv[Index], "argument pair must begin with \"-\" or \"/\"");
PrintUsage ();
return GetUtilityStatus ();
}
//
// Make sure argument specifier is only one letter
//
if (argv[Index][2] != 0) {
Error (NULL, 0, 0, argv[Index], "unrecognized argument");
PrintUsage ();
return GetUtilityStatus ();
}
//
// Determine argument to read
//
switch (argv[Index][1]) {
case 'I':
case 'i':
if (strlen (InfFileName) == 0) {
strcpy (InfFileName, argv[Index + 1]);
} else {
Error (NULL, 0, 0, argv[Index + 1], "FvInfFileName may only be specified once");
PrintUsage ();
return GetUtilityStatus ();
}
break;
default:
Error (NULL, 0, 0, argv[Index], "unrecognized argument");
PrintUsage ();
return GetUtilityStatus ();
break;
}
}
//
// Read the INF file image
//
Status = GetFileImage (InfFileName, &InfFileImage, &InfFileSize);
if (EFI_ERROR (Status)) {
return STATUS_ERROR;
}
//
// Call the GenFvImage lib
//
Status = GenerateFvImage (
InfFileImage,
InfFileSize,
&FvImage,
&FvImageSize,
&FvFileName,
&SymImage,
&SymImageSize,
&SymFileName
);
if (EFI_ERROR (Status)) {
switch (Status) {
case EFI_INVALID_PARAMETER:
Error (NULL, 0, 0, "invalid parameter passed to GenFvImage Lib", NULL);
return GetUtilityStatus ();
break;
case EFI_ABORTED:
Error (NULL, 0, 0, "error detected while creating the file image", NULL);
return GetUtilityStatus ();
break;
case EFI_OUT_OF_RESOURCES:
Error (NULL, 0, 0, "GenFvImage Lib could not allocate required resources", NULL);
return GetUtilityStatus ();
break;
case EFI_VOLUME_CORRUPTED:
Error (NULL, 0, 0, "no base address was specified, but the FV.INF included a PEI or BSF file", NULL);
return GetUtilityStatus ();
break;
case EFI_LOAD_ERROR:
Error (NULL, 0, 0, "could not load FV image generation library", NULL);
return GetUtilityStatus ();
break;
default:
Error (NULL, 0, 0, "GenFvImage Lib returned unknown status", "status returned = 0x%X", Status);
return GetUtilityStatus ();
break;
}
}
//
// Write file
//
FvFile = fopen (FvFileName, "wb");
if (FvFile == NULL) {
Error (NULL, 0, 0, FvFileName, "could not open output file");
free (FvImage);
free (SymImage);
return GetUtilityStatus ();
}
if (fwrite (FvImage, 1, FvImageSize, FvFile) != FvImageSize) {
Error (NULL, 0, 0, FvFileName, "failed to write to output file");
free (FvImage);
free (SymImage);
fclose (FvFile);
return GetUtilityStatus ();
}
fclose (FvFile);
free (FvImage);
//
// Write symbol file
//
if (strcmp (SymFileName, "")) {
SymFile = fopen (SymFileName, "wt");
if (SymFile == NULL) {
Error (NULL, 0, 0, SymFileName, "could not open output symbol file");
free (SymImage);
return GetUtilityStatus ();
}
fprintf (SymFile, "TEXTSYM format | V1.0\n");
CurrentSymString = SymImage;
while (((UINTN) CurrentSymString - (UINTN) SymImage) < SymImageSize) {
fprintf (SymFile, "%s", CurrentSymString);
CurrentSymString = (CHAR8 *) (((UINTN) CurrentSymString) + strlen (CurrentSymString) + 1);
}
fclose (SymFile);
}
free (SymImage);
return GetUtilityStatus ();
}

View File

@@ -0,0 +1,98 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenFvImageExe.h
Abstract:
Definitions for the PeimFixup exe utility.
--*/
//
// Coded to Tiano Coding Standards
//
#ifndef _EFI_GEN_FV_IMAGE_EXE_H
#define _EFI_GEN_FV_IMAGE_EXE_H
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "GenFvImageLib.h"
//
// Utility Name
//
#define UTILITY_NAME "GenFvImage"
//
// Utility version information
//
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
#define UTILITY_DATE __DATE__
//
// The maximum number of arguments accepted from the command line.
//
#define MAX_ARGS 3
//
// The function that displays general utility information
//
VOID
PrintUtilityInfo (
VOID
)
/*++
Routine Description:
TODO: Add function description
Arguments:
None
Returns:
TODO: add return values
--*/
;
//
// The function that displays the utility usage message.
//
VOID
PrintUsage (
VOID
)
/*++
Routine Description:
TODO: Add function description
Arguments:
None
Returns:
TODO: add return values
--*/
;
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,140 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenFvImageLib.h
Abstract:
This file contains describes the public interfaces to the GenFvImage Library.
The basic purpose of the library is to create Firmware Volume images.
--*/
#ifndef _EFI_GEN_FV_IMAGE_LIB_H
#define _EFI_GEN_FV_IMAGE_LIB_H
//
// Include files
//
#include "Efi2WinNT.h"
#include "ParseInf.h"
//
// Following definition is used for FIT in IPF
//
#define COMP_TYPE_FIT_PEICORE 0x10
#define COMP_TYPE_FIT_UNUSED 0x7F
#define FIT_TYPE_MASK 0x7F
#define CHECKSUM_BIT_MASK 0x80
#pragma pack(1)
typedef struct {
UINT64 CompAddress;
UINT32 CompSize;
UINT16 CompVersion;
UINT8 CvAndType;
UINT8 CheckSum;
} FIT_TABLE;
#pragma pack()
//
// Exported function prototypes
//
EFI_STATUS
GenerateFvImage (
IN CHAR8 *InfFileImage,
IN UINTN InfFileSize,
OUT UINT8 **FvImage,
OUT UINTN *FvImageSize,
OUT CHAR8 **FvFileName,
OUT UINT8 **SymImage,
OUT UINTN *SymImageSize,
OUT CHAR8 **SymFileName
)
;
/*++
Routine Description:
This is the main function which will be called from application.
Arguments:
InfFileImage Buffer containing the INF file contents.
InfFileSize Size of the contents of the InfFileImage buffer.
FvImage Pointer to the FV image created.
FvImageSize Size of the FV image created and pointed to by FvImage.
FvFileName Requested name for the FV file.
SymImage Pointer to the Sym image created.
SymImageSize Size of the Sym image created and pointed to by SymImage.
SymFileName Requested name for the Sym file.
Returns:
EFI_SUCCESS Function completed successfully.
EFI_OUT_OF_RESOURCES Could not allocate required resources.
EFI_ABORTED Error encountered.
EFI_INVALID_PARAMETER A required parameter was NULL.
--*/
EFI_STATUS
UpdatePeiCoreEntryInFit (
IN FIT_TABLE *FitTablePtr,
IN UINT64 PeiCorePhysicalAddress
)
;
/*++
Routine Description:
This function is used to update the Pei Core address in FIT, this can be used by Sec core to pass control from
Sec to Pei Core
Arguments:
FitTablePtr - The pointer of FIT_TABLE.
PeiCorePhysicalAddress - The address of Pei Core entry.
Returns:
EFI_SUCCESS - The PEI_CORE FIT entry was updated successfully.
EFI_NOT_FOUND - Not found the PEI_CORE FIT entry.
--*/
VOID
UpdateFitCheckSum (
IN FIT_TABLE *FitTablePtr
)
;
/*++
Routine Description:
This function is used to update the checksum for FIT.
Arguments:
FitTablePtr - The pointer of FIT_TABLE.
Returns:
None.
--*/
#endif

View File

@@ -0,0 +1,212 @@
/*++
Copyright (c) 2004 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenFvImageLibInternal.h
Abstract:
This file contains describes the private declarations for the GenFvImage Library.
The basic purpose of the library is to create Firmware Volume images.
--*/
#ifndef _EFI_GEN_FV_IMAGE_LIB_INTERNAL_H
#define _EFI_GEN_FV_IMAGE_LIB_INTERNAL_H
//
// Include files
//
#include "GenFvImageLib.h"
#include <stdlib.h>
#include "EfiFirmwareVolumeHeader.h"
//
// Private data declarations
//
//
// The maximum number of block map entries supported by the library
//
#define MAX_NUMBER_OF_FV_BLOCKS 100
//
// The maximum number of files in the FV supported by the library
//
#define MAX_NUMBER_OF_FILES_IN_FV 1000
#define MAX_NUMBER_OF_COMPONENTS_IN_FV 10
//
// INF file strings
//
#define OPTIONS_SECTION_STRING "[options]"
#define ATTRIBUTES_SECTION_STRING "[attributes]"
#define FILES_SECTION_STRING "[files]"
#define COMPONENT_SECTION_STRING "[components]"
#define EFI_FV_BASE_ADDRESS_STRING "EFI_BASE_ADDRESS"
#define EFI_FV_FILE_NAME_STRING "EFI_FILE_NAME"
#define EFI_SYM_FILE_NAME_STRING "EFI_SYM_FILE_NAME"
#define EFI_NUM_BLOCKS_STRING "EFI_NUM_BLOCKS"
#define EFI_BLOCK_SIZE_STRING "EFI_BLOCK_SIZE"
#define EFI_FV_GUID_STRING "EFI_FV_GUID"
#define EFI_FVB_READ_DISABLED_CAP_STRING "EFI_READ_DISABLED_CAP"
#define EFI_FVB_READ_ENABLED_CAP_STRING "EFI_READ_ENABLED_CAP"
#define EFI_FVB_READ_STATUS_STRING "EFI_READ_STATUS"
#define EFI_FVB_WRITE_DISABLED_CAP_STRING "EFI_WRITE_DISABLED_CAP"
#define EFI_FVB_WRITE_ENABLED_CAP_STRING "EFI_WRITE_ENABLED_CAP"
#define EFI_FVB_WRITE_STATUS_STRING "EFI_WRITE_STATUS"
#define EFI_FVB_LOCK_CAP_STRING "EFI_LOCK_CAP"
#define EFI_FVB_LOCK_STATUS_STRING "EFI_LOCK_STATUS"
#define EFI_FVB_STICKY_WRITE_STRING "EFI_STICKY_WRITE"
#define EFI_FVB_MEMORY_MAPPED_STRING "EFI_MEMORY_MAPPED"
#define EFI_FVB_ERASE_POLARITY_STRING "EFI_ERASE_POLARITY"
#define EFI_FVB_ALIGNMENT_CAP_STRING "EFI_ALIGNMENT_CAP"
#define EFI_FVB_ALIGNMENT_2_STRING "EFI_ALIGNMENT_2"
#define EFI_FVB_ALIGNMENT_4_STRING "EFI_ALIGNMENT_4"
#define EFI_FVB_ALIGNMENT_8_STRING "EFI_ALIGNMENT_8"
#define EFI_FVB_ALIGNMENT_16_STRING "EFI_ALIGNMENT_16"
#define EFI_FVB_ALIGNMENT_32_STRING "EFI_ALIGNMENT_32"
#define EFI_FVB_ALIGNMENT_64_STRING "EFI_ALIGNMENT_64"
#define EFI_FVB_ALIGNMENT_128_STRING "EFI_ALIGNMENT_128"
#define EFI_FVB_ALIGNMENT_256_STRING "EFI_ALIGNMENT_256"
#define EFI_FVB_ALIGNMENT_512_STRING "EFI_ALIGNMENT_512"
#define EFI_FVB_ALIGNMENT_1K_STRING "EFI_ALIGNMENT_1K"
#define EFI_FVB_ALIGNMENT_2K_STRING "EFI_ALIGNMENT_2K"
#define EFI_FVB_ALIGNMENT_4K_STRING "EFI_ALIGNMENT_4K"
#define EFI_FVB_ALIGNMENT_8K_STRING "EFI_ALIGNMENT_8K"
#define EFI_FVB_ALIGNMENT_16K_STRING "EFI_ALIGNMENT_16K"
#define EFI_FVB_ALIGNMENT_32K_STRING "EFI_ALIGNMENT_32K"
#define EFI_FVB_ALIGNMENT_64K_STRING "EFI_ALIGNMENT_64K"
//
// Add these for PI1.0 new Attributes.
//
#define EFI_FVB_READ_LOCK_CAP_STRING "EFI_READ_LOCK_CAP"
#define EFI_FVB_READ_LOCK_STATUS_STRING "EFI_READ_LOCK_STATUS"
#define EFI_FVB_WRITE_LOCK_CAP_STRING "EFI_WRITE_LOCK_CAP"
#define EFI_FVB_WRITE_LOCK_STATUS_STRING "EFI_WRITE_LOCK_STATUS"
#define EFI_FVB2_ALIGNMENT_STRING "EFI_FVB2_ALIGNMENT"
#define EFI_FVB2_ALIGNMENT_1_STRING "1"
#define EFI_FVB2_ALIGNMENT_2_STRING "2"
#define EFI_FVB2_ALIGNMENT_4_STRING "4"
#define EFI_FVB2_ALIGNMENT_8_STRING "8"
#define EFI_FVB2_ALIGNMENT_16_STRING "16"
#define EFI_FVB2_ALIGNMENT_32_STRING "32"
#define EFI_FVB2_ALIGNMENT_64_STRING "64"
#define EFI_FVB2_ALIGNMENT_128_STRING "128"
#define EFI_FVB2_ALIGNMENT_256_STRING "256"
#define EFI_FVB2_ALIGNMENT_512_STRING "512"
#define EFI_FVB2_ALIGNMENT_1K_STRING "1K"
#define EFI_FVB2_ALIGNMENT_2K_STRING "2K"
#define EFI_FVB2_ALIGNMENT_4K_STRING "4K"
#define EFI_FVB2_ALIGNMENT_8K_STRING "8K"
#define EFI_FVB2_ALIGNMENT_16K_STRING "16K"
#define EFI_FVB2_ALIGNMENT_32K_STRING "32K"
#define EFI_FVB2_ALIGNMENT_64K_STRING "64K"
#define EFI_FVB2_ALIGNMENT_128K_STRING "128K"
#define EFI_FVB2_ALIGNMENT_256K_STRING "256K"
#define EFI_FVB2_ALIGNMENT_512K_STRING "512K"
#define EFI_FVB2_ALIGNMENT_1M_STRING "1M"
#define EFI_FVB2_ALIGNMENT_2M_STRING "2M"
#define EFI_FVB2_ALIGNMENT_4M_STRING "4M"
#define EFI_FVB2_ALIGNMENT_8M_STRING "8M"
#define EFI_FVB2_ALIGNMENT_16M_STRING "16M"
#define EFI_FVB2_ALIGNMENT_32M_STRING "32M"
#define EFI_FVB2_ALIGNMENT_64M_STRING "64M"
#define EFI_FVB2_ALIGNMENT_128M_STRING "128M"
#define EFI_FVB2_ALIGNMENT_256M_STRING "256M"
#define EFI_FVB2_ALIGNMENT_512M_STRING "512M"
#define EFI_FVB2_ALIGNMENT_1G_STRING "1G"
#define EFI_FVB2_ALIGNMENT_2G_STRING "2G"
//
// Component sections
//
#define EFI_NV_VARIABLE_STRING "EFI_NV_VARIABLE"
#define EFI_NV_EVENT_LOG_STRING "EFI_NV_EVENT_LOG"
#define EFI_NV_FTW_WORKING_STRING "EFI_NV_FTW_WORKING"
#define EFI_NV_FTW_SPARE_STRING "EFI_NV_FTW_SPARE"
#define EFI_FILE_NAME_STRING "EFI_FILE_NAME"
#define ONE_STRING "1"
#define ZERO_STRING "0"
#define TRUE_STRING "TRUE"
#define FALSE_STRING "FALSE"
#define NULL_STRING "NULL"
//
// Defines to calculate the offset for PEI CORE entry points
//
#define IA32_PEI_CORE_ENTRY_OFFSET 0x20
//
// Defines to calculate the FIT table
//
#define IPF_FIT_ADDRESS_OFFSET 0x20
//
// Defines to calculate the offset for SALE_ENTRY
//
#define IPF_SALE_ENTRY_ADDRESS_OFFSET 0x18
//
// Symbol file definitions, current max size if 512K
//
#define SYMBOL_FILE_SIZE 0x80000
#define FV_IMAGES_TOP_ADDRESS 0x100000000
//
// Private data types
//
//
// Component information
//
typedef struct {
UINTN Size;
CHAR8 ComponentName[_MAX_PATH];
} COMPONENT_INFO;
//
// FV information holder
//
typedef struct {
EFI_PHYSICAL_ADDRESS BaseAddress;
EFI_GUID FvGuid;
UINTN Size;
CHAR8 FvName[_MAX_PATH];
CHAR8 SymName[_MAX_PATH];
EFI_FV_BLOCK_MAP_ENTRY FvBlocks[MAX_NUMBER_OF_FV_BLOCKS];
EFI_FVB_ATTRIBUTES FvAttributes;
CHAR8 FvFiles[MAX_NUMBER_OF_FILES_IN_FV][_MAX_PATH];
COMPONENT_INFO FvComponents[MAX_NUMBER_OF_COMPONENTS_IN_FV];
} FV_INFO;
//
// Private function prototypes
//
EFI_STATUS
ParseFvInf (
IN MEMORY_FILE *InfFile,
IN FV_INFO *FvInfo
)
;
#endif

View File

@@ -0,0 +1,109 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name: makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Common information
#
INC=$(INC) \
-I "$(EDK_TOOLS_COMMON)"
#
# Target specific information
#
TARGET_NAME=GenFvImage
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_LIB = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).lib
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\GenFvImageExe.c"
TARGET_EXE_INCLUDE = "$(TARGET_SOURCE_DIR)\GenFvImageExe.h" \
"$(TARGET_SOURCE_DIR)\GenFvImageLib.h" \
"$(EDK_TOOLS_COMMON)\ParseInf.h" \
"$(EDK_SOURCE)\Foundation\Include\TianoCommon.h"
TARGET_EXE_LIBS = "$(EDK_TOOLS_OUTPUT)\Common.lib"
TARGET_LIB_SOURCE = "$(TARGET_SOURCE_DIR)\GenFvImageLib.c"
TARGET_LIB_INCLUDE = "$(TARGET_SOURCE_DIR)\GenFvImageLib.h" \
"$(TARGET_SOURCE_DIR)\GenFvImageLibInternal.h" \
"$(EDK_TOOLS_COMMON)\ParseInf.h" \
"$(EDK_SOURCE)\Foundation\Include\TianoCommon.h" \
"$(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareVolumeHeader.h" \
"$(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareFileSystem.h" \
"$(EDK_SOURCE)\Foundation\Framework\Guid\FirmwareFileSystem\FirmwareFileSystem.h"
TARGET_LIB_LIBS = "$(EDK_TOOLS_OUTPUT)\Common.lib"
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(TARGET_EXE_LIBS) $(TARGET_LIB)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(TARGET_LIB) $(TARGET_EXE_LIBS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
#
# Build LIB
#
$(TARGET_LIB): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Lib.obj $(TARGET_LIB_LIBS)
$(LIB_EXE) $(LIB_FLAGS) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Lib.obj $(MSVS_LINK_LIBPATHS) $(TARGET_LIB_LIBS) RPCRT4.lib /OUT:$(TARGET_LIB)
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Lib.obj: $(TARGET_LIB_SOURCE) $(TARGET_LIB_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_LIB_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Lib.obj
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Lib.* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME)Lib.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,95 @@
#/*++
#
# Copyright (c) 2006 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the GenPage utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=GenPage
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\GenPage.c"
TARGET_EXE_INCLUDE = "$(TARGET_SOURCE_DIR)\VirtualMemory.h"
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,127 @@
/*++
Copyright 2006 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
VirtualMemory.h
Abstract:
x64 Long Mode Virtual Memory Management Definitions
References:
1) IA-32 Intel(R) Atchitecture Software Developer's Manual Volume 1:Basic Architecture, Intel
2) IA-32 Intel(R) Atchitecture Software Developer's Manual Volume 2:Instruction Set Reference, Intel
3) IA-32 Intel(R) Atchitecture Software Developer's Manual Volume 3:System Programmer's Guide, Intel
4) AMD64 Architecture Programmer's Manual Volume 2: System Programming
--*/
#ifndef _VIRTUAL_MEMORY_H_
#define _VIRTUAL_MEMORY_H_
#include "Tiano.h"
#pragma pack(1)
//
// Page-Map Level-4 Offset (PML4) and
// Page-Directory-Pointer Offset (PDPE) entries 4K & 2MB
//
typedef union {
struct {
UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory
UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write
UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User
UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching
UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached
UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU)
UINT64 Reserved:1; // Reserved
UINT64 MustBeZero:2; // Must Be Zero
UINT64 Available:3; // Available for use by system software
UINT64 PageTableBaseAddress:40; // Page Table Base Address
UINT64 AvabilableHigh:11; // Available for use by system software
UINT64 Nx:1; // No Execute bit
} Bits;
UINT64 Uint64;
} X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K;
//
// Page-Directory Offset 4K
//
typedef union {
struct {
UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory
UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write
UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User
UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching
UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached
UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU)
UINT64 Reserved:1; // Reserved
UINT64 MustBeZero:1; // Must Be Zero
UINT64 Reserved2:1; // Reserved
UINT64 Available:3; // Available for use by system software
UINT64 PageTableBaseAddress:40; // Page Table Base Address
UINT64 AvabilableHigh:11; // Available for use by system software
UINT64 Nx:1; // No Execute bit
} Bits;
UINT64 Uint64;
} X64_PAGE_DIRECTORY_ENTRY_4K;
//
// Page Table Entry 4K
//
typedef union {
struct {
UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory
UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write
UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User
UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching
UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached
UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU)
UINT64 Dirty:1; // 0 = Not Dirty, 1 = written by processor on access to page
UINT64 PAT:1; // 0 = Ignore Page Attribute Table
UINT64 Global:1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
UINT64 Available:3; // Available for use by system software
UINT64 PageTableBaseAddress:40; // Page Table Base Address
UINT64 AvabilableHigh:11; // Available for use by system software
UINT64 Nx:1; // 0 = Execute Code, 1 = No Code Execution
} Bits;
UINT64 Uint64;
} X64_PAGE_TABLE_ENTRY_4K;
//
// Page Table Entry 2MB
//
typedef union {
struct {
UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory
UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write
UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User
UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching
UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached
UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU)
UINT64 Dirty:1; // 0 = Not Dirty, 1 = written by processor on access to page
UINT64 MustBe1:1; // Must be 1
UINT64 Global:1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write
UINT64 Available:3; // Available for use by system software
UINT64 PAT:1; //
UINT64 MustBeZero:8; // Must be zero;
UINT64 PageTableBaseAddress:31; // Page Table Base Address
UINT64 AvabilableHigh:11; // Available for use by system software
UINT64 Nx:1; // 0 = Execute Code, 1 = No Code Execution
} Bits;
UINT64 Uint64;
} X64_PAGE_TABLE_ENTRY_2M;
#pragma pack()
#endif

View File

@@ -0,0 +1,344 @@
/*++
Copyright 2006 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenPage.c
Abstract:
Pre-Create a 4G page table (2M pages).
It's used in DUET x64 build needed to enter LongMode.
Create 4G page table (2M pages)
Linear Address
63 48 47 39 38 30 29 21 20 0
+--------+-------+---------------+-----------+-----------------------------+
PML4 Directory-Ptr Directory Offset
Paging-Structures :=
PML4
(
Directory-Ptr Directory {512}
) {4}
--*/
#include <stdio.h>
#include <stdlib.h>
#include "VirtualMemory.h"
void
memset (void *, char, long);
unsigned int
xtoi (char *);
#define EFI_PAGE_BASE_OFFSET_IN_LDR 0x70000
#define EFI_PAGE_BASE_ADDRESS (EFI_PAGE_BASE_OFFSET_IN_LDR + 0x20000)
unsigned int gPageTableBaseAddress = EFI_PAGE_BASE_ADDRESS;
unsigned int gPageTableOffsetInFile = EFI_PAGE_BASE_OFFSET_IN_LDR;
#define EFI_MAX_ENTRY_NUM 512
#define EFI_PML4_ENTRY_NUM 1
#define EFI_PDPTE_ENTRY_NUM 4
#define EFI_PDE_ENTRY_NUM EFI_MAX_ENTRY_NUM
#define EFI_PML4_PAGE_NUM 1
#define EFI_PDPTE_PAGE_NUM EFI_PML4_ENTRY_NUM
#define EFI_PDE_PAGE_NUM (EFI_PML4_ENTRY_NUM * EFI_PDPTE_ENTRY_NUM)
#define EFI_PAGE_NUMBER (EFI_PML4_PAGE_NUM + EFI_PDPTE_PAGE_NUM + EFI_PDE_PAGE_NUM)
#define EFI_SIZE_OF_PAGE 0x1000
#define EFI_PAGE_SIZE_2M 0x200000
#define CONVERT_BIN_PAGE_ADDRESS(a) ((UINT8 *) a - PageTable + gPageTableBaseAddress)
void *
CreateIdentityMappingPageTables (
void
)
/*++
Routine Description:
To create 4G PAE 2M pagetable
Return:
void * - buffer containing created pagetable
--*/
{
UINT64 PageAddress;
UINT8 *PageTable;
UINT8 *PageTablePtr;
int PML4Index;
int PDPTEIndex;
int PDEIndex;
X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K *PageMapLevel4Entry;
X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K *PageDirectoryPointerEntry;
X64_PAGE_TABLE_ENTRY_2M *PageDirectoryEntry2MB;
PageTable = (void *)malloc (EFI_PAGE_NUMBER * EFI_SIZE_OF_PAGE);
memset (PageTable, 0, (EFI_PAGE_NUMBER * EFI_SIZE_OF_PAGE));
PageTablePtr = PageTable;
PageAddress = 0;
//
// Page Table structure 3 level 2MB.
//
// Page-Map-Level-4-Table : bits 47-39
// Page-Directory-Pointer-Table : bits 38-30
//
// Page Table 2MB : Page-Directory(2M) : bits 29-21
//
//
PageMapLevel4Entry = (X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K *)PageTablePtr;
for (PML4Index = 0; PML4Index < EFI_PML4_ENTRY_NUM; PML4Index++, PageMapLevel4Entry++) {
//
// Each Page-Map-Level-4-Table Entry points to the base address of a Page-Directory-Pointer-Table Entry
//
PageTablePtr += EFI_SIZE_OF_PAGE;
PageDirectoryPointerEntry = (X64_PAGE_MAP_AND_DIRECTORY_POINTER_2MB_4K *)PageTablePtr;
//
// Make a Page-Map-Level-4-Table Entry
//
PageMapLevel4Entry->Uint64 = (UINT64)(UINT32)(CONVERT_BIN_PAGE_ADDRESS (PageDirectoryPointerEntry));
PageMapLevel4Entry->Bits.ReadWrite = 1;
PageMapLevel4Entry->Bits.Present = 1;
for (PDPTEIndex = 0; PDPTEIndex < EFI_PDPTE_ENTRY_NUM; PDPTEIndex++, PageDirectoryPointerEntry++) {
//
// Each Page-Directory-Pointer-Table Entry points to the base address of a Page-Directory Entry
//
PageTablePtr += EFI_SIZE_OF_PAGE;
PageDirectoryEntry2MB = (X64_PAGE_TABLE_ENTRY_2M *)PageTablePtr;
//
// Make a Page-Directory-Pointer-Table Entry
//
PageDirectoryPointerEntry->Uint64 = (UINT64)(UINT32)(CONVERT_BIN_PAGE_ADDRESS (PageDirectoryEntry2MB));
PageDirectoryPointerEntry->Bits.ReadWrite = 1;
PageDirectoryPointerEntry->Bits.Present = 1;
for (PDEIndex = 0; PDEIndex < EFI_PDE_ENTRY_NUM; PDEIndex++, PageDirectoryEntry2MB++) {
//
// Make a Page-Directory Entry
//
PageDirectoryEntry2MB->Uint64 = (UINT64)PageAddress;
PageDirectoryEntry2MB->Bits.ReadWrite = 1;
PageDirectoryEntry2MB->Bits.Present = 1;
PageDirectoryEntry2MB->Bits.MustBe1 = 1;
PageAddress += EFI_PAGE_SIZE_2M;
}
}
}
return PageTable;
}
int
GenBinPage (
void *BaseMemory,
char *NoPageFileName,
char *PageFileName
)
/*++
Routine Description:
Write the buffer containing page table to file at a specified offset.
Here the offset is defined as EFI_PAGE_BASE_OFFSET_IN_LDR.
Arguments:
BaseMemory - buffer containing page table
NoPageFileName - file to write page table
PageFileName - file save to after writing
return:
0 : successful
-1 : failed
--*/
{
FILE *PageFile;
FILE *NoPageFile;
UINT8 Data;
unsigned long FileSize;
//
// Open files
//
PageFile = fopen (PageFileName, "w+b");
if (PageFile == NULL) {
fprintf (stderr, "GenBinPage: Could not open file %s\n", PageFileName);
return -1;
}
NoPageFile = fopen (NoPageFileName, "r+b");
if (NoPageFile == NULL) {
fprintf (stderr, "GenBinPage: Could not open file %s\n", NoPageFileName);
fclose (PageFile);
return -1;
}
//
// Check size - should not be great than EFI_PAGE_BASE_OFFSET_IN_LDR
//
fseek (NoPageFile, 0, SEEK_END);
FileSize = ftell (NoPageFile);
fseek (NoPageFile, 0, SEEK_SET);
if (FileSize > gPageTableOffsetInFile) {
fprintf (stderr, "GenBinPage: file size too large - 0x%x\n", FileSize);
fclose (PageFile);
fclose (NoPageFile);
return -1;
}
//
// Write data
//
while (fread (&Data, sizeof(UINT8), 1, NoPageFile)) {
fwrite (&Data, sizeof(UINT8), 1, PageFile);
}
//
// Write PageTable
//
fseek (PageFile, gPageTableOffsetInFile, SEEK_SET);
fwrite (BaseMemory, (EFI_PAGE_NUMBER * EFI_SIZE_OF_PAGE), 1, PageFile);
//
// Close files
//
fclose (PageFile);
fclose (NoPageFile);
return 0;
}
int
main (
int argc,
char **argv
)
{
void *BaseMemory;
int result;
//
// Check parameter
//
if ((argc != 3) && (argc != 5)) {
printf ("Usage: GenPage.exe NoPageFile PageFile [<PageTableBaseAddrss> <PageTableOffsetInFile>]\n");
return 1;
}
//
// Get PageTable parameter, if have
//
if (argc == 5) {
gPageTableBaseAddress = xtoi (argv[3]);
gPageTableOffsetInFile = xtoi (argv[4]);
}
//
// Create X64 page table
//
BaseMemory = CreateIdentityMappingPageTables ();
//
// Add page table to binary file
//
result = GenBinPage (BaseMemory, argv[1], argv[2]);
if (result < 0) {
return 1;
}
return 0;
}
unsigned int
xtoi (
char *str
)
/*++
Routine Description:
Convert hex string to uint
Arguments:
Str - The string
Returns:
--*/
{
unsigned int u;
char c;
unsigned int m;
if (str == NULL) {
return 0;
}
m = (unsigned int) -1 >> 4;
//
// skip preceeding white space
//
while (*str && *str == ' ') {
str += 1;
}
//
// skip preceeding zeros
//
while (*str && *str == '0') {
str += 1;
}
//
// skip preceeding white space
//
if (*str && (*str == 'x' || *str == 'X')) {
str += 1;
}
//
// convert hex digits
//
u = 0;
c = *(str++);
while (c) {
if (c >= 'a' && c <= 'f') {
c -= 'a' - 'A';
}
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
if (u > m) {
return (unsigned int) -1;
}
u = u << 4 | c - (c >= 'A' ? 'A' - 10 : '0');
} else {
break;
}
c = *(str++);
}
return u;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,42 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GenSection.h
Abstract:
Header file for GenSection.
--*/
//
// Module Coded to Tiano Coding Conventions
//
#ifndef _EFI_GEN_SECTION_H
#define _EFI_GEN_SECTION_H
//
// External Files Referenced
//
#include "TianoCommon.h"
#include "EfiImageFormat.h"
typedef struct {
EFI_GUID_DEFINED_SECTION GuidSectionHeader;
UINT32 CRC32Checksum;
} CRC32_SECTION_HEADER;
#define EFI_SECTION_CRC32_GUID_DEFINED 0
#define CRC32_SECTION_HEADER_SIZE (sizeof (CRC32_SECTION_HEADER))
#endif

View File

@@ -0,0 +1,82 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name: makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Common information
#
INC = $(INC) -I $(EDK_TOOLS_SOURCE)\Common
LIBS = $(LIBS) $(EDK_TOOLS_OUTPUT)\CustomizedCompress.lib
#
# Target specific information
#
TARGET_NAME = GenSection
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\GenSection.c"
TARGET_EXE_LIBS = "$(EDK_TOOLS_OUTPUT)\Common.lib"
TARGET_EXE_INCLUDE = "$(EDK_SOURCE)\Foundation\Include\TianoCommon.h" \
"$(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareFileSystem.h" \
"$(EDK_SOURCE)\Foundation\Framework\Include\EfiFirmwareVolumeHeader.h" \
"$(EDK_TOOLS_COMMON)\ParseInf.h"
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(LIBS) $(TARGET_EXE_LIBS)
$(LINK) /DEBUG $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj $(TARGET_EXE_LIBS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,57 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
CommonUtils.h
Abstract:
Common utility defines and structure definitions.
--*/
#ifndef _COMMON_UTILS_H_
#define _COMMON_UTILS_H_
//
// Basic types
//
typedef unsigned char UINT8;
typedef char INT8;
typedef unsigned short UINT16;
typedef unsigned int UINT32;
typedef UINT8 BOOLEAN;
typedef UINT32 STATUS;
#define TRUE 1
#define FALSE 0
#define STATUS_SUCCESS 0
#define STATUS_WARNING 1
#define STATUS_ERROR 2
//
// Linked list of strings
//
typedef struct _STRING_LIST {
struct _STRING_LIST *Next;
char *Str;
} STRING_LIST;
int
CreateGuidList (
INT8 *OutFileName
)
;
#endif // #ifndef _COMMON_UTILS_H_

View File

@@ -0,0 +1,285 @@
/*++
Copyright (c) 2004 - 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
FileSearch.c
Abstract:
Module used to support file searches on the system.
--*/
#include <stdio.h>
#include "CommonUtils.h"
#include "FileSearch.h"
#include "UtilsMsgs.h"
//
// Internal file search flag for sanity checks
//
#define FILE_SEARCH_STARTED 0x8000
#define FILE_SEARCH_INITED 0x4000
static
BOOLEAN
FileSearchMeetsCriteria (
FILE_SEARCH_DATA *FSData
);
/*****************************************************************************/
STATUS
FileSearchInit (
FILE_SEARCH_DATA *FSData
)
{
memset ((char *) FSData, 0, sizeof (FILE_SEARCH_DATA));
FSData->Handle = INVALID_HANDLE_VALUE;
FSData->FileSearchFlags = FILE_SEARCH_INITED;
FSData->FileName[0] = 0;
return STATUS_SUCCESS;
}
STATUS
FileSearchStart (
FILE_SEARCH_DATA *FSData,
char *FileMask,
UINT32 SearchFlags
)
{
BOOLEAN Done;
//
// Save their flags, and set a flag to indicate that they called this
// start function so we can perform extended checking in the other
// routines we have in this module.
//
FSData->FileSearchFlags |= (SearchFlags | FILE_SEARCH_STARTED);
FSData->FileName[0] = 0;
//
// Begin the search
//
FSData->Handle = FindFirstFile (FileMask, &(FSData->FindData));
if (FSData->Handle == INVALID_HANDLE_VALUE) {
return STATUS_ERROR;
}
//
// Keep looping through until we find a file meeting the caller's
// criteria per the search flags
//
Done = FALSE;
while (!Done) {
//
// If we're done (we found a match) copy the file name found and return
//
Done = FileSearchMeetsCriteria (FSData);
if (Done) {
return STATUS_SUCCESS;
}
//
// Go on to next file
//
if (!FindNextFile (FSData->Handle, &(FSData->FindData))) {
return STATUS_NOT_FOUND;
}
}
//
// Not reached
//
return STATUS_NOT_FOUND;
}
//
// Find the next file meeting their criteria and return it.
//
STATUS
FileSearchFindNext (
FILE_SEARCH_DATA *FSData
)
{
BOOLEAN Done;
Done = FALSE;
while (!Done) {
if (!FindNextFile (FSData->Handle, &(FSData->FindData))) {
return STATUS_NOT_FOUND;
}
//
// See if it matches their criteria
//
Done = FileSearchMeetsCriteria (FSData);
if (Done) {
return STATUS_SUCCESS;
}
}
//
// Not reached
//
return STATUS_NOT_FOUND;
}
//
// Perform any cleanup necessary to close down a search
//
STATUS
FileSearchDestroy (
FILE_SEARCH_DATA *FSData
)
{
if (FSData->Handle != INVALID_HANDLE_VALUE) {
FindClose (FSData->Handle);
FSData->Handle = INVALID_HANDLE_VALUE;
}
FSData->FileName[0] = 0;
FSData->FileSearchFlags = 0;
return STATUS_SUCCESS;
}
static
BOOLEAN
FileSearchMeetsCriteria (
FILE_SEARCH_DATA *FSData
)
{
BOOLEAN Status;
STRING_LIST *StrList;
UINT32 ExtLen;
UINT32 FileNameLen;
Status = FALSE;
//
// First clear the flag indicating this is neither a file or a
// directory.
//
FSData->FileFlags &= ~(FILE_SEARCH_DIR | FILE_SEARCH_FILE);
//
// We found a file. See if it matches the user's search criteria. First
// check for this being a directory, and they want directories, and
// it's not "." and it's not ".."
//
if ((FSData->FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
(FSData->FileSearchFlags & FILE_SEARCH_DIR) &&
(strcmp (FSData->FindData.cFileName, ".")) &&
(strcmp (FSData->FindData.cFileName, ".."))
) {
//
// Assume we'll make it past this check
//
Status = TRUE;
//
// If they have a list of exclude directories, then check for those
//
StrList = FSData->ExcludeDirs;
while (StrList != NULL) {
if (_stricmp (FSData->FindData.cFileName, StrList->Str) == 0) {
Status = FALSE;
break;
}
StrList = StrList->Next;
}
//
// If we didn't fail due to excluded directories, then set the dir flag
//
if (Status) {
FSData->FileFlags |= FILE_SEARCH_DIR;
}
//
// Else check for a file, and they want files....
//
} else if (((FSData->FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) &&
(FSData->FileSearchFlags & FILE_SEARCH_FILE)
) {
//
// See if it's in our list of excluded files
//
Status = TRUE;
StrList = FSData->ExcludeFiles;
while (StrList != NULL) {
if (_stricmp (FSData->FindData.cFileName, StrList->Str) == 0) {
Status = FALSE;
break;
}
StrList = StrList->Next;
}
if (Status) {
//
// See if it's in our list of excluded file extensions
//
FileNameLen = strlen (FSData->FindData.cFileName);
StrList = FSData->ExcludeExtensions;
while (StrList != NULL) {
ExtLen = strlen (StrList->Str);
if (_stricmp (
FSData->FindData.cFileName + FileNameLen - ExtLen,
StrList->Str
) == 0) {
Status = FALSE;
break;
}
StrList = StrList->Next;
}
}
if (Status) {
FSData->FileFlags |= FILE_SEARCH_FILE;
}
}
//
// If it's a match, copy the filename into another field of the structure
// for portability.
//
if (Status) {
strcpy (FSData->FileName, FSData->FindData.cFileName);
}
return Status;
}
//
// Exclude a list of subdirectories.
//
STATUS
FileSearchExcludeDirs (
FILE_SEARCH_DATA *FSData,
STRING_LIST *StrList
)
{
FSData->ExcludeDirs = StrList;
return STATUS_SUCCESS;
}
STATUS
FileSearchExcludeFiles (
FILE_SEARCH_DATA *FSData,
STRING_LIST *StrList
)
{
FSData->ExcludeFiles = StrList;
return STATUS_SUCCESS;
}
STATUS
FileSearchExcludeExtensions (
FILE_SEARCH_DATA *FSData,
STRING_LIST *StrList
)
{
FSData->ExcludeExtensions = StrList;
return STATUS_SUCCESS;
}

View File

@@ -0,0 +1,108 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
FileSearch.h
Abstract:
Header file to support file searching.
--*/
#ifndef _FILE_SEARCH_H_
#define _FILE_SEARCH_H_
//
// Since the file searching routines are OS dependent, put the
// necessary include paths in this header file so that the non-OS-dependent
// files don't need to include these windows-specific header files.
//
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <direct.h>
#include <windows.h>
//
// Return codes of some of the file search routines
//
#define STATUS_NOT_FOUND 0x1000
//
// Flags for what to search for. Also used in the FileFlags return field.
//
#define FILE_SEARCH_DIR 0x0001
#define FILE_SEARCH_FILE 0x0002
//
// Here's our class definition
//
typedef struct {
HANDLE Handle;
WIN32_FIND_DATA FindData;
UINT32 FileSearchFlags; // DIRS, FILES, etc
UINT32 FileFlags;
INT8 FileName[MAX_PATH]; // for portability
STRING_LIST *ExcludeDirs;
STRING_LIST *ExcludeFiles;
STRING_LIST *ExcludeExtensions;
} FILE_SEARCH_DATA;
//
// Here's our member functions
//
STATUS
FileSearchInit (
FILE_SEARCH_DATA *FSData
)
;
STATUS
FileSearchDestroy (
FILE_SEARCH_DATA *FSData
)
;
STATUS
FileSearchStart (
FILE_SEARCH_DATA *FSData,
char *FileMask,
UINT32 SearchFlags
)
;
STATUS
FileSearchFindNext (
FILE_SEARCH_DATA *FSData
)
;
STATUS
FileSearchExcludeDirs (
FILE_SEARCH_DATA *FSData,
STRING_LIST *StrList
)
;
STATUS
FileSearchExcludeExtensions (
FILE_SEARCH_DATA *FSData,
STRING_LIST *StrList
)
;
STATUS
FileSearchExcludeFiles (
FILE_SEARCH_DATA *FSData,
STRING_LIST *StrList
)
;
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,188 @@
/*++
Copyright (c) 2004 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
GuidList.c
Abstract:
Utility to create a GUID-to-name listing file that can
be used by other utilities. Basic operation is to take the
table of name+GUIDs that we have compiled into this utility,
and create a text file that can be parsed by other utilities
to do replacement of "name" with "GUID".
Notes:
To add a new GUID to this database:
1. Add a "#include EFI_GUID_DEFINITION(name)" statement below
2. Modify the mGuidList[] array below to add the new GUID name
The only issue that may come up is that, if the source GUID file
is not in the standard GUID directory, then this utility won't
compile because the #include fails. In this case you'd need
to define a new macro (if it's in a standard place) or modify
this utility's makefile to add the path to your new .h file.
--*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "Tiano.h"
#include "EfiUtilityMsgs.h"
#include EFI_GUID_DEFINITION (Apriori)
#include EFI_GUID_DEFINITION (AcpiTableStorage)
#include EFI_GUID_DEFINITION (Bmp)
#include EFI_GUID_DEFINITION (AcpiTableStorage)
#include EFI_GUID_DEFINITION (PeiApriori)
#define GUID_XREF(varname, guid) { \
#varname, #guid, guid \
}
#define NULL_GUID \
{ \
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 \
}
typedef struct {
INT8 *VariableName;
INT8 *DefineName;
EFI_GUID Guid;
} GUID_LIST;
//
// This is our table of all GUIDs we want to print out to create
// a GUID-to-name cross reference.
// Use the #defined name from the GUID definition's source .h file.
//
static GUID_LIST mGuidList[] = {
GUID_XREF(gEfiPeiAprioriGuid, EFI_PEI_APRIORI_FILE_NAME_GUID),
GUID_XREF(gAprioriGuid, EFI_APRIORI_GUID),
GUID_XREF(gEfiDefaultBmpLogoGuid, EFI_DEFAULT_BMP_LOGO_GUID),
GUID_XREF(gEfiAcpiTableStorageGuid, EFI_ACPI_TABLE_STORAGE_GUID),
//
// Terminator
//
{
NULL,
NULL,
NULL_GUID
}
};
void
PrintGuidText (
FILE *OutFptr,
INT8 *VariableName,
INT8 *DefineName,
EFI_GUID *Guid
);
int
CreateGuidList (
INT8 *OutFileName
)
/*++
Routine Description:
Print our GUID/name list to the specified output file.
Arguments:
OutFileName - name of the output file to write our results to.
Returns:
0 if successful
nonzero otherwise
--*/
{
FILE *OutFptr;
int Index;
//
// Open output file for writing. If the name is NULL, then write to stdout
//
if (OutFileName != NULL) {
OutFptr = fopen (OutFileName, "w");
if (OutFptr == NULL) {
Error (NULL, 0, 0, OutFileName, "failed to open output file for writing");
return STATUS_ERROR;
}
} else {
OutFptr = stdout;
}
for (Index = 0; mGuidList[Index].VariableName != NULL; Index++) {
PrintGuidText (OutFptr, mGuidList[Index].VariableName, mGuidList[Index].DefineName, &mGuidList[Index].Guid);
}
//
// Close the output file if they specified one.
//
if (OutFileName != NULL) {
fclose (OutFptr);
}
return STATUS_SUCCESS;
}
void
PrintGuidText (
FILE *OutFptr,
INT8 *VariableName,
INT8 *DefineName,
EFI_GUID *Guid
)
/*++
Routine Description:
Print a GUID/name combo in INF-style format
guid-guid-guid-guid DEFINE_NAME gName
Arguments:
OutFptr - file pointer to which to write the output
VariableName - the GUID variable's name
DefineName - the name used in the #define
Guid - pointer to the GUID value
Returns:
NA
--*/
{
if (OutFptr == NULL) {
OutFptr = stdout;
}
fprintf (
OutFptr,
"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X %s %s\n",
Guid->Data1,
Guid->Data2,
Guid->Data3,
Guid->Data4[0],
Guid->Data4[1],
Guid->Data4[2],
Guid->Data4[3],
Guid->Data4[4],
Guid->Data4[5],
Guid->Data4[6],
Guid->Data4[7],
DefineName,
VariableName
);
}

View File

@@ -0,0 +1,96 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the GUID check utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Target specific information
#
TARGET_NAME = GuidChk
TARGET_SRC_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\GuidChk.exe
#LIBS = $(LIBS) "$(EDK_TOOLS_OUTPUT)\Common.lib"
#
# Build targets
#
all: $(TARGET_EXE)
INC_DEPS = $(TARGET_SRC_DIR)\FileSearch.h $(INC_DEPS)
#INC_DEPS = $(TARGET_SRC_DIR)\CommonUtils.h $(INC_DEPS)
#INC_DEPS = $(TARGET_SRC_DIR)\UtilsMsgs.h $(INC_DEPS)
OBJECTS = $(EDK_TOOLS_OUTPUT)\GuidChk.obj \
$(EDK_TOOLS_OUTPUT)\FileSearch.obj \
$(EDK_TOOLS_OUTPUT)\GuidList.obj \
$(EDK_TOOLS_OUTPUT)\UtilsMsgs.obj
#
# Compile each source file
#
$(EDK_TOOLS_OUTPUT)\GuidChk.obj : $(TARGET_SRC_DIR)\GuidChk.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(INC) $(TARGET_SRC_DIR)\GuidChk.c /Fo$@
$(EDK_TOOLS_OUTPUT)\FileSearch.obj : $(TARGET_SRC_DIR)\FileSearch.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(INC) $(TARGET_SRC_DIR)\FileSearch.c /Fo$@
$(EDK_TOOLS_OUTPUT)\GuidList.obj : $(TARGET_SRC_DIR)\GuidList.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(INC) $(TARGET_SRC_DIR)\GuidList.c /Fo$@
$(EDK_TOOLS_OUTPUT)\UtilsMsgs.obj : $(TARGET_SRC_DIR)\UtilsMsgs.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(INC) $(TARGET_SRC_DIR)\UtilsMsgs.c /Fo$@
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE) : $(OBJECTS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\FileSearch.* del $(EDK_TOOLS_OUTPUT)\FileSearch.* > NUL

View File

@@ -0,0 +1,489 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
UtilsMsgs.c
Abstract:
EFI tools utility functions to display warning, error, and informational
messages.
--*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include "Tiano.h"
#include "EfiUtilityMsgs.h"
#define MAX_LINE_LEN 200
//
// Declare module globals for keeping track of the the utility's
// name and other settings.
//
static STATUS mStatus = STATUS_SUCCESS;
static INT8 mUtilityName[50] = { 0 };
static INT8 *mSourceFileName = NULL;
static UINT32 mSourceFileLineNum = 0;
static UINT32 mErrorCount = 0;
static UINT32 mWarningCount = 0;
static UINT32 mDebugMsgMask = 0;
static
void
PrintMessage (
INT8 *Type,
INT8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
va_list List
);
void
Error (
INT8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Prints an error message.
Arguments:
All arguments are optional, though the printed message may be useless if
at least something valid is not specified.
FileName - name of the file or application. If not specified, then the
utilty name (as set by the utility calling SetUtilityName()
earlier) is used. Otherwise "Unknown utility" is used.
LineNumber - the line number of error, typically used by parsers. If the
utility is not a parser, then 0 should be specified. Otherwise
the FileName and LineNumber info can be used to cause
MS Visual Studio to jump to the error.
MessageCode - an application-specific error code that can be referenced in
other documentation.
Text - the text in question, typically used by parsers.
MsgFmt - the format string for the error message. Can contain formatting
controls for use with the varargs.
Returns:
None.
Notes:
We print the following (similar to the Warn() and Debug()
W
Typical error/warning message format:
bin\VfrCompile.cpp(330) : error C2660: 'AddVfrDataStructField' : function does not take 2 parameters
BUGBUG -- these three utility functions are almost identical, and
should be modified to share code.
Visual Studio does not find error messages with:
" error :"
" error 1:"
" error c1:"
" error 1000:"
" error c100:"
It does find:
" error c1000:"
--*/
{
va_list List;
mErrorCount++;
va_start (List, MsgFmt);
PrintMessage ("error", FileName, LineNumber, MessageCode, Text, MsgFmt, List);
va_end (List);
//
// Set status accordingly
//
if (mStatus < STATUS_ERROR) {
mStatus = STATUS_ERROR;
}
}
void
ParserError (
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Print a parser error, using the source file name and line number
set by a previous call to SetParserPosition().
Arguments:
MessageCode - application-specific error code
Text - text to print in the error message
MsgFmt - format string to print at the end of the error message
...
Returns:
NA
--*/
{
va_list List;
mErrorCount++;
va_start (List, MsgFmt);
PrintMessage ("error", mSourceFileName, mSourceFileLineNum, MessageCode, Text, MsgFmt, List);
va_end (List);
//
// Set status accordingly
//
if (mStatus < STATUS_ERROR) {
mStatus = STATUS_ERROR;
}
}
void
ParserWarning (
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Print a parser warning, using the source file name and line number
set by a previous call to SetParserPosition().
Arguments:
ErrorCode - application-specific error code
OffendingText - text to print in the warning message
MsgFmt - format string to print at the end of the warning message
...
Returns:
NA
--*/
{
va_list List;
mWarningCount++;
va_start (List, MsgFmt);
PrintMessage ("warning", mSourceFileName, mSourceFileLineNum, ErrorCode, OffendingText, MsgFmt, List);
va_end (List);
//
// Set status accordingly
//
if (mStatus < STATUS_WARNING) {
mStatus = STATUS_WARNING;
}
}
void
Warning (
INT8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Print a warning message.
Arguments:
FileName - name of the file where the warning was detected, or the name
of the application that detected the warning
LineNumber - the line number where the warning was detected (parsers).
0 should be specified if the utility is not a parser.
MessageCode - an application-specific warning code that can be referenced in
other documentation.
Text - the text in question (parsers)
MsgFmt - the format string for the warning message. Can contain formatting
controls for use with varargs.
...
Returns:
None.
--*/
{
va_list List;
mWarningCount++;
va_start (List, MsgFmt);
PrintMessage ("warning", FileName, LineNumber, MessageCode, Text, MsgFmt, List);
va_end (List);
//
// Set status accordingly
//
if (mStatus < STATUS_WARNING) {
mStatus = STATUS_WARNING;
}
}
void
DebugMsg (
INT8 *FileName,
UINT32 LineNumber,
UINT32 MsgMask,
INT8 *Text,
INT8 *MsgFmt,
...
)
/*++
Routine Description:
Print a warning message.
Arguments:
FileName - typically the name of the utility printing the debug message, but
can be the name of a file being parsed.
LineNumber - the line number in FileName (parsers)
MsgMask - an application-specific bitmask that, in combination with mDebugMsgMask,
determines if the debug message gets printed.
Text - the text in question (parsers)
MsgFmt - the format string for the debug message. Can contain formatting
controls for use with varargs.
...
Returns:
None.
--*/
{
va_list List;
//
// If the debug mask is not applicable, then do nothing.
//
if ((MsgMask != 0) && ((mDebugMsgMask & MsgMask) == 0)) {
return ;
}
va_start (List, MsgFmt);
PrintMessage ("debug", FileName, LineNumber, 0, Text, MsgFmt, List);
va_end (List);
}
static
void
PrintMessage (
INT8 *Type,
INT8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
INT8 *Text,
INT8 *MsgFmt,
va_list List
)
/*++
Routine Description:
Worker routine for all the utility printing services. Prints the message in
a format that Visual Studio will find when scanning build outputs for
errors or warnings.
Arguments:
Type - "warning" or "error" string to insert into the message to be
printed. The first character of this string (converted to uppercase)
is used to preceed the MessageCode value in the output string.
FileName - name of the file where the warning was detected, or the name
of the application that detected the warning
LineNumber - the line number where the warning was detected (parsers).
0 should be specified if the utility is not a parser.
MessageCode - an application-specific warning code that can be referenced in
other documentation.
Text - part of the message to print
MsgFmt - the format string for the message. Can contain formatting
controls for use with varargs.
List - Variable function parameter list.
Returns:
None.
Notes:
If FileName == NULL then this utility will use the string passed into SetUtilityName().
LineNumber is only used if the caller is a parser, in which case FileName refers to the
file being parsed.
Text and MsgFmt are both optional, though it would be of little use calling this function with
them both NULL.
Output will typically be of the form:
<FileName>(<LineNumber>) : <Type> <Type[0]><MessageCode>: <Text> : <MsgFmt>
Parser (LineNumber != 0)
VfrCompile.cpp(330) : error E2660: AddVfrDataStructField : function does not take 2 parameters
Generic utility (LineNumber == 0)
UtilityName : error E1234 : Text string : MsgFmt string and args
--*/
{
INT8 Line[MAX_LINE_LEN];
INT8 Line2[MAX_LINE_LEN];
INT8 *Cptr;
//
// If given a filename, then add it (and the line number) to the string.
// If there's no filename, then use the program name if provided.
//
if (FileName != NULL) {
Cptr = FileName;
} else if (mUtilityName[0] != 0) {
Cptr = mUtilityName;
} else {
Cptr = "Unknown utility";
}
strcpy (Line, Cptr);
if (LineNumber != 0) {
sprintf (Line2, "(%d)", LineNumber);
strcat (Line, Line2);
}
//
// Have to print an error code or Visual Studio won't find the
// message for you. It has to be decimal digits too.
//
sprintf (Line2, " : %s %c%04d", Type, toupper (Type[0]), MessageCode);
strcat (Line, Line2);
fprintf (stdout, "%s", Line);
//
// If offending text was provided, then print it
//
if (Text != NULL) {
fprintf (stdout, ": %s ", Text);
}
//
// Print formatted message if provided
//
if (MsgFmt != NULL) {
vsprintf (Line2, MsgFmt, List);
fprintf (stdout, ": %s", Line2);
}
fprintf (stdout, "\n");
}
void
ParserSetPosition (
INT8 *SourceFileName,
UINT32 LineNum
)
/*++
Routine Description:
Set the position in a file being parsed. This can be used to
print error messages deeper down in a parser.
Arguments:
SourceFileName - name of the source file being parsed
LineNum - line number of the source file being parsed
Returns:
NA
--*/
{
mSourceFileName = SourceFileName;
mSourceFileLineNum = LineNum;
}
void
SetUtilityName (
INT8 *UtilityName
)
/*++
Routine Description:
All printed error/warning/debug messages follow the same format, and
typically will print a filename or utility name followed by the error
text. However if a filename is not passed to the print routines, then
they'll print the utility name if you call this function early in your
app to set the utility name.
Arguments:
UtilityName - name of the utility, which will be printed with all
error/warning/debug messags.
Returns:
NA
--*/
{
//
// Save the name of the utility in our local variable. Make sure its
// length does not exceed our buffer.
//
if (UtilityName != NULL) {
if (strlen (UtilityName) >= sizeof (mUtilityName)) {
Error (UtilityName, 0, 0, "application error", "utility name length exceeds internal buffer size");
strncpy (mUtilityName, UtilityName, sizeof (mUtilityName) - 1);
mUtilityName[sizeof (mUtilityName) - 1] = 0;
return ;
} else {
strcpy (mUtilityName, UtilityName);
}
} else {
Error (NULL, 0, 0, "application error", "SetUtilityName() called with NULL utility name");
}
}
STATUS
GetUtilityStatus (
VOID
)
/*++
Routine Description:
When you call Error() or Warning(), this module keeps track of it and
sets a local mStatus to STATUS_ERROR or STATUS_WARNING. When the utility
exits, it can call this function to get the status and use it as a return
value.
Arguments:
None.
Returns:
Worst-case status reported, as defined by which print function was called.
--*/
{
return mStatus;
}

View File

@@ -0,0 +1,106 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
UtilsMsgs.h
Abstract:
Prototypes for the EFI tools utility functions.
--*/
#ifndef _UTILS_MESSAGES_H_
#define _UTILS_MESSAGES_H_
STATUS
GetUtilityStatus (
VOID
)
;
//
// If someone prints an error message and didn't specify a source file name,
// then we print the utility name instead. However they must tell us the
// utility name early on via this function.
//
VOID
SetUtilityName (
INT8 *ProgramName
)
;
void
Error (
INT8 *FileName,
UINT32 LineNumber,
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
void
Warning (
INT8 *FileName,
UINT32 LineNumber,
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
void
DebugMsg (
INT8 *FileName,
UINT32 LineNumber,
UINT32 MsgLevel,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
void
SetDebugMsgMask (
UINT32 MsgMask
)
;
void
ParserSetPosition (
INT8 *SourceFileName,
UINT32 LineNum
)
;
void
ParserError (
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
void
ParserWarning (
UINT32 ErrorCode,
INT8 *OffendingText,
INT8 *MsgFmt,
...
)
;
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,69 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the MakeDeps utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Target specific information
#
TARGET_NAME = MakeDeps
TARGET_SRC_DIR = $(EDK_TOOLS_SOURCE)\MakeDeps
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\MakeDeps.exe
OBJECTS = $(EDK_TOOLS_OUTPUT)\MakeDeps.obj
LIBS = $(LIBS) $(EDK_TOOLS_OUTPUT)\Common.lib
#
# Build targets
#
all: $(TARGET_EXE)
#
# Compile each tool source file
#
$(OBJECTS) : $(TARGET_SRC_DIR)\MakeDeps.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(TARGET_SRC_DIR)\MakeDeps.c /Fo$@
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE) : $(OBJECTS) $(LIBS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF

View File

@@ -0,0 +1,79 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name: makefile
#
# Abstract:
#
# This file is used to build the EFI build tools.
#
#--*/
#
# Everything depends on EDK_SOURCE. Make sure it's defined
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Define our toolchain before we include the master settings file
#
TOOLCHAIN = TOOLCHAIN_MSVC
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define all the makefiles we want to call
#
MAKEFILES = $(EDK_TOOLS_SOURCE)\Common\Makefile \
$(CUSTOMIZEDCOMPRESS_MAKEFILE) \
$(EDK_TOOLS_SOURCE)\GenCRC32Section\Makefile \
$(EDK_TOOLS_SOURCE)\GenSection\Makefile \
$(EDK_TOOLS_SOURCE)\GenDepex\Makefile \
$(EDK_TOOLS_SOURCE)\GenFfsFile\Makefile \
$(EDK_TOOLS_SOURCE)\GenFvImage\Makefile \
$(EDK_TOOLS_SOURCE)\FwImage\Makefile \
$(EDK_TOOLS_SOURCE)\ProcessDsc\makefile \
$(EDK_TOOLS_SOURCE)\GuidChk\makefile \
$(EDK_TOOLS_SOURCE)\MakeDeps\makefile \
$(EDK_TOOLS_SOURCE)\SetStamp\makefile \
$(EDK_TOOLS_SOURCE)\VfrCompile\makefile \
$(EDK_TOOLS_SOURCE)\StrGather\makefile \
$(EDK_TOOLS_SOURCE)\BootsectImage\Makefile \
$(EDK_TOOLS_SOURCE)\GenBootsector\Makefile \
$(EDK_TOOLS_SOURCE)\GenPage\Makefile \
$(EDK_TOOLS_SOURCE)\SplitFile\Makefile \
$(EDK_TOOLS_SOURCE)\EfiCompress\Makefile \
$(EDK_TOOLS_SOURCE)\EfildrImage\Makefile \
$(EDK_TOOLS_SOURCE)\EfiRom\Makefile \
$(EDK_TOOLS_SOURCE)\GenAprioriFile\Makefile \
$(EDK_TOOLS_SOURCE)\ModifyInf\Makefile
#
# Define default all target which calls all our makefiles. The special
# bang (!) tells nmake to do the command for each out-of-date dependent.
#
# Create the BIN directory, which will only exist if you pull the source tree
# from version control.
#
all : $(MAKEFILES)
-if not exist $(EDK_TOOLS_OUTPUT) mkdir $(EDK_TOOLS_OUTPUT)
!$(MAKE) -f $? TOOLCHAIN=$(TOOLCHAIN) BUILD_DIR=$(BUILD_DIR) all
#
# Call all the tools makefiles with a clean target.
#
clean : $(MAKEFILES)
!$(MAKE) -f $? TOOLCHAIN=$(TOOLCHAIN) clean

View File

@@ -0,0 +1,82 @@
#/*++
#
# Copyright (c) 2001 - 2006 Intel Corporation.
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Target specific information
#
TARGET_NAME = ModifyInf
TARGET_SRC_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SRC_DIR)\ModifyInf.c"
TARGET_EXE_INCLUDE =
OBJECTS = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE) : $(OBJECTS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,322 @@
/*++
Copyright (c) 1999 - 2002 Intel Corporation.
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
ModifyInf.c
Abstract:
It is a simple tool to modify some fields in a FV inf file
and output a new FV inf file.
--*/
#include "stdio.h"
#include "string.h"
//
// Read a line into buffer including '\r\n'
//
int
ReadLine (
char *LineBuffer,
FILE *fp
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
LineBuffer - GC_TODO: add argument description
fp - GC_TODO: add argument description
Returns:
GC_TODO: add return values
--*/
{
int CharC;
char *Line;
Line = LineBuffer;
while ((CharC = fgetc (fp)) != EOF) {
*Line++ = (char) CharC;
if (CharC == 0x0a) {
break;
}
}
*Line = 0;
if (CharC == EOF) {
return 0;
} else {
return 1;
}
}
//
// Write a line into output file
//
int
WriteLine (
char *Line,
FILE *fp
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
Line - GC_TODO: add argument description
fp - GC_TODO: add argument description
Returns:
GC_TODO: add return values
--*/
{
fwrite (Line, strlen (Line), 1, fp);
return 0;
}
//
// Apply patterns to a line
// Currently there are 2 patterns to support
// '==' replace a field value with a new value
// '+=' append a string at the end of original line
// '-' prevent the line from applying any patterns
// it has the highest priority
//
int
ApplyPattern (
char *Line,
char *argv[],
int argc
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
Line - GC_TODO: add argument description
] - GC_TODO: add argument description
argc - GC_TODO: add argument description
Returns:
GC_TODO: add return values
--*/
{
static char Section[256];
int SectionLength;
char PatternBuffer[256];
char *Pattern;
char *Pattern1;
char *Pattern2;
int PatternNum;
char *Ptr;
Pattern = PatternBuffer;
PatternNum = argc;
//
// For section field
// record current scope section into static buffer
//
Ptr = Line;
if (*Ptr == '[') {
while (*Ptr != ']') {
if (!(*Ptr++)) {
return -1;
}
}
SectionLength = Ptr - Line + 1;
SectionLength = SectionLength > 255 ? 255 : SectionLength;
strncpy (Section, Line, SectionLength);
Section[SectionLength] = 0;
}
//
// Apply each pattern on the line
//
while (PatternNum-- > 3) {
strcpy (Pattern, argv[PatternNum]);
//
// For pattern '-'
// keep it unmodified by other patterns
//
if (*Pattern == '-') {
if (strstr (Line, Pattern + 1)) {
return 0;
} else {
continue;
}
}
//
// For other patterns
// get its section at first if it has
//
if (*Pattern == '[') {
if (strncmp (Section, Pattern, strlen (Section))) {
//
// This pattern can't be appied for current section
//
continue;
}
//
// Strip the section field
//
while (*Pattern != ']') {
if (!(*Pattern++)) {
return -1;
}
}
Pattern++;
}
//
// Apply patterns
//
Pattern1 = strstr (Pattern, "==");
Pattern2 = strstr (Pattern, "+=");
if (Pattern1) {
//
// For pattern '=='
// replace the field value with a new string
//
if (!strncmp (Line, Pattern, Pattern1 - Pattern)) {
Pattern1 += 2;
Ptr = strstr (Line, "=");
if (!Ptr) {
return -1;
}
while (*(++Ptr) == ' ')
;
*Ptr = 0;
strcat (Line, Pattern1);
strcat (Line, "\r\n");
}
} else if (Pattern2) {
//
// For pattern '+='
// append a string at end of the original string
//
if (!strncmp (Line, Pattern, Pattern2 - Pattern)) {
Pattern2 += 2;
Ptr = Line;
while (*Ptr != 0x0D && *Ptr != 0x0A) {
Ptr++;
}
*Ptr = 0;
strcat (Line, Pattern2);
strcat (Line, "\r\n");
}
}
}
return 0;
}
void
Usage (
void
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
None
Returns:
GC_TODO: add return values
--*/
{
printf ("ModifyInf InputFVInfFileName OutputFVInfFileName [Pattern strings]\r\n");
}
int
main (
int argc,
char*argv[]
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
argc - GC_TODO: add argument description
] - GC_TODO: add argument description
Returns:
GC_TODO: add return values
--*/
{
char LineBuffer[256];
FILE *fpin;
FILE *fpout;
if (argc < 3) {
Usage ();
return -1;
}
fpin = fopen (argv[1], "rb");
if (!fpin) {
printf ("Can't open input file!\r\n");
return -1;
}
fpout = fopen (argv[2], "wb");
if (!fpout) {
fclose (fpin);
printf ("Can't create output file!\r\n");
return -1;
}
while (ReadLine (LineBuffer, fpin)) {
ApplyPattern (LineBuffer, argv, argc);
WriteLine (LineBuffer, fpout);
}
fclose (fpin);
fclose (fpout);
return 0;
}

View File

@@ -0,0 +1,123 @@
/*++
Copyright (c) 2004 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
Common.h
Abstract:
Common include file for the ProcessDsc utility.
--*/
#ifndef _COMMON_H_
#define _COMMON_H_
typedef char INT8;
typedef unsigned int UINT32;
#include "EfiUtilityMsgs.h"
#define MAX_LINE_LEN 1024
#ifdef MAX_PATH
#undef MAX_PATH
#define MAX_PATH 1024
#endif
//
// Defines for how to expand symbols
//
#define EXPANDMODE_NO_UNDEFS 0x01
#define EXPANDMODE_NO_DESTDIR 0x02
#define EXPANDMODE_NO_SOURCEDIR 0x04
#define EXPANDMODE_RECURSIVE 0x08
//
// Defines for adding symbols
//
#define SYM_OVERWRITE 0x01 // overwrite existing assignments
#define SYM_GLOBAL 0x02 // global symbol (persistent)
#define SYM_LOCAL 0x04 // symbols at component level
#define SYM_FILE 0x08 // symbols at file level
#define SYM_FILEPATH 0x10 // symbol is a file path
#define SYM_FILENAME 0x20 // symbol is a file name
#define FV_DIR "FV_DIR" // symbol for base dir where FV files are
#define DSC_FILENAME "DSC_FILENAME"
//
// Smart file for better incremental build support.
// Only re-create .pkg .inf or .apr files when it's content is changed.
//
//
typedef struct _SMART_FILE {
char *FileName;
char *FileContent; // Previous file content
int FileLength; // Previous file string length
int FilePosition; // The offset from FileContent for next comparison
FILE *FilePtr; // New file pointer if the file need to be re-created
} SMART_FILE;
SMART_FILE *
SmartOpen (
char *FileName
);
int
SmartWrite (
SMART_FILE *SmartFile,
char *String
);
void
SmartClose (
SMART_FILE *SmartFile
);
INT8 *
GetSymbolValue (
INT8 *SymbolName
);
int
AddSymbol (
INT8 *Name,
INT8 *Value,
int Mode
);
int
ExpandSymbols (
INT8 *SourceLine,
INT8 *DestLine,
int LineLen,
int ExpandMode
);
void
Message (
UINT32 PrintMask,
INT8 *Fmt,
...
);
int
MakeFilePath (
INT8 *FileName
);
int
IsAbsolutePath (
INT8 *FileName
);
#endif // ifndef _COMMON_H_

View File

@@ -0,0 +1,534 @@
/*++
Copyright (c) 2004 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
DscFile.c
Abstract:
This module is used to process description files at a high level. For the
most part, it pre-parses the file to find and save off positions of all
the sections ([section.subsection.subsection]) in a linked list, then
provides services to find the sections by name, and read the lines from
the section until you run into the next section.
NOTE: DSC file is synonomous with section file. A DSC file is simply a file
containing bracketed section names [section.subsection.subsection...]
--*/
#include <stdio.h> // for file ops
#include <string.h>
#include <ctype.h>
#include <stdlib.h> // for malloc
#include "Common.h"
#include "DSCFile.h"
#define MAX_INCLUDE_NEST_LEVEL 20
static
void
DSCFileFree (
DSC_FILE *DSC
);
static
STATUS
DSCParseInclude (
DSC_FILE *DSC,
char *FileName,
int NestLevel
);
//
// Constructor for a DSC file
//
int
DSCFileInit (
DSC_FILE *DSC
)
{
memset ((char *) DSC, 0, sizeof (DSC_FILE));
DSC->SavedPositionIndex = -1;
return STATUS_SUCCESS;
}
//
// Destructor for a DSC file
//
int
DSCFileDestroy (
DSC_FILE *DSC
)
{
DSC->SavedPositionIndex = -1;
DSCFileFree (DSC);
return STATUS_SUCCESS;
}
//
// Get the next line from a DSC file.
//
char *
DSCFileGetLine (
DSC_FILE *DSC,
char *Line,
int LineLen
)
{
char *Cptr;
if (DSC->CurrentLine == NULL) {
return NULL;
}
//
// Check for running into next section
//
if (DSC->CurrentLine->Line[0] == '[') {
return NULL;
}
//
// Allow special case where the line starts with backslash-bracket. If we
// see this, then shift everything left one character.
//
if ((DSC->CurrentLine->Line[0] == '\\') && (DSC->CurrentLine->Line[1] == '[')) {
Cptr = DSC->CurrentLine->Line + 1;
} else {
Cptr = DSC->CurrentLine->Line;
}
strncpy (Line, Cptr, LineLen);
ParserSetPosition (DSC->CurrentLine->FileName, DSC->CurrentLine->LineNum);
DSC->CurrentLine = DSC->CurrentLine->Next;
return Line;
}
int
DSCFileSetFile (
DSC_FILE *DSC,
char *FileName
)
/*++
Routine Description:
Pre-scan a section file to find all the sections. Then we can speed up
searching for the different sections.
Arguments:
DSC - pointer to a DSC structure (this pointer)
FileName - name of the file to process
Returns:
STATUS_SUCCESS if everything went well.
--*/
{
STATUS Status;
//
// Called to open a new sectioned file.
//
Status = DSCParseInclude (DSC, FileName, 1);
return Status;
}
static
STATUS
DSCParseInclude (
DSC_FILE *DSC,
char *FileName,
int NestLevel
)
{
SECTION *NewSect;
SECTION_LINE *NewLine;
DSC_FILE_NAME *NewDscFileName;
char Line[MAX_LINE_LEN];
char *Start;
char *End;
char SaveChar;
char *TempCptr;
char ShortHandSectionName[MAX_LINE_LEN];
char ThisSectionName[MAX_LINE_LEN];
SECTION *CurrSect;
SECTION *TempSect;
FILE *FilePtr;
STATUS Status;
UINT32 LineNum;
//
// Make sure we haven't exceeded our maximum nesting level
//
if (NestLevel > MAX_INCLUDE_NEST_LEVEL) {
Error (NULL, 0, 0, "application error", "maximum !include nesting level exceeded");
return STATUS_ERROR;
}
//
// Try to open the file
//
if ((FilePtr = fopen (FileName, "r")) == NULL) {
//
// This function is called to handle the DSC file from the command line too,
// so differentiate whether this file is an include file or the main file
// by examining the nest level.
//
if (NestLevel == 1) {
Error (NULL, 0, 0, FileName, "could not open DSC file for reading");
} else {
Error (NULL, 0, 0, FileName, "could not open !include DSC file for reading");
}
return STATUS_ERROR;
}
//
// We keep a linked list of files we parse for error reporting purposes.
//
NewDscFileName = malloc (sizeof (DSC_FILE_NAME));
if (NewDscFileName == NULL) {
Error (__FILE__, __LINE__, 0, "memory allocation failed", NULL);
return STATUS_ERROR;
}
memset (NewDscFileName, 0, sizeof (DSC_FILE_NAME));
NewDscFileName->FileName = (INT8 *) malloc (strlen (FileName) + 1);
if (NewDscFileName->FileName == NULL) {
Error (__FILE__, __LINE__, 0, "memory allocation failed", NULL);
return STATUS_ERROR;
}
strcpy (NewDscFileName->FileName, FileName);
if (DSC->FileName == NULL) {
DSC->FileName = NewDscFileName;
} else {
DSC->LastFileName->Next = NewDscFileName;
}
DSC->LastFileName = NewDscFileName;
//
// Read lines and process until done
//
Status = STATUS_SUCCESS;
LineNum = 0;
for (;;) {
if (fgets (Line, sizeof (Line), FilePtr) == NULL) {
break;
}
LineNum++;
ParserSetPosition (FileName, LineNum);
//
// Add the line to our list if it's not a !include line
//
if ((strncmp (Line, "!include", 8) == 0) && (isspace (Line[8]))) {
Start = Line + 9;
while (*Start && (*Start != '"')) {
Start++;
}
if (*Start != '"') {
Error (FileName, LineNum, 0, NULL, "invalid format for !include");
Status = STATUS_ERROR;
goto Done;
}
Start++;
for (End = Start; *End && (*End != '"'); End++)
;
if (*End != '"') {
Error (FileName, LineNum, 0, NULL, "invalid format for !include");
Status = STATUS_ERROR;
goto Done;
}
*End = 0;
//
// Expand symbols. Use 'ThisSectionName' as scratchpad
//
ExpandSymbols (Start, ThisSectionName, sizeof (ThisSectionName), EXPANDMODE_NO_UNDEFS);
Status = DSCParseInclude (DSC, ThisSectionName, NestLevel + 1);
if (Status != STATUS_SUCCESS) {
Error (FileName, LineNum, 0, NULL, "failed to parse !include file");
goto Done;
}
} else {
NewLine = (SECTION_LINE *) malloc (sizeof (SECTION_LINE));
if (NewLine == NULL) {
Error (NULL, 0, 0, NULL, "failed to allocate memory");
Status = STATUS_ERROR;
goto Done;
}
memset ((char *) NewLine, 0, sizeof (SECTION_LINE));
NewLine->LineNum = LineNum;
NewLine->FileName = NewDscFileName->FileName;
NewLine->Line = (char *) malloc (strlen (Line) + 1);
if (NewLine->Line == NULL) {
Error (NULL, 0, 0, NULL, "failed to allocate memory");
Status = STATUS_ERROR;
goto Done;
}
strcpy (NewLine->Line, Line);
if (DSC->Lines == NULL) {
DSC->Lines = NewLine;
} else {
DSC->LastLine->Next = NewLine;
}
DSC->LastLine = NewLine;
//
// Parse the line for []. Ignore [] and [----] delimiters. The
// line may have multiple definitions separated by commas, so
// take each separately
//
Start = Line;
if ((Line[0] == '[') && ((Line[1] != ']') && (Line[1] != '-'))) {
//
// Skip over open bracket and preceeding spaces
//
Start++;
ShortHandSectionName[0] = 0;
while (*Start && (*Start != ']')) {
while (isspace (*Start)) {
Start++;
}
//
// Hack off closing bracket or trailing spaces or comma separator.
// Also allow things like [section.subsection1|subsection2], which
// is shorthand for [section.subsection1,section.subsection2]
//
End = Start;
while (*End && (*End != ']') && !isspace (*End) && (*End != ',') && (*End != '|')) {
End++;
}
//
// Save the character and null-terminate the string
//
SaveChar = *End;
*End = 0;
//
// Now allocate space for a new section and add it to the linked list.
// If the previous section ended with the shorthand indicator, then
// the section name was saved off. Append this section name to it.
//
strcpy (ThisSectionName, ShortHandSectionName);
if (*Start == '.') {
strcat (ThisSectionName, Start + 1);
} else {
strcat (ThisSectionName, Start);
}
//
// Allocate memory for the section. Then clear it out.
//
NewSect = (SECTION *) malloc (sizeof (SECTION));
if (NewSect == NULL) {
Error (NULL, 0, 0, NULL, "failed to allocation memory for sections");
Status = STATUS_ERROR;
goto Done;
}
memset ((char *) NewSect, 0, sizeof (SECTION));
NewSect->FirstLine = NewLine;
NewSect->Name = (char *) malloc (strlen (ThisSectionName) + 1);
if (NewSect->Name == NULL) {
Error (NULL, 0, 0, NULL, "failed to allocation memory for sections");
Status = STATUS_ERROR;
goto Done;
}
strcpy (NewSect->Name, ThisSectionName);
if (DSC->Sections == NULL) {
DSC->Sections = NewSect;
} else {
DSC->LastSection->Next = NewSect;
}
DSC->LastSection = NewSect;
*End = SaveChar;
//
// If the name ended in a shorthand indicator, then save the
// section name and truncate it at the last dot.
//
if (SaveChar == '|') {
strcpy (ShortHandSectionName, ThisSectionName);
for (TempCptr = ShortHandSectionName + strlen (ShortHandSectionName) - 1;
(TempCptr != ShortHandSectionName) && (*TempCptr != '.');
TempCptr--
)
;
//
// If we didn't find a dot, then hopefully they have [name1|name2]
// instead of [name1,name2].
//
if (TempCptr == ShortHandSectionName) {
ShortHandSectionName[0] = 0;
} else {
//
// Truncate after the dot
//
*(TempCptr + 1) = 0;
}
} else {
//
// Kill the shorthand string
//
ShortHandSectionName[0] = 0;
}
//
// Skip to next section name or closing bracket
//
while (*End && ((*End == ',') || isspace (*End) || (*End == '|'))) {
End++;
}
Start = End;
}
}
}
}
//
// Look through all the sections to make sure we don't have any duplicates.
// Allow [----] and [====] section separators
//
CurrSect = DSC->Sections;
while (CurrSect != NULL) {
TempSect = CurrSect->Next;
while (TempSect != NULL) {
if (isalpha (CurrSect->Name[0]) && (_stricmp (CurrSect->Name, TempSect->Name) == 0)) {
Error (
TempSect->FirstLine->FileName,
TempSect->FirstLine->LineNum,
0,
TempSect->Name,
"duplicate section found"
);
Error (
CurrSect->FirstLine->FileName,
CurrSect->FirstLine->LineNum,
0,
TempSect->Name,
"first definition of duplicate section"
);
Status = STATUS_ERROR;
goto Done;
}
TempSect = TempSect->Next;
}
CurrSect = CurrSect->Next;
}
Done:
fclose (FilePtr);
return Status;
}
//
// Free up memory allocated for DSC file handling.
//
static
void
DSCFileFree (
DSC_FILE *DSC
)
{
SECTION *NextSection;
SECTION_LINE *NextLine;
DSC_FILE_NAME *NextName;
while (DSC->Sections != NULL) {
NextSection = DSC->Sections->Next;
if (DSC->Sections->Name != NULL) {
free (DSC->Sections->Name);
}
free (DSC->Sections);
DSC->Sections = NextSection;
}
while (DSC->Lines != NULL) {
NextLine = DSC->Lines->Next;
free (DSC->Lines->Line);
free (DSC->Lines);
DSC->Lines = NextLine;
}
while (DSC->FileName != NULL) {
NextName = DSC->FileName->Next;
free (DSC->FileName->FileName);
free (DSC->FileName);
DSC->FileName = NextName;
}
}
SECTION *
DSCFileFindSection (
DSC_FILE *DSC,
char *Name
)
{
SECTION *Sect;
//
// Look through all the sections to find one with this name (case insensitive)
//
Sect = DSC->Sections;
while (Sect != NULL) {
if (_stricmp (Name, Sect->Name) == 0) {
//
// Position within file
//
DSC->CurrentLine = Sect->FirstLine->Next;
return Sect;
}
Sect = Sect->Next;
}
return NULL;
}
int
DSCFileSavePosition (
DSC_FILE *DSC
)
{
//
// Advance to next slot
//
DSC->SavedPositionIndex++;
if (DSC->SavedPositionIndex >= MAX_SAVES) {
DSC->SavedPositionIndex--;
Error (NULL, 0, 0, "APP ERROR", "max nesting of saved section file positions exceeded");
return STATUS_ERROR;
}
DSC->SavedPosition[DSC->SavedPositionIndex] = DSC->CurrentLine;
return STATUS_SUCCESS;
}
int
DSCFileRestorePosition (
DSC_FILE *DSC
)
{
if (DSC->SavedPositionIndex < 0) {
Error (NULL, 0, 0, "APP ERROR", "underflow of saved positions in section file");
return STATUS_ERROR;
}
DSC->CurrentLine = DSC->SavedPosition[DSC->SavedPositionIndex];
DSC->SavedPositionIndex--;
return STATUS_SUCCESS;
}

View File

@@ -0,0 +1,109 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
DscFile.h
Abstract:
Defines and function prototypes for the ProcessDsc utility.
--*/
#ifndef _DSC_FILE_H_
#define _DSC_FILE_H_
typedef struct _SECTION_LINE {
struct _SECTION_LINE *Next;
char *Line;
char *FileName;
UINT32 LineNum;
} SECTION_LINE;
//
// Use this structure to keep track of parsed file names. Then
// if we get a parse error we can figure out the file/line of
// the error and print a useful message.
//
typedef struct _DSC_FILE_NAME {
struct _DSC_FILE_NAME *Next;
char *FileName;
} DSC_FILE_NAME;
//
// We create a list of section names when we pre-parse a description file.
// Use this structure.
//
typedef struct _SECTION {
struct _SECTION *Next;
char *Name;
SECTION_LINE *FirstLine;
} SECTION;
#define MAX_SAVES 4
typedef struct {
SECTION_LINE *SavedPosition[MAX_SAVES];
int SavedPositionIndex;
SECTION *Sections;
SECTION_LINE *Lines;
SECTION *LastSection;
SECTION_LINE *LastLine;
SECTION_LINE *CurrentLine;
DSC_FILE_NAME *FileName;
DSC_FILE_NAME *LastFileName;
} DSC_FILE;
//
// Function prototypes
//
int
DSCFileSetFile (
DSC_FILE *DSC,
char *FileName
)
;
SECTION *
DSCFileFindSection (
DSC_FILE *DSC,
char *Name
)
;
int
DSCFileSavePosition (
DSC_FILE *DSC
)
;
int
DSCFileRestorePosition (
DSC_FILE *DSC
)
;
char *
DSCFileGetLine (
DSC_FILE *DSC,
char *Line,
int LineLen
)
;
int
DSCFileInit (
DSC_FILE *DSC
)
;
int
DSCFileDestroy (
DSC_FILE *DSC
)
;
#endif // ifndef _DSC_FILE_H_

View File

@@ -0,0 +1,141 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
Exceptions.c
Abstract:
Exception logging routines.
--*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // for memset()
#include "Exceptions.h"
//
// Max length of a saved exception message
//
#define MAX_EXCEPTION_MSG 200
//
// We use this structure to track exceptions thrown. We nest deeper on
// TryException() calls, and come back out on CatchException() calls.
// We save off the first exception message for a given exception level,
// but we save the count of how many were thrown.
//
typedef struct {
int ExceptionCount;
char ExceptionMsg[MAX_EXCEPTION_MSG];
} EXCEPTION_LOG;
static EXCEPTION_LOG ExceptionLog[MAX_EXCEPTION_NESTING + 1];
static int ExceptionLevel;
//
// Initialize our data and structures for tracking exceptions.
//
int
InitExceptions (
VOID
)
{
ExceptionLevel = -1;
memset ((char *) &ExceptionLog, 0, sizeof (ExceptionLog));
return 0;
}
//
// This function replaces the _try() exception macro. It sets the
// nesting level.
//
int
TryException (
VOID
)
{
//
// Boost our exception level if we would not go out of range
//
ExceptionLevel++;
if (ExceptionLevel >= MAX_EXCEPTION_NESTING) {
fprintf (stderr, "ERROR: Max exception nesting level exceeded\n");
ExceptionLevel--;
return 1;
}
return 0;
}
//
// This function replaces the _catch() exception macro. It's used to decrement
// the nesting level and return any exeption error messages that were
// thrown at the current nesting level.
//
char *
CatchException (
VOID
)
{
//
// Return a pointer to exception message. NULL if no exceptions at this level
//
if (ExceptionLevel >= 0) {
ExceptionLevel--;
if (ExceptionLog[ExceptionLevel + 1].ExceptionMsg[0]) {
return ExceptionLog[ExceptionLevel + 1].ExceptionMsg;
} else {
return NULL;
}
} else {
fprintf (stderr, "ERROR: Invalid nesting level call to CatchException()\n");
return NULL;
}
}
//
// This function can be used to test for exceptions between the TryException()
// and CatchException() calls in a given function.
//
int
ExceptionThrown (
VOID
)
{
return ExceptionLog[ExceptionLevel].ExceptionCount;
}
//
// This function replaces the _throw() exception macro. It saves off the
// given error message at the current exeption level nesting.
//
int
ThrowException (
char *Msg
)
{
if (ExceptionLevel < 0) {
//
// fprintf (stderr, "ERROR: Exception thrown out of scope");
// Haven't yet enabled handling of exceptions, so just emit the message.
//
fprintf (stderr, Msg);
return 1;
}
//
// Only log the first
//
if (ExceptionLog[ExceptionLevel].ExceptionMsg[0] == 0) {
strncpy (ExceptionLog[ExceptionLevel].ExceptionMsg, Msg, MAX_EXCEPTION_MSG);
}
ExceptionLog[ExceptionLevel].ExceptionCount++;
return 0;
}

View File

@@ -0,0 +1,57 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
Exceptions.h
Abstract:
Defines and function prototypes for the ProcessDsc utility.
--*/
#ifndef _EXCEPTIONS_H_
#define _EXCEPTIONS_H_
#define VOID void
#define MAX_EXCEPTION_NESTING 4
//
// Function prototypes
//
int
InitExceptions (
VOID
)
;
int
TryException (
VOID
)
;
char *
CatchException (
VOID
)
;
int
ExceptionThrown (
VOID
)
;
int
ThrowException (
char *EMsg
)
;
#endif // ifndef _EXCEPTIONS_H_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,76 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
FWVolume.h
Abstract:
Include file for the module that keeps track of files for the firmware
volumes.
--*/
#ifndef _FW_VOLUME_H_
#define _FW_VOLUME_H_
//
// class CFirmwareVolume
// {
// public:
//
void
CFVConstructor (
VOID
)
;
void
CFVDestructor (
VOID
)
;
int
CFVAddFVFile (
char *Name,
char *ComponentType,
char *FVs,
int ComponentsInstance,
char *FFSExt,
char *Processor,
char *Apriori,
char *BaseName,
char *Guid
)
;
int
CFVSetXRefFileName (
char *FileName
)
;
int
CFVWriteInfFiles (
DSC_FILE *DSC,
FILE *MakeFptr
)
;
int
NonFFSFVWriteInfFiles (
DSC_FILE *DSC,
char *FileName
)
;
#endif // ifndef _FW_VOLUME_H_

View File

@@ -0,0 +1,102 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the ProcessDsc utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Target specific information
#
TARGET_NAME = ProcessDsc
TARGET_SRC_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\ProcessDsc.exe
#
# Build targets
#
all: $(TARGET_EXE)
INC_DEPS = $(TARGET_SRC_DIR)\DSCFile.h $(INC_DEPS)
INC_DEPS = $(TARGET_SRC_DIR)\FWVolume.h $(INC_DEPS)
INC_DEPS = $(TARGET_SRC_DIR)\Exceptions.h $(INC_DEPS)
INC_DEPS = $(TARGET_SRC_DIR)\Common.h $(INC_DEPS)
LIBS = $(LIBS) "$(EDK_TOOLS_OUTPUT)\Common.lib"
OBJECTS = $(EDK_TOOLS_OUTPUT)\DSCFile.obj \
$(EDK_TOOLS_OUTPUT)\FWVolume.obj \
$(EDK_TOOLS_OUTPUT)\ProcessDsc.obj \
$(EDK_TOOLS_OUTPUT)\Exceptions.obj
#
# Compile each source file
#
$(EDK_TOOLS_OUTPUT)\DSCFile.obj : $(TARGET_SRC_DIR)\DSCFile.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(TARGET_SRC_DIR)\DSCFile.c /Fo$@
$(EDK_TOOLS_OUTPUT)\FWVolume.obj : $(TARGET_SRC_DIR)\FWVolume.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(TARGET_SRC_DIR)\FWVolume.c /Fo$@
$(EDK_TOOLS_OUTPUT)\ProcessDsc.obj : $(TARGET_SRC_DIR)\ProcessDsc.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(TARGET_SRC_DIR)\ProcessDsc.c /Fo$@
$(EDK_TOOLS_OUTPUT)\Exceptions.obj : $(TARGET_SRC_DIR)\Exceptions.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(TARGET_SRC_DIR)\Exceptions.c /Fo$@
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE) : $(OBJECTS) $(LIBS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\DscFile.* del $(EDK_TOOLS_OUTPUT)\DscFile.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\Exceptions* del $(EDK_TOOLS_OUTPUT)\Exceptions.* > NUL
@if exist $(EDK_TOOLS_OUTPUT)\FwVolume.* del $(EDK_TOOLS_OUTPUT)\FwVolume.* > NUL

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=SetStamp
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\SetStamp.c"
TARGET_EXE_INCLUDE =
OBJECTS = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE) : $(OBJECTS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).*

View File

@@ -0,0 +1,475 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
SetStamp.c
Abstract:
Set Date/Time Stamp of Portable Executable (PE) format file
--*/
#include <stdio.h>
#include <string.h>
#include <time.h>
#define LINE_MAXLEN 80
void
PrintUsage (
void
)
/*++
Routine Description:
print usage of setstamp command
Arguments:
void
Returns:
None
--*/
{
//
// print usage of command
//
printf ("Usage: SetStamp <PE-File> <TIME-File>\n");
}
int
GetDateTime (
FILE *fp,
time_t *ltime
)
/*++
Routine Description:
Read the date and time from TIME file. If the date/time string is
"NOW NOW", write the current date and time to TIME file and set it to
ltime. Else, set the date and time of TIME file to ltime.
Arguments:
fp - The pointer of TIME file
ltime - Date and time
Returns:
= 0 - Success
= -1 - Failed
--*/
{
char buffer[LINE_MAXLEN];
struct tm stime;
struct tm *now;
if (fgets (buffer, LINE_MAXLEN, fp) == NULL) {
printf ("Error: Cannot read TIME file.\n");
return -1;
}
//
// compare the value with "NOW NOW", write TIME file if equal
//
if (strncmp (buffer, "NOW NOW", 7) == 0) {
//
// get system current time and date
//
time (ltime);
now = localtime (ltime);
if (now == NULL) {
printf ("Error: Cannot get local time.\n");
return -1;
}
if (strftime (buffer, LINE_MAXLEN, "%Y-%m-%d %H:%M:%S", now) == 0) {
printf ("Error: Cannot format time string.\n");
return -1;
}
//
// write TIME file
//
if (fseek (fp, 0, SEEK_SET) != 0) {
printf ("Error: Cannot move location of TIME file.\n");
return -1;
}
if (fputs (buffer, fp) == EOF) {
printf ("Error: Cannot write time string to TIME file.\n");
return -1;
}
//
// ltime has been set as current time and date, return
//
return 0;
}
//
// get the date and time from buffer
//
if (6 != sscanf (
buffer,
"%d-%d-%d %d:%d:%d",
&stime.tm_year,
&stime.tm_mon,
&stime.tm_mday,
&stime.tm_hour,
&stime.tm_min,
&stime.tm_sec
)) {
printf ("Error: Invaild date or time!\n");
return -1;
}
//
// in struct, Month (0 - 11; Jan = 0). So decrease 1 from it
//
stime.tm_mon -= 1;
//
// in struct, Year (current year minus 1900)
// and only the dates can be handled from Jan 1, 1970 to Jan 18, 2038
//
//
// convert 0 -> 100 (2000), 1 -> 101 (2001), ..., 38 -> 138 (2038)
//
if (stime.tm_year <= 38) {
stime.tm_year += 100;
}
//
// convert 1970 -> 70, 2000 -> 100, ...
//
else if (stime.tm_year >= 1970) {
stime.tm_year -= 1900;
}
//
// convert the date and time to time_t format
//
*ltime = mktime (&stime);
if (*ltime == (time_t) - 1) {
printf ("Error: Invalid date or time!\n");
return -1;
}
return 0;
}
int
ReadFromFile (
FILE *fp,
long offset,
void *buffer,
int size
)
/*++
Routine Description:
read data from a specified location of file
Arguments:
fp - file pointer
offset - number of bytes from beginning of file
buffer - buffer used to store data
size - size of buffer
Returns:
= 0 - Success
= -1 - Failed
--*/
{
//
// set file pointer to the specified location of file
//
if (fseek (fp, offset, SEEK_SET) != 0) {
printf ("Error: Cannot move the current location of the file.\n");
return -1;
}
//
// read data from the file
//
if (fread (buffer, size, 1, fp) != 1) {
printf ("Error: Cannot read data from the file.\n");
return -1;
}
return 0;
}
int
WriteToFile (
FILE *fp,
long offset,
void *buffer,
int size
)
/*++
Routine Description:
write data to a specified location of file
Arguments:
fp - file pointer
offset - number of bytes from beginning of file
buffer - buffer used to store data
size - size of buffer
Returns:
= 0 - Success
= -1 - Failed
--*/
{
//
// set file pointer to the specified location of file
//
if (fseek (fp, offset, SEEK_SET) != 0) {
printf ("Error: Cannot move the current location of the file.\n");
return -1;
}
//
// write data to the file
//
if (fwrite (buffer, size, 1, fp) != 1) {
perror ("Error: Cannot write data to the file.\n");
return -1;
}
return 0;
}
int
SetStamp (
FILE *fp,
time_t ltime
)
/*++
Routine Description:
set Date/Time Stamp of the file
Arguments:
fp - file pointer
ltime - time and date
Returns:
= 0 - Success
= -1 - Failed
--*/
{
unsigned char header[4];
unsigned long offset;
unsigned long NumberOfRvaAndSizes;
unsigned int nvalue;
unsigned long lvalue;
//
// read the header of file
//
if (ReadFromFile (fp, 0, header, 2) != 0) {
return -1;
}
//
// "MZ" -- the header of image file (PE)
//
if (strncmp ((char *) header, "MZ", 2) != 0) {
printf ("Error: Invalid Image file.\n");
return -1;
}
//
// At location 0x3C, the stub has the file offset to the
// PE signature.
//
if (ReadFromFile (fp, 0x3C, &offset, 4) != 0) {
return -1;
}
//
// read the header of optional
//
if (ReadFromFile (fp, offset, header, 4) != 0) {
return -1;
}
//
// "PE\0\0" -- the signature of optional header
//
if (strncmp ((char *) header, "PE\0\0", 4) != 0) {
printf ("Error: Invalid PE format file.\n");
return -1;
}
//
// Add 8 to skip PE signature (4-byte), Machine (2-byte) and
// NumberOfSection (2-byte)
//
offset += 8;
if (WriteToFile (fp, offset, &ltime, 4) != 0) {
return -1;
}
//
// Add 16 to skip COFF file header, and get to optional header.
//
offset += 16;
//
// Check the magic field, 0x10B for PE32 and 0x20B for PE32+
//
if (ReadFromFile (fp, offset, &nvalue, 2) != 0) {
return -1;
}
//
// If this is PE32 image file, offset of NumberOfRvaAndSizes is 92.
// Else it is 108.
//
switch (nvalue & 0xFFFF) {
case 0x10B:
offset += 92;
break;
case 0x20B:
offset += 108;
break;
default:
printf ("Error: Sorry! The Magic value is unknown.\n");
return -1;
}
//
// get the value of NumberOfRvaAndSizes
//
if (ReadFromFile (fp, offset, &NumberOfRvaAndSizes, 4) != 0) {
return -1;
}
//
// Date/time stamp exists in Export Table, Import Table, Resource Table,
// Debug Table and Delay Import Table. And in Import Table and Delay Import
// Table, it will be set when bound. So here only set the date/time stamp
// of Export Table, Resource Table and Debug Table.
//
//
// change date/time stamp of Export Table, the offset of Export Table
// is 4 + 0 * 8 = 4. And the offset of stamp is 4.
//
if (NumberOfRvaAndSizes >= 1) {
if (ReadFromFile (fp, offset + 4, &lvalue, 4) != 0) {
return -1;
}
if (lvalue != 0) {
if (WriteToFile (fp, lvalue + 4, &ltime, 4) != 0) {
return -1;
}
}
}
//
// change date/time stamp of Resource Table, the offset of Resource Table
// is 4 + 2 * 8 = 20. And the offset of stamp is 4.
//
if (NumberOfRvaAndSizes >= 3) {
if (ReadFromFile (fp, offset + 20, &lvalue, 4) != 0) {
return -1;
}
if (lvalue != 0) {
if (WriteToFile (fp, lvalue + 4, &ltime, 4) != 0) {
return -1;
}
}
}
//
// change date/time stamp of Debug Table, offset of Debug Table
// is 4 + 6 * 8 = 52. And the offset of stamp is 4.
//
if (NumberOfRvaAndSizes >= 7) {
if (ReadFromFile (fp, offset + 52, &lvalue, 4) != 0) {
return -1;
}
if (lvalue != 0) {
if (WriteToFile (fp, lvalue + 4, &ltime, 4) != 0) {
return -1;
}
}
//
// change the date/time stamp of Debug Data
//
if (ReadFromFile (fp, lvalue + 24, &lvalue, 4) != 0) {
return -1;
}
//
// get the signature of debug data
//
if (ReadFromFile (fp, lvalue, header, 2) != 0) {
return -1;
}
//
// "NB" - the signature of Debug Data
// Need Review: (From Spec. is "NB05", From .dll is "NB10")
//
if (strncmp ((char *) header, "NB", 2) == 0) {
if (WriteToFile (fp, lvalue + 8, &ltime, 4) != 0) {
return -1;
}
}
}
return 0;
}
int
main (
int argc,
char *argv[]
)
{
FILE *fp;
time_t ltime;
//
// check the number of parameters
//
if (argc != 3) {
PrintUsage ();
return -1;
}
//
// open the TIME file, if not exists, return
//
fp = fopen (argv[2], "r+");
if (fp == NULL) {
return 0;
}
//
// get time and date from file
//
if (GetDateTime (fp, &ltime) != 0) {
fclose (fp);
return -1;
}
//
// close the TIME file
//
fclose (fp);
//
// open the PE file
//
fp = fopen (argv[1], "r+b");
if (fp == NULL) {
printf ("Error: Cannot open the PE file!\n");
return -1;
}
//
// set time and date stamp to the PE file
//
if (SetStamp (fp, ltime) != 0) {
fclose (fp);
return -1;
}
printf ("Set Date/Time Stamp to %s", ctime (&ltime));
//
// close the PE file
//
fclose (fp);
return 0;
}

View File

@@ -0,0 +1,94 @@
#/*++
#
# Copyright (c) 2006 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the SplitFile utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=SplitFile
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\SplitFile.c"
TARGET_EXE_INCLUDE =
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tool.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE): $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) /out:$(TARGET_EXE) $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,136 @@
/*++
Copyright 2006, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
splitfile.c
Abstract:
--*/
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
void
helpmsg (
void
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
Returns:
GC_TODO: add return values
--*/
{
printf (
"SplitFile Filename Offset\n"" Filename = Input file to split\n"" Offset = offset at which to split file\n"
"\n\n""SplitFile will break a file in two pieces at the requested offset\n"
" outputting Filename1 and Filename2\n"
);
}
int
main (
int argc,
char*argv[]
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
argc - GC_TODO: add argument description
argv - GC_TODO: add argument description
Returns:
GC_TODO: add return values
--*/
{
FILE *In;
FILE *Out1;
FILE *Out2;
char OutName1[512];
char OutName2[512];
unsigned long Index;
unsigned long splitpoint;
char CharC;
if (argc != 3) {
helpmsg ();
return -1;
}
In = fopen (argv[1], "rb");
if (In == NULL) {
printf ("Unable to open file \"%s\"\n", argv[1]);
return -1;
}
strncpy (OutName1, argv[1], 510);
strncpy (OutName2, argv[1], 510);
strcat (OutName1, "1");
strcat (OutName2, "2");
Out1 = fopen (OutName1, "wb");
if (Out1 == NULL) {
printf ("Unable to open file \"%s\"\n", OutName1);
return -1;
}
Out2 = fopen (OutName2, "wb");
if (Out2 == NULL) {
printf ("Unable to open file \"%s\"\n", OutName2);
return -1;
}
splitpoint = atoi (argv[2]);
for (Index = 0; Index < splitpoint; Index++) {
CharC = (char) fgetc (In);
if (feof (In)) {
break;
}
fputc (CharC, Out1);
}
for (;;) {
CharC = (char) fgetc (In);
if (feof (In)) {
break;
}
fputc (CharC, Out2);
}
fclose (In);
fclose (Out1);
fclose (Out2);
return 0;
}

View File

@@ -0,0 +1,89 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name:
#
# Makefile
#
# Abstract:
#
# makefile for building the StrGather utility.
#
#--*/
#
# Make sure environmental variable EDK_SOURCE is set
#
!IFNDEF EDK_SOURCE
!ERROR EDK_SOURCE environmental variable not set
!ENDIF
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Target specific information
#
TARGET_NAME = StrGather
TARGET_SRC_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\StrGather.exe
#
# Build targets
#
all: $(TARGET_EXE)
LIBS = "$(EDK_TOOLS_OUTPUT)\Common.lib"
OBJECTS = $(EDK_TOOLS_OUTPUT)\StrGather.obj \
$(EDK_TOOLS_OUTPUT)\StringDB.obj
INC_DEPS = $(TARGET_SRC_DIR)\StrGather.h $(TARGET_SRC_DIR)\StringDB.h
C_FLAGS = $(C_FLAGS) /W4
#
# Compile each source file
#
$(EDK_TOOLS_OUTPUT)\StrGather.obj : $(TARGET_SRC_DIR)\StrGather.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(INC_PATHS) $(TARGET_SRC_DIR)\StrGather.c /Fo$@
$(EDK_TOOLS_OUTPUT)\StringDB.obj : $(TARGET_SRC_DIR)\StringDB.c $(INC_DEPS)
$(CC) $(C_FLAGS) $(INC_PATHS) $(TARGET_SRC_DIR)\StringDB.c /Fo$@
#
# Add Binary Build description for this tools.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE) : $(OBJECTS) $(LIBS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,84 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
StrGather.h
Abstract:
Common defines and prototypes for StrGather.
--*/
#ifndef _STR_GATHER_H_
#define _STR_GATHER_H_
#define MALLOC(size) malloc (size)
#define FREE(ptr) free (ptr)
#define PROGRAM_NAME "StrGather"
typedef CHAR16 WCHAR;
#define UNICODE_TO_ASCII(w) (INT8) ((w) & 0xFF)
#define ASCII_TO_UNICODE(a) (WCHAR) ((UINT8) (a))
#define UNICODE_HASH L'#'
#define UNICODE_BACKSLASH L'\\'
#define UNICODE_SLASH L'/'
#define UNICODE_EQUAL_SIGN L'='
#define UNICODE_PLUS_SIGN L'+'
#define UNICODE_FILE_START 0xFEFF
#define UNICODE_CR 0x000D
#define UNICODE_LF 0x000A
#define UNICODE_NULL 0x0000
#define UNICODE_SPACE L' '
#define UNICODE_SLASH L'/'
#define UNICODE_DOUBLE_QUOTE L'"'
#define UNICODE_Z L'Z'
#define UNICODE_z L'z'
#define UNICODE_A L'A'
#define UNICODE_a L'a'
#define UNICODE_F L'F'
#define UNICODE_f L'f'
#define UNICODE_UNDERSCORE L'_'
#define UNICODE_0 L'0'
#define UNICODE_9 L'9'
#define UNICODE_TAB L'\t'
#define UNICODE_NBR_STRING L"\\nbr"
#define UNICODE_BR_STRING L"\\br"
#define UNICODE_WIDE_STRING L"\\wide"
#define UNICODE_NARROW_STRING L"\\narrow"
//
// This is the length of a valid string identifier
//
#define LANGUAGE_IDENTIFIER_NAME_LEN 3
typedef struct _TEXT_STRING_LIST {
struct _TEXT_STRING_LIST *Next;
UINT8 *Str;
} TEXT_STRING_LIST;
typedef struct _WCHAR_STRING_LIST {
struct _WCHAR_STRING_LIST *Next;
WCHAR *Str;
} WCHAR_STRING_LIST;
typedef struct _WCHAR_MATCHING_STRING_LIST {
struct _WCHAR_MATCHING_STRING_LIST *Next;
WCHAR *Str1;
WCHAR *Str2;
} WCHAR_MATCHING_STRING_LIST;
#endif // #ifndef _STR_GATHER_H_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,136 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
StringDB.h
Abstract:
Common defines and prototypes for string database management
--*/
#ifndef _STRING_DB_H_
#define _STRING_DB_H_
#define LANGUAGE_NAME_STRING_NAME L"$LANGUAGE_NAME"
#define PRINTABLE_LANGUAGE_NAME_STRING_NAME L"$PRINTABLE_LANGUAGE_NAME"
void
StringDBConstructor (
void
)
;
void
StringDBDestructor (
void
)
;
STATUS
StringDBAddString (
WCHAR *LanguageName,
WCHAR *StringIdentifier,
WCHAR *Scope,
WCHAR *String,
BOOLEAN Format,
UINT16 Flags
)
;
STATUS
StringDBSetScope (
WCHAR *Scope
)
;
#define STRING_FLAGS_REFERENCED 0x0001 // if referenced somewhere
#define STRING_FLAGS_UNDEFINED 0x0002 // if we added it for padding purposes
#define STRING_FLAGS_INDEX_ASSIGNED 0x0004 // so don't change the index value
#define STRING_ID_INVALID 0xFFFF
#define STRING_ID_LANGUAGE_NAME 0x0000
#define STRING_ID_PRINTABLE_LANGUAGE_NAME 0x0001
STATUS
StringDBAddStringIdentifier (
WCHAR *StringIdentifier,
UINT16 *NewId,
UINT16 Flags
)
;
STATUS
StringDBReadDatabase (
INT8 *DBFileName,
BOOLEAN IgnoreIfNotExist,
BOOLEAN Verbose
)
;
STATUS
StringDBWriteDatabase (
INT8 *DBFileName,
BOOLEAN Verbose
)
;
STATUS
StringDBDumpDatabase (
INT8 *DBFileName,
INT8 *OutputFileName,
BOOLEAN Verbose
)
;
STATUS
StringDBAddLanguage (
WCHAR *LanguageName,
WCHAR *PrintableLanguageName
)
;
STATUS
StringDBDumpCStrings (
INT8 *FileName,
INT8 *BaseName,
WCHAR_STRING_LIST *LanguagesOfInterest,
WCHAR_MATCHING_STRING_LIST *IndirectionList
)
;
STATUS
StringDBDumpStringDefines (
INT8 *FileName,
INT8 *BaseName
)
;
STATUS
StringDBSetCurrentLanguage (
WCHAR *LanguageName
)
;
STATUS
StringDBSetStringReferenced (
INT8 *StringIdentifierName,
BOOLEAN IgnoreNotFound
)
;
void
StringDBFormatString (
WCHAR *String
)
;
#endif // #ifndef _STRING_DB_H_

View File

@@ -0,0 +1,121 @@
/*++
Copyright (c) 2004, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
VcCheck.c
Abstract:
We have found problems with the Visual C++ SP4 and the /O1 flag.
If this tests ask a question you have the wrong version of Visual C++
on your system
This test assumes the tools are being compiled with the same complier
as the Tiano code.
Please see $(EFI_SOURCE)\EFI2.0 Developer's Manual.doc to get the
correct version of Visual C++
--*/
#include <stdio.h>
_int16 gGloba16;
int
CheckLostCode (
int Value
)
/*++
Routine Description:
This routine is used to test for compiler isseus with /O1.
If the /O1 compiler option, and C2.dll is got from Visual C++ SP5
(version: 6.00.8168.0), the assember codes after default branch will be
losted. (Execute "cl Visual Ccheck.c /O1 /FAsc" to get detail information)
Arguments:
Value - Test case
Returns:
Test to see if comiler error is present.
--*/
{
switch (Value) {
case 0:
break;
default:
_asm
{
mov bx, 1
mov gGloba16, bx
}
return 1;
}
_asm
{
mov bx, 0
mov gGloba16, bx
}
return 0;
}
int
main (
void
)
/*++
Routine Description:
This utility is checking for a known Visual C++ compiler issues. To remove this
question from the build follow the steps in the developers manual.
Arguments:
NONE
Returns:
0 - Compiler version is O.K.
1 - Compiler version is Bad
--*/
{
int result;
char select;
gGloba16 = 0xFF;
result = 0;
CheckLostCode (0);
result += (gGloba16 == 0) ? 0 : 1;
CheckLostCode (1);
result += (gGloba16 == 1) ? 0 : 1;
if (result != 0) {
printf ("Warning: C2.dll is incorrect.\n Please see $(EFI_SOURCE)\\EFI2.0 Developer's Manual.doc for corrective action.\n");
printf ("Would you want to continue?(Y/N)");
scanf ("%c", &select);
if ((select == 'Y') || (select == 'y')) {
return 0;
} else {
return 1;
}
}
return 0;
}

View File

@@ -0,0 +1,92 @@
#/*++
#
# Copyright (c) 2004 - 2007, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
# Module Name: makefile
#
# Abstract:
#
# This file is used to build the EFI utility.
#
#--*/
#
# Do this if you want to compile from this directory
#
!IFNDEF TOOLCHAIN
TOOLCHAIN = TOOLCHAIN_MSVC
!ENDIF
!INCLUDE $(BUILD_DIR)\PlatformTools.env
#
# Define some macros we use here. Should get rid of them someday and
# get rid of the extra level of indirection.
#
COMMON_SOURCE = $(EDK_TOOLS_COMMON)
#
# Common information
#
INC=$(INC)
#
# Target specific information
#
TARGET_NAME=VcCheck
TARGET_SOURCE_DIR = $(EDK_TOOLS_SOURCE)\$(TARGET_NAME)
TARGET_EXE = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).exe
TARGET_EXE_SOURCE = "$(TARGET_SOURCE_DIR)\VcCheck.c"
TARGET_EXE_INCLUDE =
OBJECTS = $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Replace /Od with "" to fix the Command line warning D4025
#
C_FLAGS = $(C_FLAGS:/Od=) /O1
#
# Build targets
#
all: $(TARGET_EXE)
#
# Build EXE
#
$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj: $(TARGET_EXE_SOURCE) $(TARGET_EXE_INCLUDE)
$(CC) $(C_FLAGS) $(INC) $(TARGET_EXE_SOURCE) /Fo$(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).obj
#
# Add Binary Build description for this tools.
#
!IF (("$(EFI_BINARY_TOOLS)" == "YES") && EXIST($(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe))
$(TARGET_EXE): $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).exe $(TARGET_EXE) /Y
if exist $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb \
copy $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb /Y
!ELSE
$(TARGET_EXE) : $(OBJECTS)
$(LINK) $(MSVS_LINK_LIBPATHS) $(L_FLAGS) $(LIBS) /out:$(TARGET_EXE) $(OBJECTS)
if not exist $(EFI_PLATFORM_BIN)\Tools mkdir $(EFI_PLATFORM_BIN)\Tools
if exist $(TARGET_EXE) copy $(TARGET_EXE) $(EFI_PLATFORM_BIN)\tools\$(TARGET_NAME).exe /Y
if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb \
copy $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).pdb $(EFI_PLATFORM_BIN)\Tools\$(TARGET_NAME).pdb /Y
!ENDIF
clean:
@if exist $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* del $(EDK_TOOLS_OUTPUT)\$(TARGET_NAME).* > NUL

View File

@@ -0,0 +1,178 @@
/*++
Copyright (c) 2004 - 2005, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
EfiVfr.h
Abstract:
Defines and prototypes for the EFI internal forms representation
setup protocol and drivers
--*/
#ifndef _EFI_VFR_H_
#define _EFI_VFR_H_
#include "Tiano.h"
#include "EfiInternalFormRepresentation.h"
#include <string.h>
//
// This number should be incremented with each change to the VFR compiler.
// We write the version to the output list file for debug purposes.
//
#define VFR_COMPILER_VERSION "1.88"
//
// Maximum file path for filenames
//
#define MAX_PATH 255
#define MAX_QUEUE_COUNT 255
#define MAX_LINE_LEN 1024
#define PROGRAM_NAME "VfrCompile"
//
// We parse C-style structure definitions which can then be referenced
// in VFR statements.
// We need to define an internal structure that can be used to
// track the fields in a structure definition, and another structure
// to keep track of the structure name and subfields.
//
typedef struct _STRUCT_FIELD_DEFINITION {
struct _STRUCT_FIELD_DEFINITION *Next;
int DataSize;
int Offset; // from the start of the structure
int ArrayLength;
char IsArray;
char *Name;
} STRUCT_FIELD_DEFINITION;
typedef struct _STRUCT_DEFINITION {
struct _STRUCT_DEFINITION *Next;
int Size;
int LineNum; // line number where the structure was defined
int IsNonNV; // if this is the non-NV data structure definition
int Referenced; // if it's referenced anywhere in the VFR
int VarStoreIdValid; // found a 'varstore' statement for it in the VFR
unsigned short VarStoreId; // key from a varstore IFR statement
int VarStoreLineNum; // line number where VARSTORE was defined
char *Name;
STRUCT_FIELD_DEFINITION *Field;
STRUCT_FIELD_DEFINITION *LastField;
} STRUCT_DEFINITION;
//
// For the IdEqValList variable list of UINT16's, keep track of them using
// a linked list until we know how many there are.
// We also use a linked list of these to keep track of labels used in
// the VFR script so we can catch duplicates.
// We'll also use it to keep track of defined varstore id's so we can
// detect duplicate definitions.
//
typedef struct _UINT16_LIST {
struct _UINT16_LIST *Next;
UINT16 Value;
UINT32 LineNum;
} UINT16_LIST;
typedef struct _GOTO_REFERENCE {
struct _GOTO_REFERENCE *Next;
UINT32 RefLineNum; // line number of source file where referenced
UINT16 Value;
} GOTO_REFERENCE;
typedef struct _FORM_ID_VALUE {
struct _FORM_ID_VALUE *Next;
UINT32 LineNum;
UINT16 Value;
} FORM_ID_VALUE;
//
// We keep track in the parser of all "#line 4 "x.y"" strings so we
// can cross-reference the line numbers in the preprocessor output .i file
// to the original input files.
//
typedef struct _PARSER_LINE_DEFINITION {
struct _PARSER_LINE_DEFINITION *Next;
UINT32 HashLineNum; // from the #line stmt
UINT32 TokenLineNum; // line number in the .i file
INT8 *FileName; // from the #line stmt
} PARSER_LINE_DEFINITION;
extern PARSER_LINE_DEFINITION *gLineDefinition;
extern PARSER_LINE_DEFINITION *gLastLineDefinition;
extern
char *
ConvertLineNumber (
UINT32 *LineNum
)
/*++
Routine Description:
Given the line number in the preprocessor-output file, use the line number
information we've saved to determine the source file name and line number
where the code originally came from. This is required for error reporting.
Arguments:
LineNum - the line number in the preprocessor-output file.
Returns:
Returns a pointer to the source file name. Also returns the line number
in the provided LineNum argument
--*/
;
typedef struct _IFR_BYTE {
struct _IFR_BYTE *Next;
UINT32 LineNum;
UINT8 OpcodeByte;
UINT8 KeyByte;
} IFR_BYTE;
typedef struct {
INT8 VfrFileName[MAX_PATH];
INT8 VfrListFileName[MAX_PATH];
INT8 CreateListFile;
INT8 CreateIfrBinFile;
INT8 IfrOutputFileName[MAX_PATH];
INT8 OutputDirectory[MAX_PATH];
INT8 PreprocessorOutputFileName[MAX_PATH];
INT8 VfrBaseFileName[MAX_PATH]; // name of input VFR file with no path or extension
INT8 *IncludePaths;
INT8 *CPreprocessorOptions;
} OPTIONS;
extern OPTIONS gOptions;
VOID
WriteStandardFileHeader (
FILE *OutFptr
)
/*++
Routine Description:
This function is invoked to emit a standard header to an
output text file.
Arguments:
OutFptr - file to write the header to
Returns:
None
--*/
;
#endif // #ifndef _EFI_VFR_H_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,754 @@
/*++
Copyright (c) 2004 - 2007, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
VfrServices.cpp
Abstract:
Support routines for the VFR compiler
--*/
#include <stdio.h> // for FILE routines
#include <stdlib.h> // for malloc() and free()
#include "Tiano.h"
#include "EfiUtilityMsgs.h"
#include "EfiVfr.h"
#include "VfrServices.h"
#include EFI_PROTOCOL_DEFINITION (Hii)
static const char *mSourceFileHeader[] = {
"//",
"// DO NOT EDIT -- auto-generated file",
"//",
"// This file is generated by the VFR compiler.",
"//",
NULL
};
typedef struct {
INT8 *Name;
INT32 Size;
} IFR_OPCODE_SIZES;
//
// Create a table that can be used to do internal checking on the IFR
// bytes we emit.
//
static const IFR_OPCODE_SIZES mOpcodeSizes[] = {
{ 0, 0 }, // invalid
{ "EFI_IFR_FORM", sizeof (EFI_IFR_FORM) },
{ "EFI_IFR_SUBTITLE", sizeof (EFI_IFR_SUBTITLE) },
{ "EFI_IFR_TEXT", -6 }, //sizeof (EFI_IFR_TEXT) },
{ "unused 0x04 opcode", 0 }, // EFI_IFR_GRAPHIC_OP
{ "EFI_IFR_ONE_OF", sizeof (EFI_IFR_ONE_OF) },
{ "EFI_IFR_CHECK_BOX", sizeof (EFI_IFR_CHECK_BOX) },
{ "EFI_IFR_NUMERIC", sizeof (EFI_IFR_NUMERIC) },
{ "EFI_IFR_PASSWORD", sizeof (EFI_IFR_PASSWORD) },
{ "EFI_IFR_ONE_OF_OPTION", sizeof (EFI_IFR_ONE_OF_OPTION) },
{ "EFI_IFR_SUPPRESS", sizeof (EFI_IFR_SUPPRESS) },
{ "EFI_IFR_END_FORM", sizeof (EFI_IFR_END_FORM) },
{ "EFI_IFR_HIDDEN", sizeof (EFI_IFR_HIDDEN) },
{ "EFI_IFR_END_FORM_SET", sizeof (EFI_IFR_END_FORM_SET) },
{ "EFI_IFR_FORM_SET", sizeof (EFI_IFR_FORM_SET) },
{ "EFI_IFR_REF", sizeof (EFI_IFR_REF) },
{ "EFI_IFR_END_ONE_OF", sizeof (EFI_IFR_END_ONE_OF) },
{ "EFI_IFR_INCONSISTENT", sizeof (EFI_IFR_INCONSISTENT) },
{ "EFI_IFR_EQ_ID_VAL", sizeof (EFI_IFR_EQ_ID_VAL) },
{ "EFI_IFR_EQ_ID_ID", sizeof (EFI_IFR_EQ_ID_ID) },
{ "EFI_IFR_EQ_ID_LIST", -sizeof (EFI_IFR_EQ_ID_LIST) },
{ "EFI_IFR_AND", sizeof (EFI_IFR_AND) },
{ "EFI_IFR_OR", sizeof (EFI_IFR_OR) },
{ "EFI_IFR_NOT", sizeof (EFI_IFR_NOT) },
{ "EFI_IFR_END_IF", sizeof (EFI_IFR_END_IF) },
{ "EFI_IFR_GRAYOUT", sizeof (EFI_IFR_GRAYOUT) },
{ "EFI_IFR_DATE", sizeof (EFI_IFR_DATE) / 3 },
{ "EFI_IFR_TIME", sizeof (EFI_IFR_TIME) / 3 },
{ "EFI_IFR_STRING", sizeof (EFI_IFR_STRING) },
{ "EFI_IFR_LABEL", sizeof (EFI_IFR_LABEL) },
{ "EFI_IFR_SAVE_DEFAULTS", sizeof (EFI_IFR_SAVE_DEFAULTS) },
{ "EFI_IFR_RESTORE_DEFAULTS", sizeof (EFI_IFR_RESTORE_DEFAULTS) },
{ "EFI_IFR_BANNER", sizeof (EFI_IFR_BANNER) },
{ "EFI_IFR_INVENTORY", sizeof (EFI_IFR_INVENTORY) },
{ "EFI_IFR_EQ_VAR_VAL_OP", sizeof (EFI_IFR_EQ_VAR_VAL) },
{ "EFI_IFR_ORDERED_LIST_OP", sizeof (EFI_IFR_ORDERED_LIST) },
{ "EFI_IFR_VARSTORE_OP", -sizeof (EFI_IFR_VARSTORE) },
{ "EFI_IFR_VARSTORE_SELECT_OP", sizeof (EFI_IFR_VARSTORE_SELECT) },
{ "EFI_IFR_VARSTORE_SELECT_PAIR_OP", sizeof (EFI_IFR_VARSTORE_SELECT_PAIR) },
{ "EFI_IFR_TRUE", sizeof (EFI_IFR_TRUE)},
{ "EFI_IFR_FALSE", sizeof (EFI_IFR_FALSE)},
{ "EFI_IFR_GT", sizeof (EFI_IFR_GT)},
{ "EFI_IFR_GE", sizeof (EFI_IFR_GE)},
{ "EFI_IFR_OEM_DEFINED_OP", -2 },
};
VfrOpcodeHandler::VfrOpcodeHandler (
)
/*++
Routine Description:
Constructor for the VFR opcode handling class.
Arguments:
None
Returns:
None
--*/
{
mIfrBytes = NULL;
mLastIfrByte = NULL;
mBytesWritten = 0;
mQueuedByteCount = 0;
mQueuedOpcodeByteValid = 0;
mPrimaryVarStoreId = 0;
mSecondaryVarStoreId = 0;
mSecondaryVarStoreIdSet = 0;
mPrimaryVarStoreIdSet = 0;
mDefaultVarStoreId = 0;
}
VOID
VfrOpcodeHandler::SetVarStoreId (
UINT16 VarStoreId
)
/*++
Routine Description:
This function is invoked by the parser when a variable is referenced in the
VFR. Save the variable store (and set a flag) so that we can later determine
if we need to emit a varstore-select or varstore-select-pair opcode.
Arguments:
VarStoreId - ID of the variable store referenced in the VFR
Returns:
None
--*/
{
mPrimaryVarStoreId = VarStoreId;
mPrimaryVarStoreIdSet = 1;
}
VOID
VfrOpcodeHandler::SetSecondaryVarStoreId (
UINT16 VarStoreId
)
/*++
Routine Description:
This function is invoked by the parser when a secondary variable is
referenced in the VFR. Save the variable store (and set a flag) so
that we can later determine if we need to emit a varstore-select or
varstore-pair opcode.
Arguments:
VarStoreId - ID of the variable store referenced in the VFR
Returns:
None
--*/
{
mSecondaryVarStoreId = VarStoreId;
mSecondaryVarStoreIdSet = 1;
}
VOID
VfrOpcodeHandler::WriteIfrBytes (
)
/*++
Routine Description:
This function is invoked at the end of parsing. Its purpose
is to write out all the IFR bytes that were queued up while
parsing.
Arguments:
None
Returns:
None
--*/
{
IFR_BYTE *Curr;
IFR_BYTE *Next;
UINT32 Count;
UINT32 LineCount;
UINT32 PoundLines;
UINT32 ByteCount;
INT8 Line[MAX_LINE_LEN];
INT8 *Cptr;
FILE *InFptr;
FILE *OutFptr;
UINT32 ListFile;
EFI_HII_IFR_PACK_HEADER IfrHeader;
UINT8 *Ptr;
FILE *IfrBinFptr;
UINT32 BytesLeftThisOpcode;
//
// If someone added a new opcode and didn't update our opcode sizes structure, error out.
//
if (sizeof(mOpcodeSizes) / sizeof (mOpcodeSizes[0]) != EFI_IFR_LAST_OPCODE + 1) {
Error (__FILE__, __LINE__, 0, "application error", "internal IFR binary table size is incorrect");
return;
}
//
// Flush the queue
//
FlushQueue ();
//
// If there have been any errors to this point, then skip dumping the IFR
// binary data. This way doing an nmake again will try to build it again, and
// the build will fail if they did not fix the problem.
//
if (GetUtilityStatus () != STATUS_ERROR) {
if ((IfrBinFptr = fopen (gOptions.IfrOutputFileName, "w")) == NULL) {
Error (PROGRAM_NAME, 0, 0, gOptions.IfrOutputFileName, "could not open file for writing");
return;
}
//
// Write the standard file header to the output file
//
WriteStandardFileHeader (IfrBinFptr);
//
// Write the structure header
//
fprintf (IfrBinFptr, "\nunsigned char %sBin[] = {", gOptions.VfrBaseFileName);
//
// Write the header
//
memset ((char *)&IfrHeader, 0, sizeof (IfrHeader));
IfrHeader.Header.Type = EFI_HII_IFR;
IfrHeader.Header.Length = mBytesWritten + sizeof (IfrHeader);
Ptr = (UINT8 *)&IfrHeader;
for (Count = 0; Count < sizeof (IfrHeader); Count++, Ptr++) {
if ((Count & 0x03) == 0) {
fprintf (IfrBinFptr, "\n ");
}
fprintf (IfrBinFptr, "0x%02X, ", *Ptr);
}
//
//
// Write all the IFR bytes
//
fprintf (IfrBinFptr, "\n // start of IFR data");
Curr = mIfrBytes;
Count = 0;
while (Curr != NULL) {
if ((Count & 0x0F) == 0) {
fprintf (IfrBinFptr, "\n ");
}
if (Curr->KeyByte != 0) {
fprintf (IfrBinFptr, "/*%c*/ ", Curr->KeyByte);
}
fprintf (IfrBinFptr, "0x%02X, ", Curr->OpcodeByte);
Count++;
Curr = Curr->Next;
}
fprintf (IfrBinFptr, "\n};\n\n");
//
//
// Close the file
//
fclose (IfrBinFptr);
IfrBinFptr = NULL;
}
//
// Write the bytes as binary data if the user specified to do so
//
if ((GetUtilityStatus () != STATUS_ERROR) && (gOptions.CreateIfrBinFile != 0)) {
//
// Use the Ifr output file name with a ".hpk" extension.
//
for (Cptr = gOptions.IfrOutputFileName + strlen (gOptions.IfrOutputFileName) - 1;
(*Cptr != '.') && (Cptr > gOptions.IfrOutputFileName) && (*Cptr != '\\');
Cptr--) {
//
// do nothing
//
}
if (*Cptr == '.') {
strcpy (Cptr, ".hpk");
} else {
strcat (gOptions.IfrOutputFileName, ".hpk");
}
if ((IfrBinFptr = fopen (gOptions.IfrOutputFileName, "wb")) == NULL) {
Error (PROGRAM_NAME, 0, 0, gOptions.IfrOutputFileName, "could not open file for writing");
return;
}
//
// Write the structure header
//
memset ((char *)&IfrHeader, 0, sizeof (IfrHeader));
IfrHeader.Header.Type = EFI_HII_IFR;
IfrHeader.Header.Length = mBytesWritten + sizeof (IfrHeader);
Ptr = (UINT8 *)&IfrHeader;
for (Count = 0; Count < sizeof (IfrHeader); Count++, Ptr++) {
fwrite (Ptr, 1, 1, IfrBinFptr);
}
//
//
// Write all the IFR bytes
//
Curr = mIfrBytes;
Count = 0;
while (Curr != NULL) {
fwrite (&Curr->OpcodeByte, 1, 1, IfrBinFptr);
Curr = Curr->Next;
}
//
//
// Close the file
//
fclose (IfrBinFptr);
IfrBinFptr = NULL;
}
//
// If creating a listing file, then open the input and output files
//
ListFile = 0;
if (gOptions.CreateListFile) {
//
// Open the input VFR file and the output list file
//
if ((InFptr = fopen (gOptions.PreprocessorOutputFileName, "r")) == NULL) {
Warning (PROGRAM_NAME, 0, 0, gOptions.PreprocessorOutputFileName, "could not open file for creating a list file");
} else {
if ((OutFptr = fopen (gOptions.VfrListFileName, "w")) == NULL) {
Warning (PROGRAM_NAME, 0, 0, gOptions.VfrListFileName, "could not open output list file for writing");
fclose (InFptr);
InFptr = NULL;
} else {
LineCount = 0;
ListFile = 1;
PoundLines = 0;
ByteCount = 0;
}
}
}
//
// Write the list file
//
if (ListFile) {
//
// Write out the VFR compiler version
//
fprintf (OutFptr, "//\n// VFR compiler version " VFR_COMPILER_VERSION "\n//\n");
Curr = mIfrBytes;
while (Curr != NULL) {
//
// Print lines until we reach the line of the current opcode
//
while (LineCount < PoundLines + Curr->LineNum) {
if (fgets (Line, sizeof (Line), InFptr) != NULL) {
//
// We should check for line length exceeded on the fgets(). Otherwise it
// throws the listing file output off. Future enhancement perhaps.
//
fprintf (OutFptr, "%s", Line);
if (strncmp (Line, "#line", 5) == 0) {
PoundLines++;
}
}
LineCount++;
}
//
// Print all opcodes with line numbers less than where we are now
//
BytesLeftThisOpcode = 0;
while ((Curr != NULL) && ((Curr->LineNum == 0) || (LineCount >= PoundLines + Curr->LineNum))) {
if (BytesLeftThisOpcode == 0) {
fprintf (OutFptr, ">%08X: ", ByteCount);
if (Curr->Next != NULL) {
BytesLeftThisOpcode = (UINT32)Curr->Next->OpcodeByte;
}
}
fprintf (OutFptr, "%02X ", (UINT32)Curr->OpcodeByte);
ByteCount++;
BytesLeftThisOpcode--;
if (BytesLeftThisOpcode == 0) {
fprintf (OutFptr, "\n");
}
Curr = Curr->Next;
}
}
//
// Dump any remaining lines from the input file
//
while (fgets (Line, sizeof (Line), InFptr) != NULL) {
fprintf (OutFptr, "%s", Line);
}
fclose (InFptr);
fclose (OutFptr);
}
//
// Debug code to make sure that each opcode we write out has as many
// bytes as the IFR structure requires. If there were errors, then
// don't do this step.
//
if (GetUtilityStatus () != STATUS_ERROR) {
Curr = mIfrBytes;
ByteCount = 0;
while (Curr != NULL) {
//
// First byte is the opcode, second byte is the length
//
if (Curr->Next == NULL) {
Error (__FILE__, __LINE__, 0, "application error", "last opcode written does not contain a length byte");
break;
}
Count = (UINT32)Curr->Next->OpcodeByte;
if (Count == 0) {
Error (
__FILE__,
__LINE__,
0,
"application error",
"opcode with 0 length specified in output at offset 0x%X",
ByteCount
);
break;
}
//
// Check the length
//
if ((Curr->OpcodeByte > EFI_IFR_LAST_OPCODE) || (Curr->OpcodeByte == 0)) {
Error (
__FILE__,
__LINE__,
0,
"application error",
"invalid opcode 0x%X in output at offset 0x%X",
(UINT32) Curr->OpcodeByte, ByteCount
);
} else if (mOpcodeSizes[Curr->OpcodeByte].Size < 0) {
//
// For those cases where the length is variable, the size is negative, and indicates
// the miniumum size.
//
if ((mOpcodeSizes[Curr->OpcodeByte].Size * -1) > Count) {
Error (
__FILE__,
__LINE__,
0,
"application error",
"insufficient number of bytes written for %s at offset 0x%X",
mOpcodeSizes[Curr->OpcodeByte].Name,
ByteCount
);
}
} else {
//
// Check for gaps
//
if (mOpcodeSizes[Curr->OpcodeByte].Size == 0) {
Error (
__FILE__,
__LINE__,
0,
"application error",
"invalid opcode 0x%X in output at offset 0x%X",
(UINT32)Curr->OpcodeByte,
ByteCount
);
} else {
//
// Check size
//
if (mOpcodeSizes[Curr->OpcodeByte].Size != Count) {
Error (
__FILE__,
__LINE__,
0,
"application error",
"invalid number of bytes (%d written s/b %d) written for %s at offset 0x%X",
Count,
mOpcodeSizes[Curr->OpcodeByte].Size,
mOpcodeSizes[Curr->OpcodeByte].Name,
ByteCount
);
}
}
}
//
// Skip to next opcode
//
while (Count > 0) {
ByteCount++;
if (Curr == NULL) {
Error (__FILE__, __LINE__, 0, "application error", "last opcode written has invalid length");
break;
}
Curr = Curr->Next;
Count--;
}
}
}
}
VfrOpcodeHandler::~VfrOpcodeHandler(
)
/*++
Routine Description:
Destructor for the VFR opcode handler. Free up memory allocated
while parsing the VFR script.
Arguments:
None
Returns:
None
--*/
{
IFR_BYTE *Curr;
IFR_BYTE *Next;
//
// Free up the IFR bytes
//
Curr = mIfrBytes;
while (Curr != NULL) {
Next = Curr->Next;
free (Curr);
Curr = Next;
}
}
int
VfrOpcodeHandler::AddOpcodeByte (
UINT8 OpcodeByte,
UINT32 LineNum
)
/*++
Routine Description:
This function is invoked by the parser when a new IFR
opcode should be emitted.
Arguments:
OpcodeByte - the IFR opcode
LineNum - the line number from the source file that resulted
in the opcode being emitted.
Returns:
0 always
--*/
{
UINT32 Count;
FlushQueue();
//
// Now add this new byte
//
mQueuedOpcodeByte = OpcodeByte;
mQueuedLineNum = LineNum;
mQueuedOpcodeByteValid = 1;
return 0;
}
VOID
VfrOpcodeHandler::AddByte (
UINT8 ByteVal,
UINT8 KeyByte
)
/*++
Routine Description:
This function is invoked by the parser when it determines
that more raw IFR bytes should be emitted to the output stream.
Here we just queue them up into an output buffer.
Arguments:
ByteVal - the raw byte to emit to the output IFR stream
KeyByte - a value that can be used for debug.
Returns:
None
--*/
{
//
// Check for buffer overflow
//
if (mQueuedByteCount >= MAX_QUEUE_COUNT) {
Error (PROGRAM_NAME, 0, 0, NULL, "opcode queue overflow");
} else {
mQueuedBytes[mQueuedByteCount] = ByteVal;
mQueuedKeyBytes[mQueuedByteCount] = KeyByte;
mQueuedByteCount++;
}
}
int
VfrOpcodeHandler::FlushQueue (
)
/*++
Routine Description:
This function is invoked to flush the internal IFR buffer.
Arguments:
None
Returns:
0 always
--*/
{
UINT32 Count;
UINT32 EmitNoneOnePair;
EmitNoneOnePair = 0;
//
// If the secondary varstore was specified, then we have to emit
// a varstore-select-pair opcode, which only applies to the following
// statement.
//
if (mSecondaryVarStoreIdSet) {
mSecondaryVarStoreIdSet = 0;
//
// If primary and secondary are the same as the current default
// varstore, then we don't have to do anything.
// Note that the varstore-select-pair only applies to the following
// opcode.
//
if ((mPrimaryVarStoreId != mSecondaryVarStoreId) || (mPrimaryVarStoreId != mDefaultVarStoreId)) {
IAddByte (EFI_IFR_VARSTORE_SELECT_PAIR_OP, 'O', mQueuedLineNum);
IAddByte ((UINT8)sizeof (EFI_IFR_VARSTORE_SELECT_PAIR), 'L', 0);
IAddByte ((UINT8)mPrimaryVarStoreId, 0, 0);
IAddByte ((UINT8)(mPrimaryVarStoreId >> 8), 0, 0);
IAddByte ((UINT8)mSecondaryVarStoreId, 0, 0);
IAddByte ((UINT8)(mSecondaryVarStoreId >> 8), 0, 0);
}
} else if (mPrimaryVarStoreIdSet != 0) {
mPrimaryVarStoreIdSet = 0;
if (mDefaultVarStoreId != mPrimaryVarStoreId) {
//
// The VFR statement referenced a different variable store
// than the last one we reported. Insert a new varstore select
// statement.
//
IAddByte (EFI_IFR_VARSTORE_SELECT_OP, 'O', mQueuedLineNum);
IAddByte ((UINT8)sizeof (EFI_IFR_VARSTORE_SELECT), 'L', 0);
IAddByte ((UINT8)mPrimaryVarStoreId, 0, 0);
IAddByte ((UINT8)(mPrimaryVarStoreId >> 8), 0, 0);
mDefaultVarStoreId = mPrimaryVarStoreId;
}
}
//
// Likely a new opcode is being added. Since each opcode item in the IFR has
// a header that specifies the size of the opcode item (which we don't
// know until we find the next opcode in the VFR), we queue up bytes
// until we know the size. Then we write them out. So flush the queue
// now.
//
if (mQueuedOpcodeByteValid != 0) {
//
// Add the previous opcode byte, the length byte, and the binary
// data.
//
IAddByte (mQueuedOpcodeByte, 'O', mQueuedLineNum);
IAddByte ((UINT8)(mQueuedByteCount + 2), 'L', 0);
for (Count = 0; Count < mQueuedByteCount; Count++) {
IAddByte (mQueuedBytes[Count], mQueuedKeyBytes[Count], 0);
}
mQueuedByteCount = 0;
mQueuedOpcodeByteValid = 0;
}
return 0;
}
int
VfrOpcodeHandler::IAddByte (
UINT8 ByteVal,
UINT8 KeyByte,
UINT32 LineNum
)
/*++
Routine Description:
This internal function is used to add actual IFR bytes to
the output stream. Most other functions queue up the bytes
in an internal buffer. Once they come here, there's no
going back.
Arguments:
ByteVal - value to write to output
KeyByte - key value tied to the byte -- useful for debug
LineNum - line number from source file the byte resulted from
Returns:
0 - if successful
1 - failed due to memory allocation failure
--*/
{
IFR_BYTE *NewByte;
NewByte = (IFR_BYTE *)malloc (sizeof (IFR_BYTE));
if (NewByte == NULL) {
return 1;
}
memset ((char *)NewByte, 0, sizeof (IFR_BYTE));
NewByte->OpcodeByte = ByteVal;
NewByte->KeyByte = KeyByte;
NewByte->LineNum = LineNum;
//
// Add to the list
//
if (mIfrBytes == NULL) {
mIfrBytes = NewByte;
} else {
mLastIfrByte->Next = NewByte;
}
mLastIfrByte = NewByte;
mBytesWritten++;
return 0;
}
VOID
WriteStandardFileHeader (
FILE *OutFptr
)
/*++
Routine Description:
This function is invoked to emit a standard header to an
output text file.
Arguments:
OutFptr - file to write the header to
Returns:
None
--*/
{
UINT32 TempIndex;
for (TempIndex = 0; mSourceFileHeader[TempIndex] != NULL; TempIndex++) {
fprintf (OutFptr, "%s\n", mSourceFileHeader[TempIndex]);
}
//
// Write out the VFR compiler version
//
fprintf (OutFptr, "// VFR compiler version " VFR_COMPILER_VERSION "\n//\n");
}

Some files were not shown because too many files have changed in this diff Show More