Check In tool source code based on Build tool project revision r1655.

git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@8964 6f19259b-4bc3-4df7-8a09-765794883524
This commit is contained in:
lgao4
2009-07-17 09:10:31 +00:00
parent 577e30cdb4
commit 30fdf1140b
532 changed files with 231447 additions and 32 deletions

View File

@@ -0,0 +1,10 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = BootSectImage
LIBS = -lCommon
OBJECTS = bootsectimage.o
include $(MAKEROOT)/Makefiles/app.makefile

View File

@@ -0,0 +1,10 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = BootSectImage
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = BootSectImage.obj
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,930 @@
/** @file
Abstract:
Patch the BPB information in boot sector image file.
Patch the MBR code in MBR image file.
Copyright 2006 - 2008, 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.
**/
#include <stdio.h>
#include <string.h>
#include "fat.h"
#include "mbr.h"
#include "EfiUtilityMsgs.h"
#define DEBUG_WARN 0x1
#define DEBUG_ERROR 0x2
//
// Utility Name
//
#define UTILITY_NAME "BootSectImage"
//
// Utility version information
//
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
void
Version (
void
)
/*++
Routine Description:
Displays the standard utility information to SDTOUT
Arguments:
None
Returns:
None
--*/
{
printf ("%s v%d.%d - Utility to break a file into two pieces at the specified offset.\n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION);
printf ("Copyright (c) 1999-2007 Intel Corporation. All rights reserved.\n");
}
void
Usage (
void
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
Returns:
GC_TODO: add return values
--*/
{
Version();
printf ("\nUsage: \n\
BootSectImage\n\
[-f, --force force patch even if the FAT type of SrcImage and DstImage mismatch]\n\
[-m, --mbr process MBR instead of boot sector]\n\
[-p, --parse parse SrcImageFile]\n\
[-o, --output DstImage]\n\
[-g, --patch patch DstImage using data from SrcImageFile]\n\
[-v, --verbose]\n\
[--version]\n\
[-q, --quiet disable all messages except fatal errors]\n\
[-d, --debug[#]\n\
[-h, --help]\n\
[SrcImageFile]\n");
}
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, "ERROR: E0001: Error opening file: %s", FileName);
return 0;
}
result = fread (BootSector, 1, 512, FileHandle);
if (result != 512) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "ERROR: E0004: Error reading 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: FAT - BPB_RsvdSecCnt - %04x, expected: Non-Zero Value",
FatBpb->Fat12_16.BPB_RsvdSecCnt);
return FatTypeUnknown;
}
if (FatBpb->Fat12_16.BPB_NumFATs != 2) {
DebugMsg (NULL, 0, DEBUG_WARN, NULL, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: FAT - BPB_FATSz16, BPB_FATSz32 - 0, expected: Non-Zero Value");
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, "ERROR: E3003: FAT - BPB_TotSec16, BPB_TotSec32 - 0, expected: Non-Zero Value");
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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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, "ERROR: E3003: 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: E3002: 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,
BOOLEAN 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, "ERROR: E3004: FAT type mismatch: Source - %s, Dest - %s",
FatTypeToString(SourceFatType), FatTypeToString(DestFatType));
} else {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "ERROR: E3004: FAT type mismatch: Source - %s, Dest - %s",
FatTypeToString(SourceFatType), FatTypeToString(DestFatType));
return ;
}
}
if (SourceFatType <= FatTypeUnknown || SourceFatType >= FatTypeMax) {
DebugMsg (NULL, 0, DEBUG_ERROR, NULL, "ERROR: E3002: 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 ("successful!\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: E3000: 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 ("\tsuccessful!\n");
}
return ;
}
int
main (
int argc,
char *argv[]
)
{
char *SrcImage;
char *DstImage;
BOOLEAN ForcePatch; // -f
BOOLEAN ProcessMbr; // -m
BOOLEAN DoParse; // -p SrcImage or -g SrcImage DstImage
BOOLEAN Verbose; // -v
SrcImage = DstImage = NULL;
ForcePatch = FALSE;
ProcessMbr = FALSE;
DoParse = TRUE;
Verbose = FALSE;
SetUtilityName ("bootsectimage");
argc--; argv++;
if (argc == 0) {
Usage ();
return -1;
}
while (argc != 0) {
if (strcmp (*argv, "-f") == 0 || strcmp (*argv, "--force") == 0) {
ForcePatch = TRUE;
} else if (strcmp (*argv, "-p") == 0 || strcmp (*argv, "--parse") == 0) {
DoParse = TRUE;
argc--; argv++;
if (argc < 1) {
Usage ();
return -1;
}
SrcImage = *argv;
} else if (strcmp (*argv, "-g") == 0 || strcmp (*argv, "--patch") == 0) {
DoParse = FALSE;
argc--; argv++;
if (argc < 2) {
Usage ();
return -1;
}
SrcImage = *argv;
argc--; argv++;
DstImage = *argv;
} else if (strcmp (*argv, "-m") == 0 || strcmp (*argv, "--mbr") == 0) {
ProcessMbr = TRUE;
} else if (strcmp (*argv, "-v") == 0 || strcmp (*argv, "--verbose") == 0) {
Verbose = TRUE;
} else {
Usage ();
return -1;
}
argc--; argv++;
}
if (ForcePatch && DoParse) {
printf ("ERROR: E1002: Conflicting options: -f, -p. Cannot apply force(-f) to parse(-p)!\n");
Usage ();
return -1;
}
if (ForcePatch && !DoParse && ProcessMbr) {
printf ("ERROR: E1002: Conflicting options: -f, -g -m. Cannot apply force(-f) to processing MBR (-g -m)!\n");
Usage ();
return -1;
}
if (Verbose) {
SetPrintLevel (VERBOSE_LOG_LEVEL);
} else {
SetPrintLevel (KEY_LOG_LEVEL);
}
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,152 @@
/** @file
Fat file system structure and definition.
Copyright 2006 - 2008, 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.
**/
#ifndef _FAT_BPB_H_
#define _FAT_BPB_H_
#include "CommonLib.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,58 @@
/** @file
MBR Partition Entry and Table structure defintions.
Copyright 2006 - 2008, 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.
**/
#ifndef _MBR_H_
#define _MBR_H_
#include "CommonLib.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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,87 @@
/** @file
Copyright (c) 1999 - 2008, 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:
BinderFuncs.c
Abstract:
Binder function implementations for ANSI C libraries.
**/
#include "BinderFuncs.h"
#include "CommonLib.h"
#include <stdlib.h>
#include <string.h>
//
// Binder Function Implementations
//
VOID *
CommonLibBinderAllocate (
IN UINTN Size
)
{
return (VOID *) malloc (Size);
}
VOID
CommonLibBinderFree (
IN VOID *Pointer
)
{
free (Pointer);
}
VOID
CommonLibBinderCopyMem (
IN VOID *Destination,
IN VOID *Source,
IN UINTN Length
)
{
memmove (Destination, Source, Length);
}
VOID
CommonLibBinderSetMem (
IN VOID *Destination,
IN UINTN Length,
IN UINT8 Value
)
{
memset (Destination, Value, Length);
}
INTN
CommonLibBinderCompareMem (
IN VOID *MemOne,
IN VOID *MemTwo,
IN UINTN Length
)
{
return memcmp (MemOne, MemTwo, Length);
}
BOOLEAN
CommonLibBinderCompareGuid (
IN EFI_GUID *Guid1,
IN EFI_GUID *Guid2
)
{
return CompareGuid (Guid1, Guid2) ? FALSE : TRUE;
}

View File

@@ -0,0 +1,75 @@
/** @file
Copyright (c) 1999 - 2008, 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:
BinderFuncs.h
Abstract:
Prototypes for binder functions that allow common code to be
written which then links to implementation of these functions
which is appropriate for the specific environment that they
are running under.
**/
#ifndef BinderFuncs_h_INCLUDED
#define BinderFuncs_h_INCLUDED
#include "Common/UefiBaseTypes.h"
//
// Binder Function Prototypes
//
// These binding functions must be implemented externally as appropriate for
// the environment that the code will be running under.
//
VOID *
CommonLibBinderAllocate (
IN UINTN Size
);
VOID
CommonLibBinderFree (
IN VOID *Pointer
);
VOID
CommonLibBinderCopyMem (
IN VOID *Destination,
IN VOID *Source,
IN UINTN Length
);
VOID
CommonLibBinderSetMem (
IN VOID *Destination,
IN UINTN Length,
IN UINT8 Value
);
INTN
CommonLibBinderCompareMem (
IN VOID *MemOne,
IN VOID *MemTwo,
IN UINTN Length
);
BOOLEAN
CommonLibBinderCompareGuid (
IN EFI_GUID *Guid1,
IN EFI_GUID *Guid2
);
#endif // #ifndef CommonLibs_h_INCLUDED

View File

@@ -0,0 +1,584 @@
/** @file
Copyright (c) 2004 - 2008, 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 basic Library Functions
**/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "CommonLib.h"
#include "EfiUtilityMsgs.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) {
Error (NULL, 0, 0001, "Error opening the input file", InputFileName);
return EFI_ABORTED;
}
//
// Go to the end so that we can determine the file size
//
if (fseek (InputFile, 0, SEEK_END)) {
Error (NULL, 0, 0004, "Error reading the input file", InputFileName);
fclose (InputFile);
return EFI_ABORTED;
}
//
// Get the file size
//
FileSize = ftell (InputFile);
if (FileSize == -1) {
Error (NULL, 0, 0003, "Error parsing the input file", 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)) {
Error (NULL, 0, 0004, "Error reading the input file", 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) {
Error (NULL, 0, 0004, "Error reading the input file", InputFileName);
fclose (InputFile);
free (*InputFileImage);
*InputFileImage = NULL;
return EFI_ABORTED;
}
//
// Close the file
//
fclose (InputFile);
return EFI_SUCCESS;
}
EFI_STATUS
PutFileImage (
IN CHAR8 *OutputFileName,
IN CHAR8 *OutputFileImage,
IN UINT32 BytesToWrite
)
/*++
Routine Description:
This function opens a file and writes OutputFileImage into the file.
Arguments:
OutputFileName The name of the file to write.
OutputFileImage A pointer to the memory buffer.
BytesToWrite 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 *OutputFile;
UINT32 BytesWrote;
//
// Verify input parameters.
//
if (OutputFileName == NULL || strlen (OutputFileName) == 0 || OutputFileImage == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Open the file and copy contents into a memory buffer.
//
//
// Open the file
//
OutputFile = fopen (OutputFileName, "wb");
if (OutputFile == NULL) {
Error (NULL, 0, 0001, "Error opening the output file", OutputFileName);
return EFI_ABORTED;
}
//
// Write all of the file contents.
//
BytesWrote = fwrite (OutputFileImage, sizeof (UINT8), BytesToWrite, OutputFile);
if (BytesWrote != sizeof (UINT8) * BytesToWrite) {
Error (NULL, 0, 0002, "Error writing the output file", OutputFileName);
fclose (OutputFile);
return EFI_ABORTED;
}
//
// Close the file
//
fclose (OutputFile);
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 UINTN 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) {
Error (NULL, 0, 2000, "Invalid parameter", "PrintGuidToBuffer() called with a NULL value");
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) {
Error (NULL, 0, 2000, "Invalid parameter", "PrintGuidToBuffer() called with a NULL value");
return EFI_INVALID_PARAMETER;
}
if (BufferLen < PRINTED_GUID_BUFFER_SIZE) {
Error (NULL, 0, 2000, "Invalid parameter", "PrintGuidToBuffer() called with invalid buffer size");
return EFI_BUFFER_TOO_SMALL;
}
if (Uppercase) {
sprintf (
(CHAR8 *)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 (
(CHAR8 *)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;
}
#ifdef __GNUC__
size_t _filelength(int fd)
{
struct stat stat_buf;
fstat(fd, &stat_buf);
return stat_buf.st_size;
}
#ifndef __CYGWIN__
char *strlwr(char *s)
{
char *p = s;
for(;*s;s++) {
*s = tolower(*s);
}
return p;
}
#endif
#endif

View File

@@ -0,0 +1,172 @@
/** @file
Copyright (c) 2004 - 2008, 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 <Common/UefiBaseTypes.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
)
;
EFI_STATUS
PutFileImage (
IN CHAR8 *OutputFileName,
IN CHAR8 *OutputFileImage,
IN UINT32 BytesToWrite
)
;
/*++
Routine Description:
This function opens a file and writes OutputFileImage into the file.
Arguments:
OutputFileName The name of the file to write.
OutputFileImage A pointer to the memory buffer.
BytesToWrite 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.
**/
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
)
;
#define ASSERT(x) assert(x)
#ifdef __GNUC__
#include <stdio.h>
#include <sys/stat.h>
#define stricmp strcasecmp
#define _stricmp strcasecmp
#define strnicmp strncasecmp
#define strcmpi strcasecmp
size_t _filelength(int fd);
#ifndef __CYGWIN__
char *strlwr(char *s);
#endif
#endif
//
// On windows, mkdir only has one parameter.
// On unix, it has two parameters
//
#if defined(__GNUC__)
#define mkdir(dir, perm) mkdir(dir, perm)
#else
#define mkdir(dir, perm) mkdir(dir)
#endif
#endif

View File

@@ -0,0 +1,95 @@
/** @file
Copyright (c) 2004 - 2008, 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_
#include <string.h>
#include <stdlib.h>
#include "CommonLib.h"
#include <Common/UefiBaseTypes.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,326 @@
/** @file
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 "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,54 @@
/** @file
Copyright (c) 2004 - 2008, 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
#include <Common/UefiBaseTypes.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,982 @@
/** @file
Copyright (c) 2004 - 2008, 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)
for Efi and Tiano compress algorithm.
--*/
#include <stdlib.h>
#include <string.h>
#include "Decompress.h"
//
// Decompression algorithm begins here
//
#define BITBUFSIZ 32
#define MAXMATCH 256
#define THRESHOLD 3
#define CODE_BIT 16
#define BAD_TABLE - 1
//
// C: Char&Len Set; P: Position Set; T: exTra Set
//
#define NC (0xff + MAXMATCH + 2 - THRESHOLD)
#define CBIT 9
#define EFIPBIT 4
#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];
} SCRATCH_DATA;
STATIC UINT16 mPbit = EFIPBIT;
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
NumOfBit - 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++;
}
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);
CharC--;
while ((INT16) (CharC) >= 0) {
Sd->mPTLen[Index++] = 0;
CharC--;
}
}
}
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);
}
CharC--;
while ((INT16) (CharC) >= 0) {
Sd->mCLen[Index++] = 0;
CharC--;
}
} 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, 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
//
Sd->mDstBase[Sd->mOutBuf++] = (UINT8) CharC;
if (Sd->mOutBuf >= Sd->mOrigSize) {
return ;
}
} 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 implementation of EFI_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
)
/*++
Routine Description:
The implementation Efi and Tiano 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.
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 (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;
}
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
EfiGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
)
/*++
Routine Description:
The implementation Efi Decompress 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
--*/
{
return GetInfo (Source, SrcSize, DstSize, ScratchSize);
}
EFI_STATUS
TianoGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
)
/*++
Routine Description:
The implementation Tiano Decompress 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
--*/
{
return GetInfo (Source, SrcSize, DstSize, ScratchSize);
}
EFI_STATUS
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 of Efi 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.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
{
mPbit = EFIPBIT;
return Decompress (Source, SrcSize, Destination, DstSize, Scratch, ScratchSize);
}
EFI_STATUS
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 of Tiano 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.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
--*/
{
mPbit = MAXPBIT;
return Decompress (Source, SrcSize, Destination, DstSize, Scratch, ScratchSize);
}
EFI_STATUS
Extract (
IN VOID *Source,
IN UINT32 SrcSize,
OUT VOID **Destination,
OUT UINT32 *DstSize,
IN UINTN Algorithm
)
{
VOID *Scratch;
UINT32 ScratchSize;
EFI_STATUS Status;
Status = EFI_SUCCESS;
switch (Algorithm) {
case 0:
*Destination = (VOID *)malloc(SrcSize);
if (*Destination != NULL) {
memcpy(*Destination, Source, SrcSize);
} else {
Status = EFI_OUT_OF_RESOURCES;
}
break;
case 1:
Status = EfiGetInfo(Source, SrcSize, DstSize, &ScratchSize);
if (Status == EFI_SUCCESS) {
Scratch = (VOID *)malloc(ScratchSize);
*Destination = (VOID *)malloc(*DstSize);
if (Scratch != NULL && *Destination != NULL) {
Status = EfiDecompress(Source, SrcSize, *Destination, *DstSize, Scratch, ScratchSize);
} else {
Status = EFI_OUT_OF_RESOURCES;
}
}
break;
case 2:
Status = TianoGetInfo(Source, SrcSize, DstSize, &ScratchSize);
if (Status == EFI_SUCCESS) {
Scratch = (VOID *)malloc(ScratchSize);
*Destination = (VOID *)malloc(*DstSize);
if (Scratch != NULL && *Destination != NULL) {
Status = TianoDecompress(Source, SrcSize, *Destination, *DstSize, Scratch, ScratchSize);
} else {
Status = EFI_OUT_OF_RESOURCES;
}
}
break;
default:
Status = EFI_INVALID_PARAMETER;
}
return Status;
}

View File

@@ -0,0 +1,172 @@
/** @file
Copyright (c) 2006 - 2008, 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 compression routine
**/
#ifndef _EFI_DECOMPRESS_H
#define _EFI_DECOMPRESS_H
#include <Common/UefiBaseTypes.h>
EFI_STATUS
EfiGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
);
/**
Routine Description:
The implementation Efi Decompress 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
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 of Efi 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.
Returns:
EFI_SUCCESS - Decompression is successfull
EFI_INVALID_PARAMETER - The source data is corrupted
**/
EFI_STATUS
TianoGetInfo (
IN VOID *Source,
IN UINT32 SrcSize,
OUT UINT32 *DstSize,
OUT UINT32 *ScratchSize
);
/**
Routine Description:
The implementation Tiano Decompress 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
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 of Tiano 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.
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
);
EFI_STATUS
Extract (
IN VOID *Source,
IN UINT32 SrcSize,
OUT VOID **Destination,
OUT UINT32 *DstSize,
IN UINTN Algorithm
);
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,929 @@
/** @file
Copyright (c) 2004 - 2008, 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 <time.h>
#include "EfiUtilityMsgs.h"
//
// Declare module globals for keeping track of the the utility's
// name and other settings.
//
STATIC STATUS mStatus = STATUS_SUCCESS;
STATIC CHAR8 mUtilityName[50] = { 0 };
STATIC UINT32 mPrintLogLevel = INFO_LOG_LEVEL;
STATIC CHAR8 *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 (
CHAR8 *Type,
CHAR8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
CHAR8 *Text,
CHAR8 *MsgFmt,
va_list List
);
STATIC
VOID
PrintLimitExceeded (
VOID
);
VOID
Error (
CHAR8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
CHAR8 *Text,
CHAR8 *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,
CHAR8 *Text,
CHAR8 *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,
CHAR8 *OffendingText,
CHAR8 *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);
//
// Don't set warning status accordingly
//
// if (mStatus < STATUS_WARNING) {
// mStatus = STATUS_WARNING;
// }
}
VOID
Warning (
CHAR8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
CHAR8 *Text,
CHAR8 *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;
//
// Current Print Level not output warning information.
//
if (WARNING_LOG_LEVEL < mPrintLogLevel) {
return;
}
//
// 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);
}
VOID
DebugMsg (
CHAR8 *FileName,
UINT32 LineNumber,
UINT32 MsgLevel,
CHAR8 *Text,
CHAR8 *MsgFmt,
...
)
/*++
Routine Description:
Print a Debug 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)
MsgLevel - Debug message print level (0~9)
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 level is less than current print level, then do nothing.
//
if (MsgLevel < mPrintLogLevel) {
return ;
}
va_start (List, MsgFmt);
PrintMessage ("DEBUG", FileName, LineNumber, 0, Text, MsgFmt, List);
va_end (List);
}
STATIC
VOID
PrintMessage (
CHAR8 *Type,
CHAR8 *FileName,
UINT32 LineNumber,
UINT32 MessageCode,
CHAR8 *Text,
CHAR8 *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
--*/
{
CHAR8 Line[MAX_LINE_LEN];
CHAR8 Line2[MAX_LINE_LEN];
CHAR8 *Cptr;
struct tm *NewTime;
time_t CurrentTime;
//
// init local variable
//
Line[0] = '\0';
Line2[0] = '\0';
//
// 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 {
Cptr = NULL;
}
if (strcmp (Type, "DEBUG") == 0) {
//
// Debug Message requires current time.
//
time (&CurrentTime);
NewTime = localtime (&CurrentTime);
fprintf (stdout, "%04d-%02d-%02d %02d:%02d:%02d",
NewTime->tm_year + 1900,
NewTime->tm_mon + 1,
NewTime->tm_mday,
NewTime->tm_hour,
NewTime->tm_min,
NewTime->tm_sec
);
if (Cptr != NULL) {
sprintf (Line, ": %s", Cptr);
if (LineNumber != 0) {
sprintf (Line2, "(%d)", LineNumber);
strcat (Line, Line2);
}
}
} else {
//
// Error and Warning Information.
//
if (Cptr != NULL) {
if (mUtilityName[0] != '\0') {
fprintf (stdout, "%s...\n", mUtilityName);
}
sprintf (Line, "%s", Cptr);
if (LineNumber != 0) {
sprintf (Line2, "(%d)", LineNumber);
strcat (Line, Line2);
}
} else {
if (mUtilityName[0] != '\0') {
sprintf (Line, "%s", mUtilityName);
}
}
}
//
// Have to print an error code or Visual Studio won't find the
// message for you. It has to be decimal digits too.
//
if (MessageCode != 0) {
sprintf (Line2, ": %s %04d", Type, MessageCode);
} else {
sprintf (Line2, ": %s", Type);
}
strcat (Line, Line2);
fprintf (stdout, "%s", Line);
//
// If offending text was provided, then print it
//
if (Text != NULL) {
fprintf (stdout, ": %s", Text);
}
fprintf (stdout, "\n");
//
// Print formatted message if provided
//
if (MsgFmt != NULL) {
vsprintf (Line2, MsgFmt, List);
fprintf (stdout, " %s\n", Line2);
}
}
STATIC
VOID
PrintSimpleMessage (
CHAR8 *MsgFmt,
va_list List
)
/*++
Routine Description:
Print message into stdout.
Arguments:
MsgFmt - the format string for the message. Can contain formatting
controls for use with varargs.
List - the variable list.
Returns:
None.
--*/
{
CHAR8 Line[MAX_LINE_LEN];
//
// Print formatted message if provided
//
if (MsgFmt != NULL) {
vsprintf (Line, MsgFmt, List);
fprintf (stdout, "%s\n", Line);
}
}
VOID
ParserSetPosition (
CHAR8 *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 (
CHAR8 *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
SetPrintLevel (
UINT32 LogLevel
)
/*++
Routine Description:
Set the printing message Level. This is used by the PrintMsg() function
to determine when/if a message should be printed.
Arguments:
LogLevel - 0~50 to specify the different level message.
Returns:
NA
--*/
{
mPrintLogLevel = LogLevel;
}
VOID
VerboseMsg (
CHAR8 *MsgFmt,
...
)
/*++
Routine Description:
Print a verbose level message.
Arguments:
MsgFmt - the format string for the message. Can contain formatting
controls for use with varargs.
List - the variable list.
Returns:
NA
--*/
{
va_list List;
//
// If the debug level is less than current print level, then do nothing.
//
if (VERBOSE_LOG_LEVEL < mPrintLogLevel) {
return ;
}
va_start (List, MsgFmt);
PrintSimpleMessage (MsgFmt, List);
va_end (List);
}
VOID
NormalMsg (
CHAR8 *MsgFmt,
...
)
/*++
Routine Description:
Print a default level message.
Arguments:
MsgFmt - the format string for the message. Can contain formatting
controls for use with varargs.
List - the variable list.
Returns:
NA
--*/
{
va_list List;
//
// If the debug level is less than current print level, then do nothing.
//
if (INFO_LOG_LEVEL < mPrintLogLevel) {
return ;
}
va_start (List, MsgFmt);
PrintSimpleMessage (MsgFmt, List);
va_end (List);
}
VOID
KeyMsg (
CHAR8 *MsgFmt,
...
)
/*++
Routine Description:
Print a key level message.
Arguments:
MsgFmt - the format string for the message. Can contain formatting
controls for use with varargs.
List - the variable list.
Returns:
NA
--*/
{
va_list List;
//
// If the debug level is less than current print level, then do nothing.
//
if (KEY_LOG_LEVEL < mPrintLogLevel) {
return ;
}
va_start (List, MsgFmt);
PrintSimpleMessage (MsgFmt, List);
va_end (List);
}
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
)
{
CHAR8 *ArgStr = "ArgString";
INTN 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,166 @@
/** @file
Copyright (c) 2004 - 2008, 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_
#include <Common/UefiBaseTypes.h>
//
// Log message print Level
//
#define VERBOSE_LOG_LEVEL 15
#define WARNING_LOG_LEVEL 15
#define INFO_LOG_LEVEL 20
#define KEY_LOG_LEVEL 40
#define ERROR_LOG_LEVLE 50
//
// 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;
#define MAX_LINE_LEN 0x200
#define MAXIMUM_INPUT_FILE_NUM 10
#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 (
CHAR8 *ProgramName
)
;
VOID
Error (
CHAR8 *FileName,
UINT32 LineNumber,
UINT32 ErrorCode,
CHAR8 *OffendingText,
CHAR8 *MsgFmt,
...
)
;
VOID
Warning (
CHAR8 *FileName,
UINT32 LineNumber,
UINT32 WarningCode,
CHAR8 *OffendingText,
CHAR8 *MsgFmt,
...
)
;
VOID
DebugMsg (
CHAR8 *FileName,
UINT32 LineNumber,
UINT32 MsgLevel,
CHAR8 *OffendingText,
CHAR8 *MsgFmt,
...
)
;
VOID
VerboseMsg (
CHAR8 *MsgFmt,
...
);
VOID
NormalMsg (
CHAR8 *MsgFmt,
...
);
VOID
KeyMsg (
CHAR8 *MsgFmt,
...
);
VOID
SetPrintLevel (
UINT32 LogLevel
);
VOID
ParserSetPosition (
CHAR8 *SourceFileName,
UINT32 LineNum
)
;
VOID
ParserError (
UINT32 ErrorCode,
CHAR8 *OffendingText,
CHAR8 *MsgFmt,
...
)
;
VOID
ParserWarning (
UINT32 ErrorCode,
CHAR8 *OffendingText,
CHAR8 *MsgFmt,
...
)
;
VOID
SetPrintLimits (
UINT32 NumErrors,
UINT32 NumWarnings,
UINT32 NumWarningsPlusErrors
)
;
#ifdef __cplusplus
}
#endif
#endif // #ifndef _EFI_UTILITY_MSGS_H_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,166 @@
/** @file
Copyright (c) 1999 - 2008, 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:
FirmwareVolumeBufferLib.h
Abstract:
EFI Firmware Volume routines which work on a Fv image in buffers.
**/
#ifndef FirmwareVolumeBuffer_h_INCLUDED
#define FirmwareVolumeBuffer_h_INCLUDED
#include "Common/UefiBaseTypes.h"
#include "Common/PiFirmwareFile.h"
#include "Common/PiFirmwareVolume.h"
EFI_STATUS
FvBufAddFile (
IN OUT VOID *Fv,
IN VOID *File
);
EFI_STATUS
FvBufAddFileWithExtend (
IN OUT VOID **Fv,
IN VOID *File
);
EFI_STATUS
FvBufAddVtfFile (
IN OUT VOID *Fv,
IN VOID *File
);
EFI_STATUS
FvBufChecksumFile (
IN OUT VOID *FfsFile
);
EFI_STATUS
FvBufChecksumHeader (
IN OUT VOID *Fv
);
EFI_STATUS
FvBufClearAllFiles (
IN OUT VOID *Fv
);
VOID
FvBufCompact3ByteSize (
OUT VOID* SizeDest,
IN UINT32 Size
);
EFI_STATUS
FvBufCountSections (
IN VOID* FfsFile,
IN UINTN* Count
);
EFI_STATUS
FvBufDuplicate (
IN VOID *SourceFv,
IN OUT VOID **DestinationFv
);
UINT32
FvBufExpand3ByteSize (
IN VOID* Size
);
EFI_STATUS
FvBufExtend (
IN VOID **Fv,
IN UINTN Size
);
EFI_STATUS
FvBufFindFileByName (
IN VOID *Fv,
IN EFI_GUID *Name,
OUT VOID **File
);
EFI_STATUS
FvBufFindFileByType (
IN VOID *Fv,
IN EFI_FV_FILETYPE Type,
OUT VOID **File
);
EFI_STATUS
FvBufFindNextFile (
IN VOID *Fv,
IN OUT UINTN *Key,
OUT VOID **File
);
EFI_STATUS
FvBufFindNextSection (
IN VOID *SectionsStart,
IN UINTN TotalSectionsSize,
IN OUT UINTN *Key,
OUT VOID **Section
);
EFI_STATUS
FvBufFindSectionByType (
IN VOID *FfsFile,
IN UINT8 Type,
OUT VOID **Section
);
EFI_STATUS
FvBufGetFileRawData (
IN VOID* FfsFile,
OUT VOID** RawData,
OUT UINTN* RawDataSize
);
EFI_STATUS
FvBufGetSize (
IN VOID *Fv,
OUT UINTN *Size
);
EFI_STATUS
FvBufPackageFreeformRawFile (
IN EFI_GUID* Filename,
IN VOID* RawData,
IN UINTN RawDataSize,
OUT VOID** FfsFile
);
EFI_STATUS
FvBufRemoveFile (
IN OUT VOID *Fv,
IN EFI_GUID *Name
);
EFI_STATUS
FvBufUnifyBlockSizes (
IN OUT VOID *Fv,
IN UINTN BlockSize
);
EFI_STATUS
FvBufShrinkWrap (
IN VOID *Fv
);
#endif // #ifndef FirmwareVolumeBuffer_h_INCLUDED

View File

@@ -0,0 +1,850 @@
/** @file
Copyright (c) 2004 - 2008, 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;
CHAR8 FileGuidString[80];
//
// 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;
}
//
// File Guid String Name
//
PrintGuidToBuffer (FileName, (UINT8 *)FileGuidString, sizeof (FileGuidString), TRUE);
//
// 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, 0003, "error parsing FV image", "FFS file with Guid %s can't be found", FileGuidString);
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, 0003, "error parsing FV image", "FFS file with Guid %s can't be found", FileGuidString);
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, 0003, "error parsing FV image", "FFS file with FileType 0x%x can't be found", FileType);
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, 0003, "error parsing FV image", "FFS file with FileType 0x%x can't be found", FileType);
return EFI_ABORTED;
}
}
*File = NULL;
return EFI_SUCCESS;
}
EFI_STATUS
SearchSectionByType (
IN EFI_FILE_SECTION_POINTER FirstSection,
IN UINT8 *SearchEnd,
IN EFI_SECTION_TYPE SectionType,
IN OUT UINTN *StartIndex,
IN UINTN Instance,
OUT EFI_FILE_SECTION_POINTER *Section
)
/*++
Routine Description:
Helper function to search a sequence of sections from the section pointed
by FirstSection to SearchEnd for the Instance-th section of type SectionType.
The current counter is saved in StartIndex and when the section is found, it's
saved in Section. GUID-defined sections, if special processing is not required,
are searched recursively in a depth-first manner.
Arguments:
FirstSection The first section to start searching from.
SearchEnd The end address to stop search.
SectionType The type of section to search.
StartIndex The current counter is saved.
Instance The requested n-th section number.
Section The found section returned.
Returns:
EFI_SUCCESS The function completed successfully.
EFI_NOT_FOUND The section is not found.
--*/
{
EFI_FILE_SECTION_POINTER CurrentSection;
EFI_FILE_SECTION_POINTER InnerSection;
EFI_STATUS Status;
UINTN SectionSize;
CurrentSection = FirstSection;
while ((UINTN) CurrentSection.CommonHeader < (UINTN) SearchEnd) {
if (CurrentSection.CommonHeader->Type == SectionType) {
(*StartIndex)++;
}
if (*StartIndex == Instance) {
*Section = CurrentSection;
return EFI_SUCCESS;
}
//
// If the requesting section is not GUID-defined and
// we find a GUID-defined section that doesn't need
// special processing, go ahead to search the requesting
// section inside the GUID-defined section.
//
if (SectionType != EFI_SECTION_GUID_DEFINED &&
CurrentSection.CommonHeader->Type == EFI_SECTION_GUID_DEFINED &&
!(CurrentSection.GuidDefinedSection->Attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED)) {
InnerSection.CommonHeader = (EFI_COMMON_SECTION_HEADER *)
((UINTN) CurrentSection.CommonHeader + CurrentSection.GuidDefinedSection->DataOffset);
SectionSize = CurrentSection.CommonHeader->Size[0] +
(CurrentSection.CommonHeader->Size[1] << 8) +
(CurrentSection.CommonHeader->Size[2] << 16);
Status = SearchSectionByType (
InnerSection,
(UINT8 *) ((UINTN) CurrentSection.CommonHeader + SectionSize),
SectionType,
StartIndex,
Instance,
Section
);
if (!EFI_ERROR (Status)) {
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));
}
return EFI_NOT_FOUND;
}
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.
GUID-defined sections, if special processing is not needed, are handled in a
depth-first manner.
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, 0006, "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));
//
// Depth-first manner to find section file.
//
Status = SearchSectionByType (
CurrentSection,
(UINT8 *) ((UINTN) File + GetLength (File->Size)),
SectionType,
&SectionCount,
Instance,
Section
);
if (!EFI_ERROR (Status)) {
return EFI_SUCCESS;
} else {
//
// 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, 0006, "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, 0006, "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;
UINT8 SavedChecksum;
UINT8 SavedState;
UINT8 FileGuidString[80];
//
// 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);
//
// 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, 0006, "invalid FFS file header checksum", "Ffs file with Guid %s", FileGuidString);
return EFI_ABORTED;
}
//
// Verify file checksum
//
if (FfsHeader->Attributes & FFS_ATTRIB_CHECKSUM) {
//
// Verify file data checksum
//
FileLength = GetLength (FfsHeader->Size);
Checksum = CalculateSum8 ((UINT8 *) FfsHeader, FileLength);
Checksum = (UINT8) (Checksum - FfsHeader->State);
if (Checksum != 0) {
Error (NULL, 0, 0006, "invalid FFS file checksum", "Ffs file with Guid %s", FileGuidString);
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, 0006, "invalid fixed FFS file header checksum", "Ffs file with Guid %s", FileGuidString);
return EFI_ABORTED;
}
}
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_FVB2_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,178 @@
/** @file
Copyright (c) 2004 - 2008, 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 <string.h>
#include <Common/UefiBaseTypes.h>
#include <Common/PiFirmwareFile.h>
#include <Common/PiFirmwareVolume.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,28 @@
ARCH ?= IA32
MAKEROOT ?= ..
# VPATH = ..
LIBNAME = Common
OBJECTS = \
BasePeCoff.o \
BinderFuncs.o \
CommonLib.o \
Crc32.o \
Decompress.o \
EfiCompress.o \
EfiUtilityMsgs.o \
FirmwareVolumeBuffer.o \
FvLib.o \
MemoryFile.o \
MyAlloc.o \
OsPath.o \
ParseGuidedSectionTools.o \
ParseInf.o \
PeCoffLoaderEx.o \
SimpleFileParsing.o \
StringFuncs.o \
TianoCompress.o
include $(MAKEROOT)/Makefiles/lib.makefile

View File

@@ -0,0 +1,30 @@
!INCLUDE ..\Makefiles\ms.common
# VPATH = ..
LIBNAME = Common
OBJECTS = \
BasePeCoff.obj \
BinderFuncs.obj \
CommonLib.obj \
Crc32.obj \
Decompress.obj \
EfiCompress.obj \
EfiUtilityMsgs.obj \
FirmwareVolumeBuffer.obj \
FvLib.obj \
MemoryFile.obj \
MyAlloc.obj \
OsPath.obj \
ParseGuidedSectionTools.obj \
ParseInf.obj \
PeCoffLoaderEx.obj \
SimpleFileParsing.obj \
StringFuncs.obj \
TianoCompress.obj
!INCLUDE ..\Makefiles\ms.lib

View File

@@ -0,0 +1,260 @@
/** @file
Copyright (c) 2004 - 2008, 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:
MemoryFile.c
Abstract:
This contains some useful functions for accessing files.
**/
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "CommonLib.h"
#include "MemoryFile.h"
//
// Local (static) function prototypes
//
STATIC
VOID
CheckMemoryFileState (
IN EFI_HANDLE InputMemoryFile
);
//
// Function implementations
//
EFI_STATUS
GetMemoryFile (
IN CHAR8 *InputFileName,
OUT EFI_HANDLE *OutputMemoryFile
)
/*++
Routine Description:
This opens a file, reads it into memory and returns a memory file
object.
Arguments:
InputFile Memory file image.
OutputMemoryFile Handle to memory file
Returns:
EFI_STATUS
OutputMemoryFile is valid if !EFI_ERROR
--*/
{
EFI_STATUS Status;
CHAR8 *InputFileImage;
UINT32 BytesRead;
MEMORY_FILE *NewMemoryFile;
Status = GetFileImage (InputFileName, &InputFileImage, &BytesRead);
if (EFI_ERROR (Status)) {
return Status;
}
NewMemoryFile = malloc (sizeof (*NewMemoryFile));
if (NewMemoryFile == NULL) {
return EFI_OUT_OF_RESOURCES;
}
NewMemoryFile->FileImage = InputFileImage;
NewMemoryFile->CurrentFilePointer = InputFileImage;
NewMemoryFile->Eof = InputFileImage + BytesRead;
*OutputMemoryFile = (EFI_HANDLE)NewMemoryFile;
CheckMemoryFileState (*OutputMemoryFile);
return EFI_SUCCESS;
}
EFI_STATUS
FreeMemoryFile (
IN EFI_HANDLE InputMemoryFile
)
/*++
Routine Description:
Frees all memory associated with the input memory file.
Arguments:
InputMemoryFile Handle to memory file
Returns:
EFI_STATUS
--*/
{
MEMORY_FILE *MemoryFile;
CheckMemoryFileState (InputMemoryFile);
MemoryFile = (MEMORY_FILE*)InputMemoryFile;
free (MemoryFile->FileImage);
//
// Invalidate state of MEMORY_FILE structure to catch invalid usage.
//
memset (MemoryFile, 0xcc, sizeof (*MemoryFile));
MemoryFile->Eof -= 1;
free (MemoryFile);
return EFI_SUCCESS;
}
CHAR8 *
ReadMemoryFileLine (
IN EFI_HANDLE InputMemoryFile
)
/*++
Routine Description:
This function reads a line from the memory file. The newline characters
are stripped and a null terminated string is returned.
If the string pointer returned is non-NULL, then the caller must free the
memory associated with this string.
Arguments:
InputMemoryFile Handle to memory file
Returns:
NULL if error or EOF
NULL character termincated string otherwise (MUST BE FREED BY CALLER)
--*/
{
CHAR8 *EndOfLine;
UINTN CharsToCopy;
MEMORY_FILE *InputFile;
UINTN BytesToEof;
CHAR8 *OutputString;
//
// Verify input parameters are not null
//
CheckMemoryFileState (InputMemoryFile);
InputFile = (MEMORY_FILE*)InputMemoryFile;
//
// Check for end of file condition
//
if (InputFile->CurrentFilePointer >= InputFile->Eof) {
return NULL;
}
//
// Determine the number of bytes remaining until the EOF
//
BytesToEof = InputFile->Eof - InputFile->CurrentFilePointer;
//
// Find the next newline char
//
EndOfLine = memchr (InputFile->CurrentFilePointer, '\n', BytesToEof);
//
// 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 {
//
// Newline found in the file.
//
CharsToCopy = EndOfLine - InputFile->CurrentFilePointer;
}
OutputString = malloc (CharsToCopy);
if (OutputString == NULL) {
return NULL;
}
//
// Copy the line.
//
memcpy (OutputString, InputFile->CurrentFilePointer, CharsToCopy);
//
// Add the null termination over the 0x0D
//
if (OutputString[CharsToCopy - 1] == '\r') {
OutputString[CharsToCopy - 1] = '\0';
} else {
OutputString[CharsToCopy] = '\0';
}
//
// Increment the current file pointer (include the 0x0A)
//
InputFile->CurrentFilePointer += CharsToCopy + 1;
CheckMemoryFileState (InputMemoryFile);
//
// Return the string
//
return OutputString;
}
STATIC
VOID
CheckMemoryFileState (
IN EFI_HANDLE InputMemoryFile
)
{
MEMORY_FILE *MemoryFile;
assert (InputMemoryFile != NULL);
MemoryFile = (MEMORY_FILE*)InputMemoryFile;
assert (MemoryFile->FileImage != NULL);
assert (MemoryFile->CurrentFilePointer != NULL);
assert (MemoryFile->Eof != NULL);
assert (MemoryFile->Eof >= MemoryFile->FileImage);
assert (MemoryFile->CurrentFilePointer >= MemoryFile->FileImage);
assert (MemoryFile->CurrentFilePointer <= MemoryFile->Eof);
}

View File

@@ -0,0 +1,122 @@
/** @file
Copyright (c) 2004 - 2008, 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:
MemoryFile.h
Abstract:
Header file for helper functions useful for accessing files.
**/
#ifndef _EFI_MEMORY_FILE_H
#define _EFI_MEMORY_FILE_H
#include <stdio.h>
#include <stdlib.h>
#include <Common/UefiBaseTypes.h>
#ifndef _MAX_PATH
#define _MAX_PATH 500
#endif
//
// Common data structures
//
typedef struct {
CHAR8 *FileImage;
CHAR8 *Eof;
CHAR8 *CurrentFilePointer;
} MEMORY_FILE;
//
// Functions declarations
//
EFI_STATUS
GetMemoryFile (
IN CHAR8 *InputFileName,
OUT EFI_HANDLE *OutputMemoryFile
)
;
/**
Routine Description:
This opens a file, reads it into memory and returns a memory file
object.
Arguments:
InputFile Memory file image.
OutputMemoryFile Handle to memory file
Returns:
EFI_STATUS
OutputMemoryFile is valid if !EFI_ERROR
**/
EFI_STATUS
FreeMemoryFile (
IN EFI_HANDLE InputMemoryFile
)
;
/**
Routine Description:
Frees all memory associated with the input memory file.
Arguments:
InputMemoryFile Handle to memory file
Returns:
EFI_STATUS
**/
CHAR8 *
ReadMemoryFileLine (
IN EFI_HANDLE InputMemoryFile
)
;
/**
Routine Description:
This function reads a line from the memory file. The newline characters
are stripped and a null terminated string is returned.
If the string pointer returned is non-NULL, then the caller must free the
memory associated with this string.
Arguments:
InputMemoryFile Handle to memory file
Returns:
NULL if error or EOF
NULL character termincated string otherwise (MUST BE FREED BY CALLER)
**/
#endif

View File

@@ -0,0 +1,516 @@
/** @file
Copyright (c) 2004 - 2008, 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=%s, Line=%u)"
"Invalid parameter(s).\n",
Final,
File,
(UINT32)Line
);
exit (1);
}
if (strlen ((CHAR8 *)File) == 0) {
printf (
"\nMyCheck(Final=%u, File=%s, Line=%u)"
"Invalid parameter.\n",
Final,
File,
(UINT32)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,
(UINT32)Line,
Tmp->File,
(UINT32)Tmp->Line,
(UINT32)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,
(UINT32)Line
);
for (Tmp = MyAllocData; Tmp != NULL; Tmp = Tmp->Next) {
printf (
"File=%s, Line=%u, nSize=%u, Head=%xh, Tail=%xh\n",
Tmp->File,
(UINT32)Tmp->Line,
(UINT32)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=%s, Line=%u)"
"\nInvalid parameter(s).\n",
(UINT32)Size,
File,
(UINT32)Line
);
exit (1);
}
Len = strlen ((CHAR8 *)File);
if (Len == 0) {
printf (
"\nMyAlloc(Size=%u, File=%s, Line=%u)"
"\nInvalid parameter.\n",
(UINT32)Size,
File,
(UINT32)Line
);
exit (1);
}
//
// Check the allocation list for corruption.
//
MyCheck (0, (UINT8 *)__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",
(UINT32)Size,
File,
(UINT32)Line
);
exit (1);
}
//
// Fill in the new entry.
//
Tmp->File = ((UINT8 *) Tmp) + sizeof (MY_ALLOC_STRUCT);
strcpy ((CHAR8 *)Tmp->File, (CHAR8 *)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=%p, Size=%u, File=%s, Line=%u)"
"\nInvalid parameter(s).\n",
Ptr,
(UINT32)Size,
File,
(UINT32)Line
);
exit (1);
}
if (strlen ((CHAR8 *)File) == 0) {
printf (
"\nMyRealloc(Ptr=%p, Size=%u, File=%s, Line=%u)"
"\nInvalid parameter.\n",
Ptr,
(UINT32)Size,
File,
(UINT32)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=%p, Size=%u, File=%s, Line=%u)"
"\nCould not find buffer.\n",
Ptr,
(UINT32)Size,
File,
(UINT32)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, (UINT8 *)__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=%p, File=%s, Line=%u)"
"\nInvalid parameter(s).\n",
Ptr,
File,
(UINT32)Line
);
exit (1);
}
if (strlen ((CHAR8 *)File) == 0) {
printf (
"\nMyFree(Ptr=%p, File=%s, Line=%u)"
"\nInvalid parameter.\n",
Ptr,
File,
(UINT32)Line
);
exit (1);
}
//
// Freeing NULL is always valid.
//
if (Ptr == NULL) {
return ;
}
//
// Fail if nothing is allocated.
//
if (MyAllocData == NULL) {
printf (
"\nMyFree(Ptr=%p, File=%s, Line=%u)"
"\nCalled before memory allocated.\n",
Ptr,
File,
(UINT32)Line
);
exit (1);
}
//
// Check for corrupted allocation list.
//
MyCheck (0, (UINT8 *)__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=%p, File=%s, Line=%u)\n"
"\nNot found.\n",
Ptr,
File,
(UINT32)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 @@
/** @file
Copyright (c) 2004 - 2008, 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 <Common/BaseTypes.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,307 @@
/** @file
Copyright (c) 2007 - 2008, 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:
StringFuncs.c
Abstract:
Functions useful to operate file directories by parsing file path.
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "OsPath.h"
//
// Functions implementations
//
#if 0
//
// BUGBUG: Not fully implemented yet.
//
CHAR8*
OsPathDirName (
IN CHAR8 *FilePath
)
/*++
Routine Description:
This function returns the directory path which contains the particular path.
Some examples:
"a/b/c" -> "a/b"
"a/b/c/" -> "a/b"
"a" -> "."
"." -> ".."
"/" -> NULL
This function does not check for the existence of the file.
The caller must free the string returned.
Arguments:
FilePath Path name of file to get the parent directory for.
Returns:
NULL if error
--*/
{
CHAR8 *Return;
CHAR8 *Pos;
CHAR8 Char;
UINTN Length;
INTN Offset;
Length = strlen (FilePath);
if (Length == 0) {
return NULL;
}
//
// Check for the root directory case
//
if (
(Length == 3 && isalpha (FilePath[0]) && (strcmp(FilePath + 1, ":\\") == 0)) ||
(strcmp(FilePath, "/") == 0)
) {
return NULL;
}
//
// If the path ends with a path separator, then just append ".."
//
Char = FilePath[Length - 1];
if (Char == '/' || Char == '\\') {
return OsPathJoin (FilePath, "..");
}
//
//
//
for (Offset = Length; Offset > 0; Offset--) {
if ((Return[Offset] == '/') || (Return[Offset] == '\\')) {
Return[Offset] = '\0';
return Return;
}
}
}
#endif
#if 0
//
// BUGBUG: Not fully implemented yet.
//
VOID
OsPathNormPathInPlace (
IN CHAR8 *Path
)
/*++
Routine Description:
This function returns the directory path which contains the particular path.
Some examples:
"a/b/../c" -> "a/c"
"a/b//c" -> "a/b/c"
"a/./b" -> "a/b"
This function does not check for the existence of the file.
Arguments:
Path Path name of file to normalize
Returns:
The string is altered in place.
--*/
{
CHAR8 *Pos;
INTN Offset;
BOOLEAN TryAgain;
UINTN Length;
UINTN Remaining;
UINTN SubLength;
do {
TryAgain = FALSE;
Length = strlen (Path);
for (Offset = 0; Offset < Length; Offset++) {
Remaining = Length - Offset;
//
// Collapse '//' -> '/'
//
if (
(Remaining >= 2) &&
((Offset > 0) || (Path[0] != '\\')) &&
IsDirSep (Path[Offset]) && IsDirSep (Path[Offset + 1])
) {
memmove (&Path[Offset], &Path[Offset + 1], Remaining);
TryAgain = TRUE;
break;
}
//
// Collapse '/./' -> '/'
//
if ((Remaining >= 3) && IsDirSep (Path[Offset]) &&
(Path[Offset + 1] == '.') && IsDirSep (Path[Offset + 2])
) {
memmove (&Path[Offset], &Path[Offset + 1], Remaining);
TryAgain = TRUE;
break;
}
//
// Collapse 'a/../b' -> 'b'
//
// BUGBUG: Not implemented yet
}
} while (TryAgain);
Return = CloneString (FilePath);
if (Return == NULL) {
return NULL;
}
Length = strlen (Return);
//
// Check for the root directory case
//
if (
(Length == 3 && isalpha (Return[0]) && (strcmp(Return + 1, ":\\") == 0)) ||
(strcmp(Return, "/") == 0)
) {
free (Return);
return NULL;
}
//
//
//
for (Offset = Length; Offset > 0; Offset--) {
if ((Return[Offset] == '/') || (Return[Offset] == '\\')) {
Return[Offset] = '\0';
return Return;
}
}
}
#endif
CHAR8*
OsPathPeerFilePath (
IN CHAR8 *OldPath,
IN CHAR8 *Peer
)
/*++
Routine Description:
This function replaces the final portion of a path with an alternative
'peer' filename. For example:
"a/b/../c", "peer" -> "a/b/../peer"
"a/b/", "peer" -> "a/b/peer"
"/a", "peer" -> "/peer"
"a", "peer" -> "peer"
This function does not check for the existence of the file.
Arguments:
OldPath Path name of replace the final segment
Peer The new path name to concatinate to become the peer path
Returns:
A CHAR8* string, which must be freed by the caller
--*/
{
CHAR8 *Result;
INTN Offset;
Result = (CHAR8 *) malloc (strlen (OldPath) + strlen (Peer) + 1);
if (Result == NULL) {
return NULL;
}
strcpy (Result, OldPath);
//
// Search for the last '/' or '\' in the string. If found, replace
// everything following it with Peer
//
for (Offset = strlen (Result); Offset >= 0; Offset--) {
if ((Result[Offset] == '/') || (Result[Offset] == '\\')) {
Result[Offset + 1] = '\0';
strcat (Result, Peer);
return Result;
}
}
//
// Neither a '/' nor a '\' was found. Therefore, we simply return Peer.
//
strcpy (Result, Peer);
return Result;
}
BOOLEAN
OsPathExists (
IN CHAR8 *InputFileName
)
/*++
Routine Description:
Checks if a file exists
Arguments:
InputFileName The name of the file to check for existence
Returns:
TRUE The file exists
FALSE The file does not exist
--*/
{
FILE *InputFile;
InputFile = fopen (InputFileName, "rb");
if (InputFile == NULL) {
return FALSE;
} else {
fclose (InputFile);
return TRUE;
}
}

View File

@@ -0,0 +1,146 @@
/** @file
Copyright (c) 2007 - 2008, 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:
OsPath.h
Abstract:
Header file for helper functions useful to operate file directories
by parsing file path.
**/
#ifndef _EFI_OS_PATH_H
#define _EFI_OS_PATH_H
#include <Common/UefiBaseTypes.h>
//
// Functions declarations
//
CHAR8*
OsPathDirName (
IN CHAR8 *FilePath
)
;
/**
Routine Description:
This function returns the directory path which contains the particular path.
Some examples:
"a/b/c" -> "a/b"
"a/b/c/" -> "a/b"
"a" -> "."
"." -> ".."
"/" -> NULL
This function does not check for the existence of the file.
The caller must free the string returned.
Arguments:
FilePath Path name of file to get the parent directory for.
Returns:
NULL if error
**/
VOID
OsPathNormPathInPlace (
IN CHAR8 *Path
)
;
/**
Routine Description:
This function returns the directory path which contains the particular path.
Some examples:
"a/b/../c" -> "a/c"
"a/b//c" -> "a/b/c"
"a/./b" -> "a/b"
This function does not check for the existence of the file.
Arguments:
Path Path name of file to normalize
Returns:
The string is altered in place.
**/
CHAR8*
OsPathPeerFilePath (
IN CHAR8 *OldPath,
IN CHAR8 *Peer
)
;
/**
Routine Description:
This function replaces the final portion of a path with an alternative
'peer' filename. For example:
"a/b/../c", "peer" -> "a/b/../peer"
"a/b/", "peer" -> "a/b/peer"
"/a", "peer" -> "/peer"
"a", "peer" -> "peer"
This function does not check for the existence of the file.
Arguments:
OldPath Path name of replace the final segment
Peer The new path name to concatinate to become the peer path
Returns:
A CHAR8* string, which must be freed by the caller
**/
BOOLEAN
OsPathExists (
IN CHAR8 *InputFileName
)
;
/**
Routine Description:
Checks if a file exists
Arguments:
InputFileName The name of the file to check for existence
Returns:
TRUE The file exists
FALSE The file does not exist
**/
#endif

View File

@@ -0,0 +1,210 @@
/** @file
Copyright (c) 2007 - 2008, 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:
ParseGuidedSectionTools.c
Abstract:
Helper functions for parsing GuidedSectionTools.txt
**/
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "MemoryFile.h"
#include "CommonLib.h"
#include "EfiUtilityMsgs.h"
#include "ParseInf.h"
#include "ParseGuidedSectionTools.h"
#include "StringFuncs.h"
//
// Local types / structures
//
typedef struct _GUID_SEC_TOOL_ENTRY {
EFI_GUID Guid;
CHAR8* Name;
CHAR8* Path;
struct _GUID_SEC_TOOL_ENTRY *Next;
} GUID_SEC_TOOL_ENTRY;
//
// Functin Implementation
//
EFI_HANDLE
ParseGuidedSectionToolsFile (
IN CHAR8 *InputFile
)
/*++
Routine Description:
This function parses the tools_def.txt file. It returns a
EFI_HANDLE object which can be used for the other library
functions and should be passed to FreeParsedGuidedSectionToolsHandle
to free resources when the tools_def.txt information is no
longer needed.
Arguments:
InputFile Path name of file to read
Returns:
NULL if error parsing
A non-NULL EFI_HANDLE otherwise
--*/
{
EFI_STATUS Status;
EFI_HANDLE MemoryFile;
EFI_HANDLE ParsedGuidedSectionTools;
Status = GetMemoryFile (InputFile, &MemoryFile);
if (EFI_ERROR (Status)) {
return NULL;
}
ParsedGuidedSectionTools = ParseGuidedSectionToolsMemoryFile (MemoryFile);
FreeMemoryFile (MemoryFile);
return ParsedGuidedSectionTools;
}
EFI_HANDLE
ParseGuidedSectionToolsMemoryFile (
IN EFI_HANDLE InputFile
)
/*++
Routine Description:
This function parses the tools_def.txt file. It returns a
EFI_HANDLE object which can be used for the other library
functions and should be passed to FreeParsedGuidedSectionToolsHandle
to free resources when the tools_def.txt information is no
longer needed.
Arguments:
InputFile Memory file image.
Returns:
NULL if error or EOF
InputBuffer otherwise
--*/
{
EFI_STATUS Status;
CHAR8 *NextLine;
STRING_LIST *Tool;
EFI_GUID Guid;
GUID_SEC_TOOL_ENTRY *FirstGuidTool;
GUID_SEC_TOOL_ENTRY *LastGuidTool;
GUID_SEC_TOOL_ENTRY *NewGuidTool;
FirstGuidTool = NULL;
while (TRUE) {
NextLine = ReadMemoryFileLine (InputFile);
if (NextLine == NULL) {
break;
}
Status = StripInfDscStringInPlace (NextLine);
if (EFI_ERROR (Status)) {
break;
}
if (NextLine[0] == '\0') {
continue;
}
Tool = SplitStringByWhitespace (NextLine);
if ((Tool != NULL) &&
(Tool->Count == 3)
) {
Status = StringToGuid (Tool->Strings[0], &Guid);
if (!EFI_ERROR (Status)) {
NewGuidTool = malloc (sizeof (GUID_SEC_TOOL_ENTRY));
if (NewGuidTool != NULL) {
memcpy (&(NewGuidTool->Guid), &Guid, sizeof (Guid));
NewGuidTool->Name = CloneString(Tool->Strings[1]);
NewGuidTool->Path = CloneString(Tool->Strings[2]);
NewGuidTool->Next = NULL;
}
if (FirstGuidTool == NULL) {
FirstGuidTool = NewGuidTool;
} else {
LastGuidTool->Next = NewGuidTool;
}
LastGuidTool = NewGuidTool;
}
FreeStringList (Tool);
}
}
return FirstGuidTool;
}
CHAR8*
LookupGuidedSectionToolPath (
IN EFI_HANDLE ParsedGuidedSectionToolsHandle,
IN EFI_GUID *SectionGuid
)
/*++
Routine Description:
This function looks up the appropriate tool to use for extracting
a GUID defined FV section.
Arguments:
ParsedGuidedSectionToolsHandle A parsed GUID section tools handle.
SectionGuid The GUID for the section.
Returns:
NULL - if no tool is found or there is another error
Non-NULL - The tool to use to access the section contents. (The caller
must free the memory associated with this string.)
--*/
{
GUID_SEC_TOOL_ENTRY *GuidTool;
GuidTool = (GUID_SEC_TOOL_ENTRY*)ParsedGuidedSectionToolsHandle;
if (GuidTool == NULL) {
return NULL;
}
for ( ; GuidTool != NULL; GuidTool = GuidTool->Next) {
if (CompareGuid (&(GuidTool->Guid), SectionGuid) == 0) {
return CloneString (GuidTool->Path);
}
}
return NULL;
}

View File

@@ -0,0 +1,133 @@
/** @file
Copyright (c) 2007 - 2008, 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:
ParseGuidedSectionTools.h
Abstract:
Header file for helper functions for parsing GuidedSectionTools.txt
**/
#ifndef _EFI_PARSE_GUIDED_SECTION_TOOLS_H
#define _EFI_PARSE_GUIDED_SECTION_TOOLS_H
#include <Common/UefiBaseTypes.h>
//
// Functions declarations
//
EFI_HANDLE
ParseGuidedSectionToolsFile (
IN CHAR8 *InputFile
)
;
/**
Routine Description:
This function parses the tools_def.txt file. It returns a
EFI_HANDLE object which can be used for the other library
functions and should be passed to FreeParsedToolsDefHandle
to free resources when the tools_def.txt information is no
longer needed.
Arguments:
InputFile Path name of file to read
Returns:
NULL if error parsing
A non-NULL EFI_HANDLE otherwise
**/
EFI_HANDLE
ParseGuidedSectionToolsMemoryFile (
IN EFI_HANDLE InputFile
)
;
/**
Routine Description:
This function parses the tools_def.txt file. It returns a
EFI_HANDLE object which can be used for the other library
functions and should be passed to FreeParsedToolsDefHandle
to free resources when the tools_def.txt information is no
longer needed.
Arguments:
InputFile Memory file image.
Returns:
NULL if error parsing
A non-NULL EFI_HANDLE otherwise
**/
CHAR8*
LookupGuidedSectionToolPath (
IN EFI_HANDLE ParsedGuidedSectionToolsHandle,
IN EFI_GUID *SectionGuid
)
;
/**
Routine Description:
This function looks up the appropriate tool to use for extracting
a GUID defined FV section.
Arguments:
ParsedGuidedSectionToolsHandle A parsed GUID section tools handle.
SectionGuid The GUID for the section.
Returns:
NULL - if no tool is found or there is another error
Non-NULL - The tool to use to access the section contents. (The caller
must free the memory associated with this string.)
**/
EFI_STATUS
FreeParsedGuidedSectionToolsHandle (
IN EFI_HANDLE ParsedGuidedSectionToolsHandle
)
;
/**
Routine Description:
Frees resources that were allocated by ParseGuidedSectionToolsFile.
After freeing these resources, the information that was parsed
is no longer accessible.
Arguments:
ParsedToolDefHandle Handle returned from ParseGuidedSectionToolsFile
Returns:
EFI_STATUS
**/
#endif

View File

@@ -0,0 +1,665 @@
/** @file
Copyright (c) 2004 - 2008, 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 <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include "EfiUtilityMsgs.h"
#include "ParseInf.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
//
if (InputBuffer[CharsToCopy - 1] == '\r') {
InputBuffer[CharsToCopy - 1] = '\0';
} else {
InputBuffer[CharsToCopy] = '\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;
UINT32 Data1;
UINT32 Data2;
UINT32 Data3;
UINT16 Data4[8];
if (AsciiGuidBuffer == NULL || GuidBuffer == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Check Guid Format strictly xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
//
for (Index = 0; AsciiGuidBuffer[Index] != '\0' && Index < 37; Index ++) {
if (Index == 8 || Index == 13 || Index == 18 || Index == 23) {
if (AsciiGuidBuffer[Index] != '-') {
break;
}
} else {
if (((AsciiGuidBuffer[Index] >= '0') && (AsciiGuidBuffer[Index] <= '9')) ||
((AsciiGuidBuffer[Index] >= 'a') && (AsciiGuidBuffer[Index] <= 'f')) ||
((AsciiGuidBuffer[Index] >= 'A') && (AsciiGuidBuffer[Index] <= 'F'))) {
continue;
} else {
break;
}
}
}
if (Index < 36 || AsciiGuidBuffer[36] != '\0') {
Error (NULL, 0, 1003, "Invalid option value", "Incorrect GUID \"%s\"\n Correct Format \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"", AsciiGuidBuffer);
return EFI_ABORTED;
}
//
// Scan the guid string into the buffer
//
Index = sscanf (
AsciiGuidBuffer,
"%08x-%04x-%04x-%02hx%02hx-%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) {
Error (NULL, 0, 1003, "Invalid option value", "Incorrect GUID \"%s\"\n Correct Format \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"", 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;
//
// Check input paramter
//
if (AsciiString == NULL || ReturnValue == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// 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,230 @@
/** @file
Copyright (c) 2004 - 2008, 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 <stdio.h>
#include <stdlib.h>
#include <Common/UefiBaseTypes.h>
#include <MemoryFile.h>
#ifndef _MAX_PATH
#define _MAX_PATH 500
#endif
//
// Functions declarations
//
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
--*/
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

View File

@@ -0,0 +1,137 @@
/** @file
Function prototypes and defines on Memory Only PE COFF loader
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: PeCoffLib.h
**/
#ifndef __BASE_PE_COFF_LIB_H__
#define __BASE_PE_COFF_LIB_H__
//
// Return status codes from the PE/COFF Loader services
// BUGBUG: Find where used and see if can be replaced by RETURN_STATUS codes
//
#define IMAGE_ERROR_SUCCESS 0
#define IMAGE_ERROR_IMAGE_READ 1
#define IMAGE_ERROR_INVALID_PE_HEADER_SIGNATURE 2
#define IMAGE_ERROR_INVALID_MACHINE_TYPE 3
#define IMAGE_ERROR_INVALID_SUBSYSTEM 4
#define IMAGE_ERROR_INVALID_IMAGE_ADDRESS 5
#define IMAGE_ERROR_INVALID_IMAGE_SIZE 6
#define IMAGE_ERROR_INVALID_SECTION_ALIGNMENT 7
#define IMAGE_ERROR_SECTION_NOT_LOADED 8
#define IMAGE_ERROR_FAILED_RELOCATION 9
#define IMAGE_ERROR_FAILED_ICACHE_FLUSH 10
//
// PE/COFF Loader Read Function passed in by caller
//
typedef
RETURN_STATUS
(EFIAPI *PE_COFF_LOADER_READ_FILE) (
IN VOID *FileHandle,
IN UINTN FileOffset,
IN OUT UINTN *ReadSize,
OUT VOID *Buffer
);
//
// Context structure used while PE/COFF image is being loaded and relocated
//
typedef struct {
PHYSICAL_ADDRESS ImageAddress;
UINT64 ImageSize;
PHYSICAL_ADDRESS DestinationAddress;
PHYSICAL_ADDRESS EntryPoint;
PE_COFF_LOADER_READ_FILE ImageRead;
VOID *Handle;
VOID *FixupData;
UINT32 SectionAlignment;
UINT32 PeCoffHeaderOffset;
UINT32 DebugDirectoryEntryRva;
VOID *CodeView;
CHAR8 *PdbPointer;
UINTN SizeOfHeaders;
UINT32 ImageCodeMemoryType;
UINT32 ImageDataMemoryType;
UINT32 ImageError;
UINTN FixupDataSize;
UINT16 Machine;
UINT16 ImageType;
BOOLEAN RelocationsStripped;
BOOLEAN IsTeImage;
} PE_COFF_LOADER_IMAGE_CONTEXT;
/**
Retrieves information on a PE/COFF image
@param ImageContext The context of the image being loaded
@retval EFI_SUCCESS The information on the PE/COFF image was collected.
@retval EFI_INVALID_PARAMETER ImageContext is NULL.
@retval EFI_UNSUPPORTED The PE/COFF image is not supported.
@retval Otherwise The error status from reading the PE/COFF image using the
ImageContext->ImageRead() function
**/
RETURN_STATUS
EFIAPI
PeCoffLoaderGetImageInfo (
IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
)
;
/**
Relocates a PE/COFF image in memory
@param ImageContext Contains information on the loaded image to relocate
@retval EFI_SUCCESS if the PE/COFF image was relocated
@retval EFI_LOAD_ERROR if the image is not a valid PE/COFF image
@retval EFI_UNSUPPORTED not support
**/
RETURN_STATUS
EFIAPI
PeCoffLoaderRelocateImage (
IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
)
;
/**
Loads a PE/COFF image into memory
@param ImageContext Contains information on image to load into memory
@retval EFI_SUCCESS if the PE/COFF image was loaded
@retval EFI_BUFFER_TOO_SMALL if the caller did not provide a large enough buffer
@retval EFI_LOAD_ERROR if the image is a runtime driver with no relocations
@retval EFI_INVALID_PARAMETER if the image address is invalid
**/
RETURN_STATUS
EFIAPI
PeCoffLoaderLoadImage (
IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
)
;
VOID *
EFIAPI
PeCoffLoaderGetPdbPointer (
IN VOID *Pe32Data
)
;
#endif

View File

@@ -0,0 +1,317 @@
/** @file
Copyright (c) 2004 - 2008, 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:
PeCoffLoaderEx.c
Abstract:
IA32, X64 and IPF Specific relocation fixups
Revision History
--*/
#include <Common/UefiBaseTypes.h>
#include <IndustryStandard/PeImage.h>
#include "PeCoffLib.h"
#define EXT_IMM64(Value, Address, Size, InstPos, ValPos) \
Value |= (((UINT64)((*(Address) >> InstPos) & (((UINT64)1 << Size) - 1))) << ValPos)
#define INS_IMM64(Value, Address, Size, InstPos, ValPos) \
*(UINT32*)Address = (*(UINT32*)Address & ~(((1 << Size) - 1) << InstPos)) | \
((UINT32)((((UINT64)Value >> ValPos) & (((UINT64)1 << Size) - 1))) << InstPos)
#define IMM64_IMM7B_INST_WORD_X 3
#define IMM64_IMM7B_SIZE_X 7
#define IMM64_IMM7B_INST_WORD_POS_X 4
#define IMM64_IMM7B_VAL_POS_X 0
#define IMM64_IMM9D_INST_WORD_X 3
#define IMM64_IMM9D_SIZE_X 9
#define IMM64_IMM9D_INST_WORD_POS_X 18
#define IMM64_IMM9D_VAL_POS_X 7
#define IMM64_IMM5C_INST_WORD_X 3
#define IMM64_IMM5C_SIZE_X 5
#define IMM64_IMM5C_INST_WORD_POS_X 13
#define IMM64_IMM5C_VAL_POS_X 16
#define IMM64_IC_INST_WORD_X 3
#define IMM64_IC_SIZE_X 1
#define IMM64_IC_INST_WORD_POS_X 12
#define IMM64_IC_VAL_POS_X 21
#define IMM64_IMM41a_INST_WORD_X 1
#define IMM64_IMM41a_SIZE_X 10
#define IMM64_IMM41a_INST_WORD_POS_X 14
#define IMM64_IMM41a_VAL_POS_X 22
#define IMM64_IMM41b_INST_WORD_X 1
#define IMM64_IMM41b_SIZE_X 8
#define IMM64_IMM41b_INST_WORD_POS_X 24
#define IMM64_IMM41b_VAL_POS_X 32
#define IMM64_IMM41c_INST_WORD_X 2
#define IMM64_IMM41c_SIZE_X 23
#define IMM64_IMM41c_INST_WORD_POS_X 0
#define IMM64_IMM41c_VAL_POS_X 40
#define IMM64_SIGN_INST_WORD_X 3
#define IMM64_SIGN_SIZE_X 1
#define IMM64_SIGN_INST_WORD_POS_X 27
#define IMM64_SIGN_VAL_POS_X 63
RETURN_STATUS
PeCoffLoaderRelocateIa32Image (
IN UINT16 *Reloc,
IN OUT CHAR8 *Fixup,
IN OUT CHAR8 **FixupData,
IN UINT64 Adjust
)
/*++
Routine Description:
Performs an IA-32 specific relocation fixup
Arguments:
Reloc - Pointer to the relocation record
Fixup - Pointer to the address to fix up
FixupData - Pointer to a buffer to log the fixups
Adjust - The offset to adjust the fixup
Returns:
EFI_UNSUPPORTED - Unsupported now
--*/
{
return RETURN_UNSUPPORTED;
}
RETURN_STATUS
PeCoffLoaderRelocateIpfImage (
IN UINT16 *Reloc,
IN OUT CHAR8 *Fixup,
IN OUT CHAR8 **FixupData,
IN UINT64 Adjust
)
/*++
Routine Description:
Performs an Itanium-based specific relocation fixup
Arguments:
Reloc - Pointer to the relocation record
Fixup - Pointer to the address to fix up
FixupData - Pointer to a buffer to log the fixups
Adjust - The offset to adjust the fixup
Returns:
Status code
--*/
{
UINT64 *F64;
UINT64 FixupVal;
switch ((*Reloc) >> 12) {
case EFI_IMAGE_REL_BASED_DIR64:
F64 = (UINT64 *) Fixup;
*F64 = *F64 + (UINT64) Adjust;
if (*FixupData != NULL) {
*FixupData = ALIGN_POINTER(*FixupData, sizeof(UINT64));
*(UINT64 *)(*FixupData) = *F64;
*FixupData = *FixupData + sizeof(UINT64);
}
break;
case EFI_IMAGE_REL_BASED_IA64_IMM64:
//
// Align it to bundle address before fixing up the
// 64-bit immediate value of the movl instruction.
//
Fixup = (CHAR8 *)((UINTN) Fixup & (UINTN) ~(15));
FixupVal = (UINT64)0;
//
// Extract the lower 32 bits of IMM64 from bundle
//
EXT_IMM64(FixupVal,
(UINT32 *)Fixup + IMM64_IMM7B_INST_WORD_X,
IMM64_IMM7B_SIZE_X,
IMM64_IMM7B_INST_WORD_POS_X,
IMM64_IMM7B_VAL_POS_X
);
EXT_IMM64(FixupVal,
(UINT32 *)Fixup + IMM64_IMM9D_INST_WORD_X,
IMM64_IMM9D_SIZE_X,
IMM64_IMM9D_INST_WORD_POS_X,
IMM64_IMM9D_VAL_POS_X
);
EXT_IMM64(FixupVal,
(UINT32 *)Fixup + IMM64_IMM5C_INST_WORD_X,
IMM64_IMM5C_SIZE_X,
IMM64_IMM5C_INST_WORD_POS_X,
IMM64_IMM5C_VAL_POS_X
);
EXT_IMM64(FixupVal,
(UINT32 *)Fixup + IMM64_IC_INST_WORD_X,
IMM64_IC_SIZE_X,
IMM64_IC_INST_WORD_POS_X,
IMM64_IC_VAL_POS_X
);
EXT_IMM64(FixupVal,
(UINT32 *)Fixup + IMM64_IMM41a_INST_WORD_X,
IMM64_IMM41a_SIZE_X,
IMM64_IMM41a_INST_WORD_POS_X,
IMM64_IMM41a_VAL_POS_X
);
//
// Update 64-bit address
//
FixupVal += Adjust;
//
// Insert IMM64 into bundle
//
INS_IMM64(FixupVal,
((UINT32 *)Fixup + IMM64_IMM7B_INST_WORD_X),
IMM64_IMM7B_SIZE_X,
IMM64_IMM7B_INST_WORD_POS_X,
IMM64_IMM7B_VAL_POS_X
);
INS_IMM64(FixupVal,
((UINT32 *)Fixup + IMM64_IMM9D_INST_WORD_X),
IMM64_IMM9D_SIZE_X,
IMM64_IMM9D_INST_WORD_POS_X,
IMM64_IMM9D_VAL_POS_X
);
INS_IMM64(FixupVal,
((UINT32 *)Fixup + IMM64_IMM5C_INST_WORD_X),
IMM64_IMM5C_SIZE_X,
IMM64_IMM5C_INST_WORD_POS_X,
IMM64_IMM5C_VAL_POS_X
);
INS_IMM64(FixupVal,
((UINT32 *)Fixup + IMM64_IC_INST_WORD_X),
IMM64_IC_SIZE_X,
IMM64_IC_INST_WORD_POS_X,
IMM64_IC_VAL_POS_X
);
INS_IMM64(FixupVal,
((UINT32 *)Fixup + IMM64_IMM41a_INST_WORD_X),
IMM64_IMM41a_SIZE_X,
IMM64_IMM41a_INST_WORD_POS_X,
IMM64_IMM41a_VAL_POS_X
);
INS_IMM64(FixupVal,
((UINT32 *)Fixup + IMM64_IMM41b_INST_WORD_X),
IMM64_IMM41b_SIZE_X,
IMM64_IMM41b_INST_WORD_POS_X,
IMM64_IMM41b_VAL_POS_X
);
INS_IMM64(FixupVal,
((UINT32 *)Fixup + IMM64_IMM41c_INST_WORD_X),
IMM64_IMM41c_SIZE_X,
IMM64_IMM41c_INST_WORD_POS_X,
IMM64_IMM41c_VAL_POS_X
);
INS_IMM64(FixupVal,
((UINT32 *)Fixup + IMM64_SIGN_INST_WORD_X),
IMM64_SIGN_SIZE_X,
IMM64_SIGN_INST_WORD_POS_X,
IMM64_SIGN_VAL_POS_X
);
F64 = (UINT64 *) Fixup;
if (*FixupData != NULL) {
*FixupData = ALIGN_POINTER(*FixupData, sizeof(UINT64));
*(UINT64 *)(*FixupData) = *F64;
*FixupData = *FixupData + sizeof(UINT64);
}
break;
default:
return RETURN_UNSUPPORTED;
}
return RETURN_SUCCESS;
}
RETURN_STATUS
PeCoffLoaderRelocateX64Image (
IN UINT16 *Reloc,
IN OUT CHAR8 *Fixup,
IN OUT CHAR8 **FixupData,
IN UINT64 Adjust
)
/**
Performs an x64 specific relocation fixup
@param Reloc Pointer to the relocation record
@param Fixup Pointer to the address to fix up
@param FixupData Pointer to a buffer to log the fixups
@param Adjust The offset to adjust the fixup
@retval RETURN_SUCCESS Success to perform relocation
@retval RETURN_UNSUPPORTED Unsupported.
**/
{
UINT64 *F64;
switch ((*Reloc) >> 12) {
case EFI_IMAGE_REL_BASED_DIR64:
F64 = (UINT64 *) Fixup;
*F64 = *F64 + (UINT64) Adjust;
if (*FixupData != NULL) {
*FixupData = ALIGN_POINTER(*FixupData, sizeof(UINT64));
*(UINT64 *)(*FixupData) = *F64;
*FixupData = *FixupData + sizeof(UINT64);
}
break;
default:
return RETURN_UNSUPPORTED;
}
return RETURN_SUCCESS;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,117 @@
/** @file
Copyright (c) 2004 - 2008, 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_
#include <Common/UefiBaseTypes.h>
STATUS
SFPInit (
VOID
)
;
STATUS
SFPOpenFile (
CHAR8 *FileName
)
;
BOOLEAN
SFPIsKeyword (
CHAR8 *Str
)
;
BOOLEAN
SFPIsToken (
CHAR8 *Str
)
;
BOOLEAN
SFPGetNextToken (
CHAR8 *Str,
UINTN Len
)
;
BOOLEAN
SFPGetGuidToken (
CHAR8 *Str,
UINT32 Len
)
;
#define PARSE_GUID_STYLE_5_FIELDS 0
BOOLEAN
SFPGetGuid (
INTN GuidStyle,
EFI_GUID *Value
)
;
BOOLEAN
SFPSkipToToken (
CHAR8 *Str
)
;
BOOLEAN
SFPGetNumber (
UINTN *Value
)
;
BOOLEAN
SFPGetQuotedString (
CHAR8 *Str,
INTN Length
)
;
BOOLEAN
SFPIsEOF (
VOID
)
;
STATUS
SFPCloseFile (
VOID
)
;
UINTN
SFPGetLineNumber (
VOID
)
;
CHAR8 *
SFPGetFileName (
VOID
)
;
#endif // #ifndef _SIMPLE_FILE_PARSING_H_

View File

@@ -0,0 +1,426 @@
/** @file
Copyright (c) 2007 - 2008, 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:
StringFuncs.c
Abstract:
Function prototypes and defines for string routines.
**/
#include <string.h>
#include <ctype.h>
#include "StringFuncs.h"
//
// Functions implementations
//
CHAR8*
CloneString (
IN CHAR8 *String
)
/*++
Routine Description:
Allocates a new string and copies 'String' to clone it
Arguments:
String The string to clone
Returns:
CHAR8* - NULL if there are not enough resources
--*/
{
CHAR8* NewString;
NewString = malloc (strlen (String) + 1);
if (NewString != NULL) {
strcpy (NewString, String);
}
return NewString;
}
EFI_STATUS
StripInfDscStringInPlace (
IN CHAR8 *String
)
/*++
Routine Description:
Remove all comments, leading and trailing whitespace from the string.
Arguments:
String The string to 'strip'
Returns:
EFI_STATUS
--*/
{
CHAR8 *Pos;
if (String == NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Remove leading whitespace
//
for (Pos = String; isspace (*Pos); Pos++) {
}
if (Pos != String) {
memmove (String, Pos, strlen (Pos) + 1);
}
//
// Comment BUGBUGs!
//
// What about strings? Comment characters are okay in strings.
// What about multiline comments?
//
Pos = (CHAR8 *) strstr (String, "//");
if (Pos != NULL) {
*Pos = '\0';
}
Pos = (CHAR8 *) strchr (String, '#');
if (Pos != NULL) {
*Pos = '\0';
}
//
// Remove trailing whitespace
//
for (Pos = String + strlen (String);
((Pos - 1) >= String) && (isspace (*(Pos - 1)));
Pos--
) {
}
*Pos = '\0';
return EFI_SUCCESS;
}
STRING_LIST*
SplitStringByWhitespace (
IN CHAR8 *String
)
/*++
Routine Description:
Creates and returns a 'split' STRING_LIST by splitting the string
on whitespace boundaries.
Arguments:
String The string to 'split'
Returns:
EFI_STATUS
--*/
{
CHAR8 *Pos;
CHAR8 *EndOfSubString;
CHAR8 *EndOfString;
STRING_LIST *Output;
UINTN Item;
String = CloneString (String);
if (String == NULL) {
return NULL;
}
EndOfString = String + strlen (String);
Output = NewStringList ();
for (Pos = String, Item = 0; Pos < EndOfString; Item++) {
while (isspace (*Pos)) {
Pos++;
}
for (EndOfSubString=Pos;
(*EndOfSubString != '\0') && !isspace (*EndOfSubString);
EndOfSubString++
) {
}
if (EndOfSubString == Pos) {
break;
}
*EndOfSubString = '\0';
AppendCopyOfStringToList (&Output, Pos);
Pos = EndOfSubString + 1;
}
free (String);
return Output;
}
STRING_LIST*
NewStringList (
)
/*++
Routine Description:
Creates a new STRING_LIST with 0 strings.
Returns:
STRING_LIST* - Null if there is not enough resources to create the object.
--*/
{
STRING_LIST *NewList;
NewList = AllocateStringListStruct (0);
if (NewList != NULL) {
NewList->Count = 0;
}
return NewList;
}
EFI_STATUS
AppendCopyOfStringToList (
IN OUT STRING_LIST **StringList,
IN CHAR8 *String
)
/*++
Routine Description:
Adds String to StringList. A new copy of String is made before it is
added to StringList.
Returns:
EFI_STATUS
--*/
{
STRING_LIST *OldList;
STRING_LIST *NewList;
CHAR8 *NewString;
OldList = *StringList;
NewList = AllocateStringListStruct (OldList->Count + 1);
if (NewList == NULL) {
return EFI_OUT_OF_RESOURCES;
}
NewString = CloneString (String);
if (NewString == NULL) {
free (NewList);
return EFI_OUT_OF_RESOURCES;
}
memcpy (
NewList->Strings,
OldList->Strings,
sizeof (OldList->Strings[0]) * OldList->Count
);
NewList->Count = OldList->Count + 1;
NewList->Strings[OldList->Count] = NewString;
*StringList = NewList;
free (OldList);
return EFI_SUCCESS;
}
EFI_STATUS
RemoveLastStringFromList (
IN STRING_LIST *StringList
)
/*++
Routine Description:
Removes the last string from StringList and frees the memory associated
with it.
Arguments:
StringList The string list to remove the string from
Returns:
EFI_STATUS
--*/
{
if (StringList->Count == 0) {
return EFI_INVALID_PARAMETER;
}
free (StringList->Strings[StringList->Count - 1]);
StringList->Count--;
return EFI_SUCCESS;
}
STRING_LIST*
AllocateStringListStruct (
IN UINTN StringCount
)
/*++
Routine Description:
Allocates a STRING_LIST structure that can store StringCount strings.
Arguments:
StringCount The number of strings that need to be stored
Returns:
EFI_STATUS
--*/
{
return malloc (OFFSET_OF(STRING_LIST, Strings[StringCount + 1]));
}
VOID
FreeStringList (
IN STRING_LIST *StringList
)
/*++
Routine Description:
Frees all memory associated with StringList.
Arguments:
StringList The string list to free
Returns:
VOID
--*/
{
while (StringList->Count > 0) {
RemoveLastStringFromList (StringList);
}
free (StringList);
}
CHAR8*
StringListToString (
IN STRING_LIST *StringList
)
/*++
Routine Description:
Generates a string that represents the STRING_LIST
Arguments:
StringList The string list to convert to a string
Returns:
CHAR8* - The string list represented with a single string. The returned
string must be freed by the caller.
--*/
{
UINTN Count;
UINTN Length;
CHAR8 *NewString;
Length = 2;
for (Count = 0; Count < StringList->Count; Count++) {
if (Count > 0) {
Length += 2;
}
Length += strlen (StringList->Strings[Count]) + 2;
}
NewString = malloc (Length + 1);
if (NewString == NULL) {
return NewString;
}
NewString[0] = '\0';
strcat (NewString, "[");
for (Count = 0; Count < StringList->Count; Count++) {
if (Count > 0) {
strcat (NewString, ", ");
}
strcat (NewString, "\"");
strcat (NewString, StringList->Strings[Count]);
strcat (NewString, "\"");
}
strcat (NewString, "]");
return NewString;
}
VOID
PrintStringList (
IN STRING_LIST *StringList
)
/*++
Routine Description:
Prints out the string list
Arguments:
StringList The string list to print
Returns:
EFI_STATUS
--*/
{
CHAR8* String;
String = StringListToString (StringList);
if (String != NULL) {
printf ("%s", String);
free (String);
}
}

View File

@@ -0,0 +1,257 @@
/**
Copyright (c) 2007 - 2008, 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:
StringFuncs.h
Abstract:
String routines implementation.
**/
#ifndef _EFI_STRING_FUNCS_H
#define _EFI_STRING_FUNCS_H
#include <stdio.h>
#include <stdlib.h>
#include <Common/UefiBaseTypes.h>
//
// Common data structures
//
typedef struct {
UINTN Count;
//
// Actually this array can be 0 or more items (based on Count)
//
CHAR8* Strings[1];
} STRING_LIST;
//
// Functions declarations
//
CHAR8*
CloneString (
IN CHAR8 *String
)
;
/**
Routine Description:
Allocates a new string and copies 'String' to clone it
Arguments:
String The string to clone
Returns:
CHAR8* - NULL if there are not enough resources
**/
EFI_STATUS
StripInfDscStringInPlace (
IN CHAR8 *String
)
;
/**
Routine Description:
Remove all comments, leading and trailing whitespace from the string.
Arguments:
Strin The string to 'strip'
Returns:
EFI_STATUS
**/
STRING_LIST*
SplitStringByWhitespace (
IN CHAR8 *String
)
;
/**
Routine Description:
Creates and returns a 'split' STRING_LIST by splitting the string
on whitespace boundaries.
Arguments:
String The string to 'split'
Returns:
EFI_STATUS
**/
STRING_LIST*
NewStringList (
)
;
/**
Routine Description:
Creates a new STRING_LIST with 0 strings.
Returns:
STRING_LIST* - Null if there is not enough resources to create the object.
**/
EFI_STATUS
AppendCopyOfStringToList (
IN OUT STRING_LIST **StringList,
IN CHAR8 *String
)
;
/**
Routine Description:
Adds String to StringList. A new copy of String is made before it is
added to StringList.
Returns:
EFI_STATUS
**/
EFI_STATUS
RemoveLastStringFromList (
IN STRING_LIST *StringList
)
;
/**
Routine Description:
Removes the last string from StringList and frees the memory associated
with it.
Arguments:
StringList The string list to remove the string from
Returns:
EFI_STATUS
**/
STRING_LIST*
AllocateStringListStruct (
IN UINTN StringCount
)
;
/**
Routine Description:
Allocates a STRING_LIST structure that can store StringCount strings.
Arguments:
StringCount The number of strings that need to be stored
Returns:
EFI_STATUS
**/
VOID
FreeStringList (
IN STRING_LIST *StringList
)
;
/**
Routine Description:
Frees all memory associated with StringList.
Arguments:
StringList The string list to free
Returns:
EFI_STATUS
**/
CHAR8*
StringListToString (
IN STRING_LIST *StringList
)
;
/**
Routine Description:
Generates a string that represents the STRING_LIST
Arguments:
StringList The string list to convert to a string
Returns:
CHAR8* - The string list represented with a single string. The returned
string must be freed by the caller.
**/
VOID
PrintStringList (
IN STRING_LIST *StringList
)
;
/**
Routine Description:
Prints out the string list
Arguments:
StringList The string list to print
**/
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,73 @@
/** @file
Copyright (c) 2006 - 2008, 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:
WinNtInclude.h
Abstract:
Include file for the WinNt Library
**/
#ifndef __WIN_NT_INCLUDE_H__
#define __WIN_NT_INCLUDE_H__
#define GUID _WINNT_DUP_GUID_____
#define _LIST_ENTRY _WINNT_DUP_LIST_ENTRY_FORWARD
#define LIST_ENTRY _WINNT_DUP_LIST_ENTRY
#define InterlockedIncrement _WINNT_DUP_InterlockedIncrement
#define InterlockedDecrement _WINNT_DUP_InterlockedDecrement
#define InterlockedCompareExchange64 _WINNT_DUP_InterlockedCompareExchange64
#undef UNALIGNED
#undef CONST
#undef VOID
#ifndef __GNUC__
#include "windows.h"
//
// Win32 include files do not compile clean with /W4, so we use the warning
// pragma to suppress the warnings for Win32 only. This way our code can stil
// compile at /W4 (highest warning level) with /WX (warnings cause build
// errors).
//
#pragma warning(disable : 4115)
#pragma warning(disable : 4201)
#pragma warning(disable : 4214)
#pragma warning(disable : 4028)
#pragma warning(disable : 4133)
//
// Set the warnings back on as the EFI code must be /W4.
//
#pragma warning(default : 4115)
#pragma warning(default : 4201)
#pragma warning(default : 4214)
#endif
#undef GUID
#undef _LIST_ENTRY
#undef LIST_ENTRY
#undef InterlockedIncrement
#undef InterlockedDecrement
#undef InterlockedCompareExchange64
#undef InterlockedCompareExchangePointer
#define VOID void
//
// Prevent collisions with Windows API name macros that deal with Unicode/Not issues
//
#undef LoadImage
#undef CreateEvent
#endif

View File

@@ -0,0 +1,329 @@
/** @file
Copyright 2006 - 2008, 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ParseInf.h"
#include "CommonLib.h"
#include "EfiUtilityMsgs.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;
//
// Utility Name
//
#define UTILITY_NAME "EfiLdrImage"
//
// Utility version information
//
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
void
Version (
void
)
/*++
Routine Description:
Displays the standard utility information to SDTOUT
Arguments:
None
Returns:
None
--*/
{
printf ("%s v%d.%d -Utility to break a file into two pieces at the request offset.\n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION);
printf ("Copyright (c) 1999-2007 Intel Corporation. All rights reserved.\n");
}
VOID
Usage (
VOID
)
{
printf ("Usage: EfiLdrImage -o OutImage LoaderImage PeImage1 PeImage2 ... PeImageN\n");
exit (1);
}
EFI_STATUS
CountVerboseLevel (
IN CONST CHAR8* VerboseLevelString,
IN CONST UINT64 Length,
OUT UINT64 *ReturnValue
)
{
UINT64 i = 0;
for (;i < Length; ++i) {
if (VerboseLevelString[i] != 'v' && VerboseLevelString[i] != 'V') {
return EFI_ABORTED;
}
++(*ReturnValue);
}
return EFI_SUCCESS;
}
UINT64
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:
UINT64 : file size of input file
--*/
{
UINT64 filesize, offset, length;
CHAR8 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:
--*/
{
UINT64 i;
UINT64 filesize;
FILE *fpIn, *fpOut;
EFILDR_HEADER EfiLdrHeader;
EFILDR_IMAGE EfiLdrImage[MAX_PE_IMAGES];
CHAR8* OutputFileName = NULL;
CHAR8* InputFileNames[MAX_PE_IMAGES + 1];
UINT8 InputFileCount = 0;
BOOLEAN QuietFlag = FALSE;
UINT64 DebugLevel = 0;
UINT64 VerboseLevel = 0;
EFI_STATUS Status = EFI_SUCCESS;
SetUtilityName (UTILITY_NAME);
if (argc == 1) {
Usage();
return STATUS_ERROR;
}
argc --;
argv ++;
if ((stricmp (argv[0], "-h") == 0) || (stricmp (argv[0], "--help") == 0)) {
Usage();
return STATUS_SUCCESS;
}
if (stricmp (argv[0], "--version") == 0) {
Version();
return STATUS_SUCCESS;
}
while (argc > 0) {
if ((stricmp (argv[0], "-o") == 0) || (stricmp (argv[0], "--output") == 0)) {
OutputFileName = argv[1];
if (OutputFileName == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Output file can't be null");
return STATUS_ERROR;
}
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-q") == 0) || (stricmp (argv[0], "--quiet") == 0)) {
QuietFlag = TRUE;
argc --;
argv ++;
continue;
}
if ((strlen(argv[0]) >= 2 && argv[0][0] == '-' && (argv[0][1] == 'v' || argv[0][1] == 'V')) || (stricmp (argv[0], "--verbose") == 0)) {
VerboseLevel = 1;
if (strlen(argv[0]) > 2) {
Status = CountVerboseLevel (&argv[0][2], strlen(argv[0]) - 2, &VerboseLevel);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", argv[0]);
return STATUS_ERROR;
}
}
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-d") == 0) || (stricmp (argv[0], "--debug") == 0)) {
Status = AsciiStringToUint64 (argv[1], FALSE, &DebugLevel);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
return STATUS_ERROR;
}
argc -= 2;
argv += 2;
continue;
}
//
// Don't recognize the paramter, should be regarded as the input file name.
//
InputFileNames[InputFileCount] = argv[0];
InputFileCount++;
argc--;
argv++;
}
if (InputFileCount == 0) {
Error (NULL, 0, 1001, "Missing option", "No input file");
return STATUS_ERROR;
}
//
// Open output file for write
//
if (OutputFileName == NULL) {
Error (NULL, 0, 1001, "Missing option", "No output file");
return STATUS_ERROR;
}
fpOut = fopen(OutputFileName, "w+b");
if (!fpOut) {
Error (NULL, 0, 0001, "Could not open output file", OutputFileName);
return STATUS_ERROR;
}
memset (&EfiLdrHeader, 0, sizeof (EfiLdrHeader));
memset (&EfiLdrImage, 0, sizeof (EFILDR_IMAGE) * (InputFileCount));
memcpy (&EfiLdrHeader.Signature, "EFIL", 4);
EfiLdrHeader.FileLength = sizeof(EFILDR_HEADER) + sizeof(EFILDR_IMAGE)*(InputFileCount);
//
// Skip the file header first
//
fseek (fpOut, EfiLdrHeader.FileLength, SEEK_SET);
//
// copy all the input files to the output file
//
for(i=0;i<InputFileCount;i++) {
//
// Copy the content of PeImage file to output file
//
fpIn = fopen (InputFileNames[i], "rb");
if (!fpIn) {
Error (NULL, 0, 0001, "Could not open input file", InputFileNames[i]);
fclose (fpOut);
return STATUS_ERROR;
}
filesize = FCopyFile (fpIn, fpOut);
fclose(fpIn);
//
// And in the same time update the EfiLdrHeader and EfiLdrImage array
//
EfiLdrImage[i].Offset = EfiLdrHeader.FileLength;
EfiLdrImage[i].Length = filesize;
strncpy ((CHAR8*) EfiLdrImage[i].FileName, InputFileNames[i], sizeof (EfiLdrImage[i].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)*(InputFileCount), 1, fpOut);
fclose (fpOut);
printf ("Created %s\n", OutputFileName);
return 0;
}

View File

@@ -0,0 +1,10 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = EfiLdrImage
LIBS = -lCommon
OBJECTS = EfiLdrImage.o
include $(MAKEROOT)/Makefiles/app.makefile

View File

@@ -0,0 +1,10 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = EfiLdrImage
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = EfiLdrImage.obj
!INCLUDE ..\Makefiles\ms.app

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,366 @@
/** @file
Copyright (c) 1999 - 2008 Intel Corporation. All rights reserved
This software and associated documentation (if any) is furnished
under a license and may only be used or copied in accordance
with the terms of the license. Except as permitted by such
license, no part of this software or documentation may be
reproduced, stored in a retrieval system, or transmitted in any
form or by any means without the express written consent of
Intel Corporation.
Module Name:
EfiRom.h
Abstract:
This file contains the relevant declarations required
to generate Option Rom File
**/
#ifndef __EFI_ROM_H__
#define __EFI_ROM_H__
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <Common/UefiBaseTypes.h>
#include <IndustryStandard/PeImage.h> // for PE32 structure definitions
#include <IndustryStandard/pci22.h> // for option ROM header structures
#include <IndustryStandard/pci30.h>
#include "Compress.h"
#include "CommonLib.h"
//
// Version of this utility
//
#define UTILITY_NAME "EfiRom"
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
//
// Define the max length of a filename
//
#define MAX_PATH 200
//
// Define the default file extension name
//
#define DEFAULT_OUTPUT_EXTENSION ".rom"
//
// Max size for an option ROM image
//
#define MAX_OPTION_ROM_SIZE (1024 * 1024 * 16) // 16MB
//
// Values for the indicator field in the PCI data structure
//
#define INDICATOR_LAST 0x80 // last file in series of files
//
// Masks for the FILE_LIST.FileFlags field
//
#define FILE_FLAG_BINARY 0x01
#define FILE_FLAG_EFI 0x02
#define FILE_FLAG_COMPRESS 0x04
//
// Use this linked list structure to keep track of all the filenames
// specified on the command line.
//
typedef struct _FILE_LIST {
struct _FILE_LIST *Next;
CHAR8 *FileName;
UINT32 FileFlags;
UINT32 ClassCode;
UINT16 CodeRevision;
} FILE_LIST;
//
// Use this to track our command-line options
//
typedef struct {
CHAR8 OutFileName[MAX_PATH];
INT8 NoLast;
UINT16 ClassCode;
UINT16 PciRevision;
UINT16 VendId;
UINT16 DevId;
UINT8 VendIdValid;
UINT8 DevIdValid;
INT8 Verbose;
INT8 Quiet;
INT8 Debug;
INT8 Pci23;
INT8 Pci30;
INT8 DumpOption;
// INT8 Help;
// INT8 Version;
FILE_LIST *FileList;
} OPTIONS;
//
// Make a global structure to keep track of command-line options
//
static OPTIONS mOptions;
//
// Use these to convert from machine type value to a named type
//
typedef struct {
UINT16 Value;
CHAR8 *Name;
} STRING_LOOKUP;
//
// Machine Types
//
static STRING_LOOKUP mMachineTypes[] = {
{ EFI_IMAGE_MACHINE_IA32, "IA32" },
{ EFI_IMAGE_MACHINE_IA64, "IA64" },
{ EFI_IMAGE_MACHINE_EBC, "EBC" },
{ 0, NULL }
};
//
// Subsystem Types
//
static STRING_LOOKUP mSubsystemTypes[] = {
{ EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION, "EFI application" },
{ EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, "EFI boot service driver" },
{ EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER, "EFI runtime driver" },
{ 0, NULL }
};
//
// Function prototypes
//
static
void
Version (
VOID
)
/*++
Routine Description:
Displays the utility version to STDOUT
Arguments:
None
Returns:
None
--*/
;
static
void
Usage (
VOID
)
/*++
Routine Description:
Displays the utility usage syntax to STDOUT
Arguments:
None
Returns:
None
--*/
;
static
int
ParseCommandLine (
int Argc,
char *Argv[],
OPTIONS *Options
)
/*++
Routine Description:
Given the Argc/Argv program arguments, and a pointer to an options structure,
parse the command-line options and check their validity.
Arguments:
Argc - standard C main() argument count
Argv[] - standard C main() argument list
Options - pointer to a structure to store the options in
Returns:
STATUS_SUCCESS success
non-zero otherwise
--*/
;
static
int
CheckPE32File (
FILE *Fptr,
UINT16 *MachineType,
UINT16 *SubSystem
)
/*++
Routine Description:
Given the Argc/Argv program arguments, and a pointer to an options structure,
parse the command-line options and check their validity.
Arguments:
Argc - standard C main() argument count
Argv[] - standard C main() argument list
Options - pointer to a structure to store the options in
Returns:
STATUS_SUCCESS success
non-zero otherwise
--*/
;
static
int
ProcessEfiFile (
FILE *OutFptr,
FILE_LIST *InFile,
UINT16 VendId,
UINT16 DevId,
UINT32 *Size
)
/*++
Routine Description:
Process a PE32 EFI file.
Arguments:
OutFptr - file pointer to output binary ROM image file we're creating
InFile - structure contains information on the PE32 file to process
VendId - vendor ID as required in the option ROM header
DevId - device ID as required in the option ROM header
Size - pointer to where to return the size added to the output file
Returns:
0 - successful
--*/
;
static
int
ProcessBinFile (
FILE *OutFptr,
FILE_LIST *InFile,
UINT32 *Size
)
/*++
Routine Description:
Process a binary input file.
Arguments:
OutFptr - file pointer to output binary ROM image file we're creating
InFile - structure contains information on the binary file to process
Size - pointer to where to return the size added to the output file
Returns:
0 - successful
--*/
;
static
void
DumpImage (
FILE_LIST *InFile
)
/*++
Routine Description:
Dump the headers of an existing option ROM image
Arguments:
InFile - the file name of an existing option ROM image
Returns:
none
--*/
;
char *
GetMachineTypeStr (
UINT16 MachineType
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
MachineType - GC_TODO: add argument description
Returns:
GC_TODO: add return values
--*/
;
static
char *
GetSubsystemTypeStr (
UINT16 SubsystemType
)
/*++
Routine Description:
GC_TODO: Add function description
Arguments:
SubsystemType - GC_TODO: add argument description
Returns:
GC_TODO: add return values
--*/
;
#endif

View File

@@ -0,0 +1,10 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = EfiRom
LIBS = -lCommon
OBJECTS = EfiRom.o
include $(MAKEROOT)/Makefiles/app.makefile

View File

@@ -0,0 +1,10 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = EfiRom
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = EfiRom.obj
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,90 @@
## @file
# GNU Make makefile for BaseTools/Source/C.
#
# Copyright (c) 2007 - 2009, 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.
#
ifndef ARCH
#
# If ARCH is not defined, then we use 'uname -m' to attempt
# try to figure out the appropriate ARCH.
#
uname_m = $(shell uname -m)
$(info Attempting to detect ARCH from 'uname -m': $(uname_m))
ifeq ($(uname_m),x86_64)
ARCH=X64
endif
ifeq ($(uname_m),i386)
ARCH=IA32
endif
ifeq ($(uname_m),i686)
ARCH=IA32
endif
ifndef ARCH
$(info Could not detected ARCH from uname results)
$(error ARCH is not defined!)
endif
$(info Detected ARCH of $(ARCH) using uname.)
endif
export ARCH
MAKEROOT = .
include Makefiles/header.makefile
all: makerootdir subdirs $(MAKEROOT)/libs
@echo Finished building BaseTools C Tools with ARCH=$(ARCH)
LIBRARIES = Common
# NON_BUILDABLE_APPLICATIONS = GenBootSector BootSectImage
APPLICATIONS = \
GnuGenBootSector \
BootSectImage \
EfiLdrImage \
EfiRom \
GenFfs \
GenFv \
GenFw \
GenPage \
GenSec \
GenCrc32 \
GenVtf \
LzmaCompress \
Split \
TianoCompress \
VolInfo \
VfrCompile
SUBDIRS := $(LIBRARIES) $(APPLICATIONS)
.PHONY: outputdirs
makerootdir:
-mkdir $(MAKEROOT)
.PHONY: subdirs $(SUBDIRS)
subdirs: $(SUBDIRS)
$(SUBDIRS):
$(MAKE) -C $@
.PHONY: $(patsubst %,%-clean,$(sort $(SUBDIRS)))
$(patsubst %,%-clean,$(sort $(SUBDIRS))):
-$(MAKE) -C $(@:-clean=) clean
clean: $(patsubst %,%-clean,$(sort $(SUBDIRS)))
clean: localClean
localClean:
rm -f $(MAKEROOT)/bin/*
-rmdir $(MAKEROOT)/libs $(MAKEROOT)/bin
include Makefiles/footer.makefile

View File

@@ -0,0 +1,152 @@
/** @file
Fat file system structure and definition.
Copyright 2006 - 2008, 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.
--*/
#ifndef _FAT_BPB_H_
#define _FAT_BPB_H_
#include "CommonLib.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,795 @@
/** @file
Copyright 2006 - 2008, 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>
#include <Common/UefiBaseTypes.h>
//
// Utility Name
//
#define UTILITY_NAME "GenBootSector"
//
// Utility version information
//
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
#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,
PatchTypeFileImage // input and output are all file image, patching action is same as PatchTypeFloppy
} PATCH_TYPE;
typedef enum {
PathUnknown,
PathFile,
PathFloppy,
PathUsb,
PathIde
} PATH_TYPE;
typedef enum {
ErrorSuccess,
ErrorFileCreate,
ErrorFileReadWrite,
ErrorNoMbr,
ErrorFatType,
ErrorPath,
} ERROR_STATUS;
CHAR *ErrorStatusDesc[] = {
"Success",
"Failed to create files",
"Failed to read/write files",
"No MBR exists",
"Failed to detect Fat type",
"Inavlid path"
};
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;
typedef struct _PATH_INFO {
CHAR *Path;
CHAR PhysicalPath[260];
PATH_TYPE Type;
BOOL Input;
} PATH_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 E0005: 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 E3005: Fatal 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,
PATH_INFO *PathInfo
)
/*++
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
PathInfo : PATH_INFO structure.
WriteToDisk : TRUE indicates writing
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 (!PathInfo->Input && (PathInfo->Type == PathUsb)) {
SetFilePointer(DiskHandle, 0, NULL, FILE_BEGIN);
DiskPartition[PARTITION_TABLE_OFFSET] = 0x80;
WriteFile (DiskHandle, DiskPartition, 0x200, &BytesReturn, NULL);
}
}
}
return DbrOffset;
}
/**
* Get window file handle for input/ouput disk/file.
*
* @param PathInfo
* @param ProcessMbr
* @param FileHandle
*
* @return ERROR_STATUS
*/
ERROR_STATUS
GetFileHandle (
PATH_INFO *PathInfo,
BOOL ProcessMbr,
HANDLE *FileHandle,
DWORD *DbrOffset
)
{
DWORD OpenFlag;
OpenFlag = OPEN_ALWAYS;
if (PathInfo->Input || PathInfo->Type != PathFile) {
OpenFlag = OPEN_EXISTING;
}
*FileHandle = CreateFile(
PathInfo->PhysicalPath,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
OpenFlag,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (*FileHandle == INVALID_HANDLE_VALUE) {
return ErrorFileCreate;
}
if ((PathInfo->Type == PathIde) || (PathInfo->Type == PathUsb)){
*DbrOffset = GetBootSectorOffset (*FileHandle, PathInfo);
if (!ProcessMbr) {
//
// 1. Process boot sector, set file pointer to the beginning of boot sector
//
SetFilePointer (*FileHandle, *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 (*FileHandle, 0, NULL, FILE_BEGIN);
}
}
return ErrorSuccess;
}
/**
Writing or reading boot sector or MBR according to the argument.
@param InputInfo PATH_INFO instance for input path
@param OutputInfo PATH_INFO instance for output path
@param ProcessMbr TRUE is to process MBR, otherwise, processing boot sector
@return ERROR_STATUS
**/
ERROR_STATUS
ProcessBsOrMbr (
PATH_INFO *InputInfo,
PATH_INFO *OutputInfo,
BOOL ProcessMbr
)
{
BYTE DiskPartition[0x200] = {0};
BYTE DiskPartitionBackup[0x200] = {0};
DWORD BytesReturn;
DWORD DbrOffset;
INT DrvNumOffset;
HANDLE InputHandle;
HANDLE OutputHandle;
BOOL WriteToDisk;
ERROR_STATUS Status;
DWORD InputDbrOffset;
DWORD OutputDbrOffset;
//
// Create file Handle and move file Pointer is pointed to beginning of Mbr or Dbr
//
Status = GetFileHandle(InputInfo, ProcessMbr, &InputHandle, &InputDbrOffset);
if (Status != ErrorSuccess) {
return Status;
}
//
// Create file Handle and move file Pointer is pointed to beginning of Mbr or Dbr
//
Status = GetFileHandle(OutputInfo, ProcessMbr, &OutputHandle, &OutputDbrOffset);
if (Status != ErrorSuccess) {
return Status;
}
//
// Read boot sector from source disk/file
//
if (!ReadFile (InputHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
return ErrorFileReadWrite;
}
if (InputInfo->Type == PathUsb) {
// 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] = ((InputDbrOffset > 0) ? 0x80 : 0);
}
if (InputInfo->Type == PathIde) {
//
// Patch LBAOffsetForBootSector
//
*(DWORD *)&DiskPartition [BOOT_SECTOR_LBA_OFFSET] = InputDbrOffset;
}
if (OutputInfo->Type != PathFile) {
if (ProcessMbr) {
//
// Use original partition table
//
if (!ReadFile (OutputHandle, DiskPartitionBackup, 0x200, &BytesReturn, NULL)) {
return ErrorFileReadWrite;
}
memcpy (DiskPartition + 0x1BE, DiskPartitionBackup + 0x1BE, 0x40);
SetFilePointer (OutputHandle, 0, NULL, FILE_BEGIN);
}
}
//
// Write boot sector to taget disk/file
//
if (!WriteFile (OutputHandle, DiskPartition, 0x200, &BytesReturn, NULL)) {
return ErrorFileReadWrite;
}
CloseHandle (InputHandle);
CloseHandle (OutputHandle);
return ErrorSuccess;
}
void
Version (
void
)
/*++
Routine Description:
Displays the standard utility information to SDTOUT
Arguments:
None
Returns:
None
--*/
{
printf ("%s v%d.%d -Utility to retrieve and update the boot sector or MBR.\n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION);
printf ("Copyright (c) 2009 Intel Corporation. All rights reserved.\n");
}
VOID
PrintUsage (
void
)
{
Version();
printf ("\nUsage: \n\
GenBootSector\n\
[-l, --list list disks]\n\
[-i, --input Filename]\n\
[-o, --output Filename]\n\
[-m, --mbr process the MBR also]\n\
[-v, --verbose]\n\
[--version]\n\
[-q, --quiet disable all messages except fatal errors]\n\
[-d, --debug[#]\n\
[-h, --help]\n");
}
/**
Get path information, including physical path for windows platform.
@param PathInfo Point to PATH_INFO structure.
@return whether path is valid.
**/
ERROR_STATUS
GetPathInfo (
PATH_INFO *PathInfo
)
{
DRIVE_INFO DriveInfo;
CHAR VolumeLetter;
CHAR DiskPathTemplate[] = "\\\\.\\PHYSICALDRIVE%u";
CHAR FloppyPathTemplate[] = "\\\\.\\%c:";
FILE *f;
//
// If path is disk path
//
if (IsLetter(PathInfo->Path[0]) && (PathInfo->Path[1] == ':') && (PathInfo->Path[2] == '\0')) {
VolumeLetter = PathInfo->Path[0];
if ((VolumeLetter == 'A') || (VolumeLetter == 'a') ||
(VolumeLetter == 'B') || (VolumeLetter == 'b')) {
PathInfo->Type = PathFloppy;
sprintf (PathInfo->PhysicalPath, FloppyPathTemplate, VolumeLetter);
return ErrorSuccess;
}
if (!GetDriveInfo(VolumeLetter, &DriveInfo)) {
fprintf (stderr, "ERROR: GetDriveInfo - 0x%x\n", GetLastError ());
return ErrorPath;
}
if (!PathInfo->Input && (DriveInfo.DriveType->Type == DRIVE_FIXED)) {
fprintf (stderr, "ERROR: Could patch own IDE disk!\n");
return ErrorPath;
}
sprintf(PathInfo->PhysicalPath, DiskPathTemplate, DriveInfo.DiskNumber);
if (DriveInfo.DriveType->Type == DRIVE_REMOVABLE) {
PathInfo->Type = PathUsb;
} else if (DriveInfo.DriveType->Type == DRIVE_FIXED) {
PathInfo->Type = PathIde;
} else {
fprintf (stderr, "ERROR, Invalid disk path - %s", PathInfo->Path);
return ErrorPath;
}
return ErrorSuccess;
}
PathInfo->Type = PathFile;
if (PathInfo->Input) {
//
// If path is file path, check whether file is valid.
//
f = fopen (PathInfo->Path, "r");
if (f == NULL) {
fprintf (stderr, "error E2003: File was not provided!\n");
return ErrorPath;
}
}
PathInfo->Type = PathFile;
strcpy(PathInfo->PhysicalPath, PathInfo->Path);
return ErrorSuccess;
}
INT
main (
INT argc,
CHAR *argv[]
)
{
CHAR8 *AppName;
INTN Index;
BOOLEAN ProcessMbr;
ERROR_STATUS Status;
EFI_STATUS EfiStatus;
PATH_INFO InputPathInfo = {0};
PATH_INFO OutputPathInfo = {0};
UINT64 LogLevel;
SetUtilityName (UTILITY_NAME);
AppName = *argv;
argv ++;
argc --;
ProcessMbr = FALSE;
if (argc == 0) {
PrintUsage();
return 0;
}
//
// Parse command line
//
for (Index = 0; Index < argc; Index ++) {
if ((stricmp (argv[Index], "-l") == 0) || (stricmp (argv[Index], "--list") == 0)) {
ListDrive ();
return 0;
}
if ((stricmp (argv[Index], "-m") == 0) || (stricmp (argv[Index], "--mbr") == 0)) {
ProcessMbr = TRUE;
continue;
}
if ((stricmp (argv[Index], "-i") == 0) || (stricmp (argv[Index], "--input") == 0)) {
InputPathInfo.Path = argv[Index + 1];
InputPathInfo.Input = TRUE;
if (InputPathInfo.Path == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Input file name can't be NULL");
return 1;
}
if (InputPathInfo.Path[0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Input file is missing");
return 1;
}
++Index;
continue;
}
if ((stricmp (argv[Index], "-o") == 0) || (stricmp (argv[Index], "--output") == 0)) {
OutputPathInfo.Path = argv[Index + 1];
OutputPathInfo.Input = FALSE;
if (OutputPathInfo.Path == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Output file name can't be NULL");
return 1;
}
if (OutputPathInfo.Path[0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Output file is missing");
return 1;
}
++Index;
continue;
}
if ((stricmp (argv[Index], "-h") == 0) || (stricmp (argv[Index], "--help") == 0)) {
PrintUsage ();
return 0;
}
if (stricmp (argv[Index], "--version") == 0) {
Version ();
return 0;
}
if ((stricmp (argv[Index], "-v") == 0) || (stricmp (argv[Index], "--verbose") == 0)) {
continue;
}
if ((stricmp (argv[Index], "-q") == 0) || (stricmp (argv[Index], "--quiet") == 0)) {
continue;
}
if ((stricmp (argv[Index], "-d") == 0) || (stricmp (argv[Index], "--debug") == 0)) {
EfiStatus = AsciiStringToUint64 (argv[Index + 1], FALSE, &LogLevel);
if (EFI_ERROR (EfiStatus)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[Index], argv[Index + 1]);
return 1;
}
if (LogLevel > 9) {
Error (NULL, 0, 1003, "Invalid option value", "Debug Level range is 0-9, currnt input level is %d", LogLevel);
return 1;
}
SetPrintLevel (LogLevel);
DebugMsg (NULL, 0, 9, "Debug Mode Set", "Debug Output Mode Level %s is set!", argv[Index + 1]);
++Index;
continue;
}
//
// Don't recognize the parameter.
//
Error (NULL, 0, 1000, "Unknown option", "%s", argv[Index]);
return 1;
}
if (InputPathInfo.Path == NULL) {
Error (NULL, 0, 1001, "Missing options", "Input file is missing");
return 1;
}
if (OutputPathInfo.Path == NULL) {
Error (NULL, 0, 1001, "Missing options", "Output file is missing");
return 1;
}
if (GetPathInfo(&InputPathInfo) != ErrorSuccess) {
Error (NULL, 0, 1003, "Invalid option value", "Input file can't be found.");
return 1;
}
if (GetPathInfo(&OutputPathInfo) != ErrorSuccess) {
Error (NULL, 0, 1003, "Invalid option value", "Output file can't be found.");
return 1;
}
//
// Process DBR (Patch or Read)
//
Status = ProcessBsOrMbr (&InputPathInfo, &OutputPathInfo, ProcessMbr);
if (Status == ErrorSuccess) {
fprintf (
stdout,
"%s %s: successful!\n",
(OutputPathInfo.Type != PathFile) ? "Write" : "Read",
ProcessMbr ? "MBR" : "DBR"
);
return 0;
} else {
fprintf (
stderr,
"%s: %s %s: failed - %s (LastError: 0x%x)!\n",
(Status == ErrorNoMbr) ? "WARNING" : "ERROR",
(OutputPathInfo.Type != PathFile) ? "Write" : "Read",
ProcessMbr ? "MBR" : "DBR",
ErrorStatusDesc[Status],
GetLastError ()
);
return 1;
}
}

View File

@@ -0,0 +1,73 @@
/** @file
Get Drv Num offset from Fat file system.
Copyright 2006 - 2008, 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.
**/
#include <stdio.h>
#include "FatFormat.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 E3003: FAT - BPB_FATSz16, BPB_FATSz32 - 0, expected: Non-Zero number\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 E3003: FAT - BPB_TotSec16, BPB_TotSec32 - 0, expected: Non-Zero number\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,10 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = GenBootSector
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = GenBootSector.obj GetDrvNumOffset.obj
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,10 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = GenCrc32
LIBS = -lCommon
OBJECTS = GenCrc32.o
include $(MAKEROOT)/Makefiles/app.makefile

View File

@@ -0,0 +1,362 @@
/** @file
Copyright (c) 2007 - 2008, 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:
GenCrc32.c
Abstract:
Calculate Crc32 value and Verify Crc32 value for input data.
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "EfiUtilityMsgs.h"
#include "CommonLib.h"
#include "Crc32.h"
#define UTILITY_NAME "GenCrc32"
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
#define CRC32_NULL 0
#define CRC32_ENCODE 1
#define CRC32_DECODE 2
VOID
Version (
VOID
)
/*++
Routine Description:
Displays the standard utility information to SDTOUT
Arguments:
None
Returns:
None
--*/
{
fprintf (stdout, "%s Version %d.%d\n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION);
}
VOID
Usage (
VOID
)
/*++
Routine Description:
Displays the utility usage syntax to STDOUT
Arguments:
None
Returns:
None
--*/
{
//
// Summary usage
//
fprintf (stdout, "\nUsage: %s -e|-d [options] <input_file>\n\n", UTILITY_NAME);
//
// Copyright declaration
//
fprintf (stdout, "Copyright (c) 2007 - 2009, Intel Corporation. All rights reserved.\n\n");
//
// Details Option
//
fprintf (stdout, "Options:\n");
fprintf (stdout, " -o FileName, --output FileName\n\
File will be created to store the ouput content.\n");
fprintf (stdout, " -e, --encode Calculate CRC32 value for the input file.\n");
fprintf (stdout, " -d, --decode Verify CRC32 value for the input file.\n");
fprintf (stdout, " -v, --verbose Turn on verbose output with informational messages.\n");
fprintf (stdout, " -q, --quiet Disable all messages except key message and fatal error\n");
fprintf (stdout, " --debug level Enable debug messages, at input debug level.\n");
fprintf (stdout, " --version Show program's version number and exit.\n");
fprintf (stdout, " -h, --help Show this help message and exit.\n");
}
int
main (
INT32 argc,
CHAR8 *argv[]
)
/*++
Routine Description:
Main function.
Arguments:
argc - Number of command line parameters.
argv - Array of pointers to parameter strings.
Returns:
STATUS_SUCCESS - Utility exits successfully.
STATUS_ERROR - Some error occurred during execution.
--*/
{
EFI_STATUS Status;
CHAR8 *OutputFileName;
CHAR8 *InputFileName;
UINT8 *FileBuffer;
UINT32 FileSize;
UINT64 LogLevel;
UINT8 FileAction;
UINT32 Crc32Value;
FILE *InFile;
FILE *OutFile;
//
// Init local variables
//
LogLevel = 0;
Status = EFI_SUCCESS;
InputFileName = NULL;
OutputFileName = NULL;
FileAction = CRC32_NULL;
InFile = NULL;
OutFile = NULL;
Crc32Value = 0;
FileBuffer = NULL;
SetUtilityName (UTILITY_NAME);
if (argc == 1) {
Error (NULL, 0, 1001, "Missing options", "no options input");
Usage ();
return STATUS_ERROR;
}
//
// Parse command line
//
argc --;
argv ++;
if ((stricmp (argv[0], "-h") == 0) || (stricmp (argv[0], "--help") == 0)) {
Version ();
Usage ();
return STATUS_SUCCESS;
}
if (stricmp (argv[0], "--version") == 0) {
Version ();
return STATUS_SUCCESS;
}
while (argc > 0) {
if ((stricmp (argv[0], "-o") == 0) || (stricmp (argv[0], "--output") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Output File name is missing for -o option");
goto Finish;
}
OutputFileName = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-e") == 0) || (stricmp (argv[0], "--encode") == 0)) {
FileAction = CRC32_ENCODE;
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-d") == 0) || (stricmp (argv[0], "--decode") == 0)) {
FileAction = CRC32_DECODE;
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-v") == 0) || (stricmp (argv[0], "--verbose") == 0)) {
SetPrintLevel (VERBOSE_LOG_LEVEL);
VerboseMsg ("Verbose output Mode Set!");
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-q") == 0) || (stricmp (argv[0], "--quiet") == 0)) {
SetPrintLevel (KEY_LOG_LEVEL);
KeyMsg ("Quiet output Mode Set!");
argc --;
argv ++;
continue;
}
if (stricmp (argv[0], "--debug") == 0) {
Status = AsciiStringToUint64 (argv[1], FALSE, &LogLevel);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
goto Finish;
}
if (LogLevel > 9) {
Error (NULL, 0, 1003, "Invalid option value", "Debug Level range is 0-9, current input level is %d", LogLevel);
goto Finish;
}
SetPrintLevel (LogLevel);
DebugMsg (NULL, 0, 9, "Debug Mode Set", "Debug Output Mode Level %s is set!", argv[1]);
argc -= 2;
argv += 2;
continue;
}
if (argv[0][0] == '-') {
Error (NULL, 0, 1000, "Unknown option", argv[0]);
goto Finish;
}
//
// Get Input file file name.
//
InputFileName = argv[0];
argc --;
argv ++;
}
VerboseMsg ("%s tool start.", UTILITY_NAME);
//
// Check Input paramters
//
if (FileAction == CRC32_NULL) {
Error (NULL, 0, 1001, "Missing option", "either the encode or the decode option must be specified!");
return STATUS_ERROR;
} else if (FileAction == CRC32_ENCODE) {
VerboseMsg ("File will be encoded by Crc32");
} else if (FileAction == CRC32_DECODE) {
VerboseMsg ("File will be decoded by Crc32");
}
if (InputFileName == NULL) {
Error (NULL, 0, 1001, "Missing option", "Input files are not specified");
goto Finish;
} else {
VerboseMsg ("Input file name is %s", InputFileName);
}
if (OutputFileName == NULL) {
Error (NULL, 0, 1001, "Missing option", "Output file are not specified");
goto Finish;
} else {
VerboseMsg ("Output file name is %s", OutputFileName);
}
//
// Open Input file and read file data.
//
InFile = fopen (InputFileName, "rb");
if (InFile == NULL) {
Error (NULL, 0, 0001, "Error opening file", InputFileName);
return STATUS_ERROR;
}
fseek (InFile, 0, SEEK_END);
FileSize = ftell (InFile);
fseek (InFile, 0, SEEK_SET);
FileBuffer = (UINT8 *) malloc (FileSize);
if (FileBuffer == NULL) {
Error (NULL, 0, 4001, "Resource", "memory cannot be allcoated!");
goto Finish;
}
fread (FileBuffer, 1, FileSize, InFile);
fclose (InFile);
VerboseMsg ("the size of the input file is %d bytes", FileSize);
//
// Open output file
//
OutFile = fopen (OutputFileName, "wb");
if (OutFile == NULL) {
Error (NULL, 0, 0001, "Error opening file", OutputFileName);
goto Finish;
}
//
// Calculate Crc32 value
//
if (FileAction == CRC32_ENCODE) {
Status = CalculateCrc32 (FileBuffer, FileSize, &Crc32Value);
if (Status != EFI_SUCCESS) {
Error (NULL, 0, 3000, "Invalid", "Calculate CRC32 value failed!");
goto Finish;
}
//
// Done, write output file.
//
fwrite (&Crc32Value, 1, sizeof (Crc32Value), OutFile);
VerboseMsg ("The calculated CRC32 value is 0x%08x", Crc32Value);
fwrite (FileBuffer, 1, FileSize, OutFile);
VerboseMsg ("the size of the encoded file is %d bytes", FileSize + sizeof (UINT32));
} else {
//
// Verify Crc32 Value
//
Status = CalculateCrc32 (FileBuffer + sizeof (UINT32), FileSize - sizeof (UINT32), &Crc32Value);
if (Status != EFI_SUCCESS) {
Error (NULL, 0, 3000, "Invalid", "Calculate CRC32 value failed!");
goto Finish;
}
VerboseMsg ("The calculated CRC32 value is 0x%08x and File Crc32 value is 0x%08x", Crc32Value, *(UINT32 *)FileBuffer);
if (Crc32Value != *(UINT32 *)FileBuffer) {
Error (NULL, 0, 3000, "Invalid", "CRC32 value of input file is not correct!");
Status = STATUS_ERROR;
goto Finish;
}
//
// Done, write output file.
//
fwrite (FileBuffer + sizeof (UINT32), 1, FileSize - sizeof (UINT32), OutFile);
VerboseMsg ("the size of the decoded file is %d bytes", FileSize - sizeof (UINT32));
}
Finish:
if (FileBuffer != NULL) {
free (FileBuffer);
}
if (OutFile != NULL) {
fclose (OutFile);
}
VerboseMsg ("%s tool done with return code is 0x%x.", UTILITY_NAME, GetUtilityStatus ());
return GetUtilityStatus ();
}

View File

@@ -0,0 +1,10 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = GenCrc32
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = GenCrc32.obj
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,11 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = GenFfs
OBJECTS = GenFfs.o
include $(MAKEROOT)/Makefiles/app.makefile
LIBS = -lCommon

View File

@@ -0,0 +1,897 @@
/**
Copyright (c) 2004-2008, 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:
GenFfs.c
Abstract:
This file contains functions required to generate a Firmware File System
file.
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Common/UefiBaseTypes.h>
#include <Common/PiFirmwareFile.h>
#include <IndustryStandard/PeImage.h>
#include "CommonLib.h"
#include "ParseInf.h"
#include "EfiUtilityMsgs.h"
#define UTILITY_NAME "GenFfs"
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
STATIC CHAR8 *mFfsFileType[] = {
NULL, // 0x00
"EFI_FV_FILETYPE_RAW", // 0x01
"EFI_FV_FILETYPE_FREEFORM", // 0x02
"EFI_FV_FILETYPE_SECURITY_CORE", // 0x03
"EFI_FV_FILETYPE_PEI_CORE", // 0x04
"EFI_FV_FILETYPE_DXE_CORE", // 0x05
"EFI_FV_FILETYPE_PEIM", // 0x06
"EFI_FV_FILETYPE_DRIVER", // 0x07
"EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER", // 0x08
"EFI_FV_FILETYPE_APPLICATION", // 0x09
"EFI_FV_FILETYPE_SMM", // 0x0A
"EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE",// 0x0B
"EFI_FV_FILETYPE_COMBINED_SMM_DXE", // 0x0C
"EFI_FV_FILETYPE_SMM_CORE" // 0x0D
};
STATIC CHAR8 *mAlignName[] = {
"1", "2", "4", "8", "16", "32", "64", "128", "256", "512",
"1K", "2K", "4K", "8K", "16K", "32K", "64K"
};
STATIC CHAR8 *mFfsValidAlignName[] = {
"8", "16", "128", "512", "1K", "4K", "32K", "64K"
};
STATIC UINT32 mFfsValidAlign[] = {0, 8, 16, 128, 512, 1024, 4096, 32768, 65536};
STATIC EFI_GUID mZeroGuid = {0};
STATIC
VOID
Version (
VOID
)
/*++
Routine Description:
Print out version information for this utility.
Arguments:
None
Returns:
None
--*/
{
fprintf (stdout, "%s Version %d.%d\n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION);
}
STATIC
VOID
Usage (
VOID
)
/*++
Routine Description:
Print Error / Help message.
Arguments:
VOID
Returns:
None
--*/
{
//
// Summary usage
//
fprintf (stdout, "\nUsage: %s [options]\n\n", UTILITY_NAME);
//
// Copyright declaration
//
fprintf (stdout, "Copyright (c) 2007, Intel Corporation. All rights reserved.\n\n");
//
// Details Option
//
fprintf (stdout, "Options:\n");
fprintf (stdout, " -o FileName, --outputfile FileName\n\
File is FFS file to be created.\n");
fprintf (stdout, " -t Type, --filetype Type\n\
Type is one FV file type defined in PI spec, which is\n\
EFI_FV_FILETYPE_RAW, EFI_FV_FILETYPE_FREEFORM,\n\
EFI_FV_FILETYPE_SECURITY_CORE, EFI_FV_FILETYPE_PEIM,\n\
EFI_FV_FILETYPE_PEI_CORE, EFI_FV_FILETYPE_DXE_CORE,\n\
EFI_FV_FILETYPE_DRIVER, EFI_FV_FILETYPE_APPLICATION,\n\
EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER,\n\
EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE.\n");
fprintf (stdout, " -g FileGuid, --fileguid FileGuid\n\
FileGuid is one module guid.\n\
Its format is xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n");
fprintf (stdout, " -x, --fixed Indicates that the file may not be moved\n\
from its present location.\n");
fprintf (stdout, " -s, --checksum Indicates to calculate file checksum.\n");
fprintf (stdout, " -a FileAlign, --align FileAlign\n\
FileAlign points to file alignment, which only support\n\
the following align: 1,2,4,8,16,128,512,1K,4K,32K,64K\n");
fprintf (stdout, " -i SectionFile, --sectionfile SectionFile\n\
Section file will be contained in this FFS file.\n");
fprintf (stdout, " -n SectionAlign, --sectionalign SectionAlign\n\
SectionAlign points to section alignment, which support\n\
the alignment scope 1~64K. It is specified together\n\
with sectionfile to point its alignment in FFS file.\n");
fprintf (stdout, " -v, --verbose Turn on verbose output with informational messages.\n");
fprintf (stdout, " -q, --quiet Disable all messages except key message and fatal error\n");
fprintf (stdout, " -d, --debug level Enable debug messages, at input debug level.\n");
fprintf (stdout, " --version Show program's version number and exit.\n");
fprintf (stdout, " -h, --help Show this help message and exit.\n");
}
STATIC
EFI_STATUS
StringtoAlignment (
IN CHAR8 *AlignBuffer,
OUT UINT32 *AlignNumber
)
/*++
Routine Description:
Converts Align String to align value (1~64K).
Arguments:
AlignBuffer - Pointer to Align string.
AlignNumber - Pointer to Align value.
Returns:
EFI_SUCCESS Successfully convert align string to align value.
EFI_INVALID_PARAMETER Align string is invalid or align value is not in scope.
--*/
{
UINT32 Index = 0;
//
// Check AlignBuffer
//
if (AlignBuffer == NULL) {
return EFI_INVALID_PARAMETER;
}
for (Index = 0; Index < sizeof (mAlignName) / sizeof (CHAR8 *); Index ++) {
if (stricmp (AlignBuffer, mAlignName [Index]) == 0) {
*AlignNumber = 1 << Index;
return EFI_SUCCESS;
}
}
return EFI_INVALID_PARAMETER;
}
STATIC
UINT8
StringToType (
IN CHAR8 *String
)
/*++
Routine Description:
Converts File Type String to value. EFI_FV_FILETYPE_ALL indicates that an
unrecognized file type was specified.
Arguments:
String - File type string
Returns:
File Type Value
--*/
{
UINT8 Index = 0;
if (String == NULL) {
return EFI_FV_FILETYPE_ALL;
}
for (Index = 0; Index < sizeof (mFfsFileType) / sizeof (CHAR8 *); Index ++) {
if (mFfsFileType [Index] != NULL && (stricmp (String, mFfsFileType [Index]) == 0)) {
return Index;
}
}
return EFI_FV_FILETYPE_ALL;
}
STATIC
EFI_STATUS
GetSectionContents (
IN CHAR8 **InputFileName,
IN UINT32 *InputFileAlign,
IN UINT32 InputFileNum,
OUT UINT8 *FileBuffer,
OUT UINT32 *BufferLength,
OUT UINT32 *MaxAlignment,
OUT UINT8 *PESectionNum
)
/*++
Routine Description:
Get the contents of all section files specified in InputFileName
into FileBuffer.
Arguments:
InputFileName - Name of the input file.
InputFileAlign - Alignment required by the input file data.
InputFileNum - Number of input files. Should be at least 1.
FileBuffer - Output buffer to contain data
BufferLength - On input, this is size of the FileBuffer.
On output, this is the actual length of the data.
MaxAlignment - The max alignment required by all the input file datas.
PeSectionNum - Calculate the number of Pe/Te Section in this FFS file.
Returns:
EFI_SUCCESS on successful return
EFI_INVALID_PARAMETER if InputFileNum is less than 1 or BufferLength point is NULL.
EFI_ABORTED if unable to open input file.
EFI_BUFFER_TOO_SMALL FileBuffer is not enough to contain all file data.
--*/
{
UINT32 Size;
UINT32 Offset;
UINT32 FileSize;
UINT32 Index;
FILE *InFile;
EFI_COMMON_SECTION_HEADER *SectHeader;
EFI_COMMON_SECTION_HEADER TempSectHeader;
EFI_TE_IMAGE_HEADER TeHeader;
UINT32 TeOffset;
Size = 0;
Offset = 0;
TeOffset = 0;
//
// Go through our array of file names and copy their contents
// to the output buffer.
//
for (Index = 0; Index < InputFileNum; Index++) {
//
// make sure section ends on a DWORD boundary
//
while ((Size & 0x03) != 0) {
Size++;
}
//
// Get the Max alignment of all input file datas
//
if (*MaxAlignment < InputFileAlign [Index]) {
*MaxAlignment = InputFileAlign [Index];
}
//
// Open file and read contents
//
InFile = fopen (InputFileName[Index], "rb");
if (InFile == NULL) {
Error (NULL, 0, 0001, "Error opening file", InputFileName[Index]);
return EFI_ABORTED;
}
fseek (InFile, 0, SEEK_END);
FileSize = ftell (InFile);
fseek (InFile, 0, SEEK_SET);
DebugMsg (NULL, 0, 9, "Input section files",
"the input section name is %s and the size is %d bytes", InputFileName[Index], FileSize);
//
// Check this section is Te/Pe section, and Calculate the numbers of Te/Pe section.
//
TeOffset = 0;
fread (&TempSectHeader, 1, sizeof (TempSectHeader), InFile);
if (TempSectHeader.Type == EFI_SECTION_TE) {
(*PESectionNum) ++;
fread (&TeHeader, 1, sizeof (TeHeader), InFile);
if (TeHeader.Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) {
TeOffset = TeHeader.StrippedSize - sizeof (TeHeader);
}
} else if (TempSectHeader.Type == EFI_SECTION_PE32) {
(*PESectionNum) ++;
} else if (TempSectHeader.Type == EFI_SECTION_COMPRESSION ||
TempSectHeader.Type == EFI_SECTION_GUID_DEFINED ||
TempSectHeader.Type == EFI_SECTION_FIRMWARE_VOLUME_IMAGE) {
//
// for the encapsulated section, assume it contains Pe/Te section
//
(*PESectionNum) ++;
}
fseek (InFile, 0, SEEK_SET);
//
// Revert TeOffset to the converse value relative to Alignment
// This is to assure the original PeImage Header at Alignment.
//
if ((TeOffset != 0) && (InputFileAlign [Index] != 0)) {
TeOffset = InputFileAlign [Index] - (TeOffset % InputFileAlign [Index]);
TeOffset = TeOffset % InputFileAlign [Index];
}
//
// make sure section data meet its alignment requirement by adding one raw pad section.
// But the different sections have the different section header. Necessary or not?
// Based on section type to adjust offset? Todo
//
if ((InputFileAlign [Index] != 0) && (((Size + sizeof (EFI_COMMON_SECTION_HEADER) + TeOffset) % InputFileAlign [Index]) != 0)) {
Offset = (Size + 2 * sizeof (EFI_COMMON_SECTION_HEADER) + TeOffset + InputFileAlign [Index] - 1) & ~(InputFileAlign [Index] - 1);
Offset = Offset - Size - sizeof (EFI_COMMON_SECTION_HEADER) - TeOffset;
if (FileBuffer != NULL && ((Size + Offset) < *BufferLength)) {
SectHeader = (EFI_COMMON_SECTION_HEADER *) (FileBuffer + Size);
SectHeader->Type = EFI_SECTION_RAW;
SectHeader->Size[0] = (UINT8) (Offset & 0xff);
SectHeader->Size[1] = (UINT8) ((Offset & 0xff00) >> 8);
SectHeader->Size[2] = (UINT8) ((Offset & 0xff0000) >> 16);
}
DebugMsg (NULL, 0, 9, "Pad raw section for section data alignment",
"Pad Raw section size is %d", Offset);
Size = Size + Offset;
}
//
// Now read the contents of the file into the buffer
// Buffer must be enough to contain the file content.
//
if ((FileSize > 0) && (FileBuffer != NULL) && ((Size + FileSize) <= *BufferLength)) {
if (fread (FileBuffer + Size, (size_t) FileSize, 1, InFile) != 1) {
Error (NULL, 0, 0004, "Error reading file", InputFileName[Index]);
fclose (InFile);
return EFI_ABORTED;
}
}
fclose (InFile);
Size += FileSize;
}
//
// Set the actual length of the data.
//
if (Size > *BufferLength) {
*BufferLength = Size;
return EFI_BUFFER_TOO_SMALL;
} else {
*BufferLength = Size;
return EFI_SUCCESS;
}
}
int
main (
INT32 argc,
CHAR8 *argv[]
)
/*++
Routine Description:
Main function.
Arguments:
argc - Number of command line parameters.
argv - Array of pointers to parameter strings.
Returns:
STATUS_SUCCESS - Utility exits successfully.
STATUS_ERROR - Some error occurred during execution.
--*/
{
EFI_STATUS Status;
EFI_FFS_FILE_ATTRIBUTES FfsAttrib;
UINT32 FfsAlign;
EFI_FV_FILETYPE FfsFiletype;
CHAR8 *OutputFileName;
EFI_GUID FileGuid = {0};
UINT32 InputFileNum;
UINT32 *InputFileAlign;
CHAR8 **InputFileName;
UINT8 *FileBuffer;
UINT32 FileSize;
UINT32 MaxAlignment;
EFI_FFS_FILE_HEADER FfsFileHeader;
FILE *FfsFile;
UINT32 Index;
UINT64 LogLevel;
UINT8 PeSectionNum;
//
// Init local variables
//
LogLevel = 0;
Index = 0;
FfsAttrib = 0;
FfsAlign = 0;
FfsFiletype = EFI_FV_FILETYPE_ALL;
OutputFileName = NULL;
InputFileNum = 0;
InputFileName = NULL;
InputFileAlign = NULL;
FileBuffer = NULL;
FileSize = 0;
MaxAlignment = 1;
FfsFile = NULL;
Status = EFI_SUCCESS;
PeSectionNum = 0;
SetUtilityName (UTILITY_NAME);
if (argc == 1) {
Error (NULL, 0, 1001, "Missing options", "no options input");
Usage ();
return STATUS_ERROR;
}
//
// Parse command line
//
argc --;
argv ++;
if ((stricmp (argv[0], "-h") == 0) || (stricmp (argv[0], "--help") == 0)) {
Version ();
Usage ();
return STATUS_SUCCESS;
}
if (stricmp (argv[0], "--version") == 0) {
Version ();
return STATUS_SUCCESS;
}
while (argc > 0) {
if ((stricmp (argv[0], "-t") == 0) || (stricmp (argv[0], "--filetype") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "file type is missing for -t option");
goto Finish;
}
FfsFiletype = StringToType (argv[1]);
if (FfsFiletype == EFI_FV_FILETYPE_ALL) {
Error (NULL, 0, 1003, "Invalid option value", "%s is not a valid file type", argv[1]);
goto Finish;
}
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-o") == 0) || (stricmp (argv[0], "--outputfile") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Output file is missing for -o option");
goto Finish;
}
OutputFileName = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-g") == 0) || (stricmp (argv[0], "--fileguid") == 0)) {
Status = StringToGuid (argv[1], &FileGuid);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
goto Finish;
}
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-x") == 0) || (stricmp (argv[0], "--fixed") == 0)) {
FfsAttrib |= FFS_ATTRIB_FIXED;
argc -= 1;
argv += 1;
continue;
}
if ((stricmp (argv[0], "-s") == 0) || (stricmp (argv[0], "--checksum") == 0)) {
FfsAttrib |= FFS_ATTRIB_CHECKSUM;
argc -= 1;
argv += 1;
continue;
}
if ((stricmp (argv[0], "-a") == 0) || (stricmp (argv[0], "--align") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Align value is missing for -a option");
goto Finish;
}
for (Index = 0; Index < sizeof (mFfsValidAlignName) / sizeof (CHAR8 *); Index ++) {
if (stricmp (argv[1], mFfsValidAlignName[Index]) == 0) {
break;
}
}
if (Index == sizeof (mFfsValidAlignName) / sizeof (CHAR8 *)) {
if ((stricmp (argv[1], "1") == 0) || (stricmp (argv[1], "2") == 0) || (stricmp (argv[1], "4") == 0)) {
//
// 1, 2, 4 byte alignment same to 8 byte alignment
//
Index = 0;
} else {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
goto Finish;
}
}
FfsAlign = Index;
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-i") == 0) || (stricmp (argv[0], "--sectionfile") == 0)) {
//
// Get Input file name and its alignment
//
if (argv[1] == NULL || argv[1][0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "input section file is missing for -i option");
goto Finish;
}
//
// Allocate Input file name buffer and its alignment buffer.
//
if ((InputFileNum == 0) && (InputFileName == NULL)) {
InputFileName = (CHAR8 **) malloc (MAXIMUM_INPUT_FILE_NUM * sizeof (CHAR8 *));
if (InputFileName == NULL) {
Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
return STATUS_ERROR;
}
memset (InputFileName, 0, (MAXIMUM_INPUT_FILE_NUM * sizeof (CHAR8 *)));
InputFileAlign = (UINT32 *) malloc (MAXIMUM_INPUT_FILE_NUM * sizeof (UINT32));
if (InputFileAlign == NULL) {
Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
free (InputFileName);
return STATUS_ERROR;
}
memset (InputFileAlign, 0, MAXIMUM_INPUT_FILE_NUM * sizeof (UINT32));
} else if (InputFileNum % MAXIMUM_INPUT_FILE_NUM == 0) {
//
// InputFileName and alignment buffer too small, need to realloc
//
InputFileName = (CHAR8 **) realloc (
InputFileName,
(InputFileNum + MAXIMUM_INPUT_FILE_NUM) * sizeof (CHAR8 *)
);
if (InputFileName == NULL) {
Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
free (InputFileAlign);
return STATUS_ERROR;
}
memset (&(InputFileName[InputFileNum]), 0, (MAXIMUM_INPUT_FILE_NUM * sizeof (CHAR8 *)));
InputFileAlign = (UINT32 *) realloc (
InputFileAlign,
(InputFileNum + MAXIMUM_INPUT_FILE_NUM) * sizeof (UINT32)
);
if (InputFileAlign == NULL) {
Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
free (InputFileName);
return STATUS_ERROR;
}
memset (&(InputFileAlign[InputFileNum]), 0, (MAXIMUM_INPUT_FILE_NUM * sizeof (UINT32)));
}
InputFileName[InputFileNum] = argv[1];
argc -= 2;
argv += 2;
if (argc <= 0) {
InputFileNum ++;
break;
}
//
// Section File alignment requirement
//
if ((stricmp (argv[0], "-n") == 0) || (stricmp (argv[0], "--sectionalign") == 0)) {
Status = StringtoAlignment (argv[1], &(InputFileAlign[InputFileNum]));
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
goto Finish;
}
argc -= 2;
argv += 2;
}
InputFileNum ++;
continue;
}
if ((stricmp (argv[0], "-n") == 0) || (stricmp (argv[0], "--sectionalign") == 0)) {
Error (NULL, 0, 1000, "Unknown option", "SectionAlign option must be specified with section file.");
goto Finish;
}
if ((stricmp (argv[0], "-v") == 0) || (stricmp (argv[0], "--verbose") == 0)) {
SetPrintLevel (VERBOSE_LOG_LEVEL);
VerboseMsg ("Verbose output Mode Set!");
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-q") == 0) || (stricmp (argv[0], "--quiet") == 0)) {
SetPrintLevel (KEY_LOG_LEVEL);
KeyMsg ("Quiet output Mode Set!");
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-d") == 0) || (stricmp (argv[0], "--debug") == 0)) {
Status = AsciiStringToUint64 (argv[1], FALSE, &LogLevel);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
goto Finish;
}
if (LogLevel > 9) {
Error (NULL, 0, 1003, "Invalid option value", "Debug Level range is 0-9, current input level is %d", LogLevel);
goto Finish;
}
SetPrintLevel (LogLevel);
DebugMsg (NULL, 0, 9, "Debug Mode Set", "Debug Output Mode Level %s is set!", argv[1]);
argc -= 2;
argv += 2;
continue;
}
Error (NULL, 0, 1000, "Unknown option", argv[0]);
goto Finish;
}
VerboseMsg ("%s tool start.", UTILITY_NAME);
//
// Check the complete input paramters.
//
if (FfsFiletype == EFI_FV_FILETYPE_ALL) {
Error (NULL, 0, 1001, "Missing option", "filetype");
goto Finish;
}
if (CompareGuid (&FileGuid, &mZeroGuid) == 0) {
Error (NULL, 0, 1001, "Missing option", "fileguid");
goto Finish;
}
if (InputFileNum == 0) {
Error (NULL, 0, 1001, "Missing option", "Input files");
goto Finish;
}
//
// Output input parameter information
//
VerboseMsg ("Fv File type is %s", mFfsFileType [FfsFiletype]);
VerboseMsg ("Output file name is %s", OutputFileName);
VerboseMsg ("FFS File Guid is %08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
FileGuid.Data1,
FileGuid.Data2,
FileGuid.Data3,
FileGuid.Data4[0],
FileGuid.Data4[1],
FileGuid.Data4[2],
FileGuid.Data4[3],
FileGuid.Data4[4],
FileGuid.Data4[5],
FileGuid.Data4[6],
FileGuid.Data4[7]);
if ((FfsAttrib & FFS_ATTRIB_FIXED) != 0) {
VerboseMsg ("FFS File has the fixed file attribute");
}
if ((FfsAttrib & FFS_ATTRIB_CHECKSUM) != 0) {
VerboseMsg ("FFS File requires the checksum of the whole file");
}
VerboseMsg ("FFS file alignment is %s", mFfsValidAlignName[FfsAlign]);
for (Index = 0; Index < InputFileNum; Index ++) {
if (InputFileAlign[Index] == 0) {
//
// Minimum alignment is 1 byte.
//
InputFileAlign[Index] = 1;
}
VerboseMsg ("the %dth input section name is %s and section alignment is %d", Index, InputFileName[Index], InputFileAlign[Index]);
}
//
// Calculate the size of all input section files.
//
Status = GetSectionContents (
InputFileName,
InputFileAlign,
InputFileNum,
FileBuffer,
&FileSize,
&MaxAlignment,
&PeSectionNum
);
if ((FfsFiletype == EFI_FV_FILETYPE_SECURITY_CORE ||
FfsFiletype == EFI_FV_FILETYPE_PEI_CORE ||
FfsFiletype == EFI_FV_FILETYPE_DXE_CORE) && (PeSectionNum != 1)) {
Error (NULL, 0, 2000, "Invalid parameter", "Fv File type %s must have one and only one Pe or Te section, but %d Pe/Te section are input", mFfsFileType [FfsFiletype], PeSectionNum);
goto Finish;
}
if ((FfsFiletype == EFI_FV_FILETYPE_PEIM ||
FfsFiletype == EFI_FV_FILETYPE_DRIVER ||
FfsFiletype == EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER ||
FfsFiletype == EFI_FV_FILETYPE_APPLICATION) && (PeSectionNum < 1)) {
Error (NULL, 0, 2000, "Invalid parameter", "Fv File type %s must have at least one Pe or Te section, but no Pe/Te section is input", mFfsFileType [FfsFiletype]);
goto Finish;
}
if (Status == EFI_BUFFER_TOO_SMALL) {
FileBuffer = (UINT8 *) malloc (FileSize);
if (FileBuffer == NULL) {
Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!");
goto Finish;
}
memset (FileBuffer, 0, FileSize);
//
// read all input file contents into a buffer
//
Status = GetSectionContents (
InputFileName,
InputFileAlign,
InputFileNum,
FileBuffer,
&FileSize,
&MaxAlignment,
&PeSectionNum
);
}
if (EFI_ERROR (Status)) {
goto Finish;
}
//
// Create Ffs file header.
//
memset (&FfsFileHeader, 0, sizeof (EFI_FFS_FILE_HEADER));
memcpy (&FfsFileHeader.Name, &FileGuid, sizeof (EFI_GUID));
FfsFileHeader.Type = FfsFiletype;
//
// Update FFS Alignment based on the max alignment required by input section files
//
VerboseMsg ("the max alignment of all input sections is %d", MaxAlignment);
for (Index = 0; Index < sizeof (mFfsValidAlign) / sizeof (UINT32) - 1; Index ++) {
if ((MaxAlignment > mFfsValidAlign [Index]) && (MaxAlignment <= mFfsValidAlign [Index + 1])) {
break;
}
}
if (FfsAlign < Index) {
FfsAlign = Index;
}
VerboseMsg ("the alignment of the genreated FFS file is %d", mFfsValidAlign [FfsAlign + 1]);
FfsFileHeader.Attributes = FfsAttrib | (FfsAlign << 3);
//
// Now FileSize includes the EFI_FFS_FILE_HEADER
//
FileSize += sizeof (EFI_FFS_FILE_HEADER);
VerboseMsg ("the size of the genreated FFS file is %d bytes", FileSize);
FfsFileHeader.Size[0] = (UINT8) (FileSize & 0xFF);
FfsFileHeader.Size[1] = (UINT8) ((FileSize & 0xFF00) >> 8);
FfsFileHeader.Size[2] = (UINT8) ((FileSize & 0xFF0000) >> 16);
//
// Fill in checksums and state, these must be zero for checksumming
//
// FileHeader.IntegrityCheck.Checksum.Header = 0;
// FileHeader.IntegrityCheck.Checksum.File = 0;
// FileHeader.State = 0;
//
FfsFileHeader.IntegrityCheck.Checksum.Header = CalculateChecksum8 (
(UINT8 *) &FfsFileHeader,
sizeof (EFI_FFS_FILE_HEADER)
);
if (FfsFileHeader.Attributes & FFS_ATTRIB_CHECKSUM) {
//
// Ffs header checksum = zero, so only need to calculate ffs body.
//
FfsFileHeader.IntegrityCheck.Checksum.File = CalculateChecksum8 (
FileBuffer,
FileSize - sizeof (EFI_FFS_FILE_HEADER)
);
} else {
FfsFileHeader.IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
}
FfsFileHeader.State = EFI_FILE_HEADER_CONSTRUCTION | EFI_FILE_HEADER_VALID | EFI_FILE_DATA_VALID;
//
// Open output file to write ffs data.
//
remove(OutputFileName);
FfsFile = fopen (OutputFileName, "wb");
if (FfsFile == NULL) {
Error (NULL, 0, 0001, "Error opening file", OutputFileName);
goto Finish;
}
//
// write header
//
fwrite (&FfsFileHeader, 1, sizeof (FfsFileHeader), FfsFile);
//
// write data
//
fwrite (FileBuffer, 1, FileSize - sizeof (EFI_FFS_FILE_HEADER), FfsFile);
fclose (FfsFile);
Finish:
if (InputFileName != NULL) {
free (InputFileName);
}
if (InputFileAlign != NULL) {
free (InputFileAlign);
}
if (FileBuffer != NULL) {
free (FileBuffer);
}
//
// If any errors were reported via the standard error reporting
// routines, then the status has been saved. Get the value and
// return it to the caller.
//
VerboseMsg ("%s tool done with return code is 0x%x.", UTILITY_NAME, GetUtilityStatus ());
return GetUtilityStatus ();
}

View File

@@ -0,0 +1,10 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = GenFfs
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = GenFfs.obj
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,18 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = GenFv
OBJECTS = GenFv.o GenFvInternalLib.o
include $(MAKEROOT)/Makefiles/app.makefile
LIBS = -lCommon
ifeq ($(CYGWIN), CYGWIN)
LIBS += -L/lib/e2fsprogs -luuid
endif
ifeq ($(LINUX), Linux)
LIBS += -luuid
endif

View File

@@ -0,0 +1,713 @@
/** @file
Copyright (c) 2007 - 2008, 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:
GenFv.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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "GenFvInternalLib.h"
//
// Utility Name
//
#define UTILITY_NAME "GenFv"
//
// Utility version information
//
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
#define GENFV_UPDATE_TIME " updated on 2008/11/21"
EFI_GUID mEfiFirmwareFileSystem2Guid = EFI_FIRMWARE_FILE_SYSTEM2_GUID;
STATIC
VOID
Version (
VOID
)
/*++
Routine Description:
Displays the standard utility information to SDTOUT
Arguments:
None
Returns:
None
--*/
{
fprintf (stdout, "%s Version %d.%d %s\n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION, GENFV_UPDATE_TIME);
}
STATIC
VOID
Usage (
VOID
)
/*++
Routine Description:
Displays the utility usage syntax to STDOUT
Arguments:
None
Returns:
None
--*/
{
//
// Summary usage
//
fprintf (stdout, "\nUsage: %s [options]\n\n", UTILITY_NAME);
//
// Copyright declaration
//
fprintf (stdout, "Copyright (c) 2007, Intel Corporation. All rights reserved.\n\n");
//
// Details Option
//
fprintf (stdout, "Options:\n");
fprintf (stdout, " -o FileName, --outputfile FileName\n\
File is the FvImage or CapImage to be created.\n");
fprintf (stdout, " -i FileName, --inputfile FileName\n\
File is the input FV.inf or Cap.inf to specify\n\
how to construct FvImage or CapImage.\n");
fprintf (stdout, " -b BlockSize, --blocksize BlockSize\n\
BlockSize is one HEX or DEC format value\n\
BlockSize is required by Fv Image.\n");
fprintf (stdout, " -n NumberBlock, --numberblock NumberBlock\n\
NumberBlock is one HEX or DEC format value\n\
NumberBlock is one optional parameter.\n");
fprintf (stdout, " -f FfsFile, --ffsfile FfsFile\n\
FfsFile is placed into Fv Image\n\
multi files can input one by one\n");
fprintf (stdout, " -s FileTakenSize, --filetakensize FileTakenSize\n\
FileTakenSize specifies the size of the required\n\
space that the input file is placed in Fvimage.\n\
It is specified together with the input file.\n");
fprintf (stdout, " -r Address, --baseaddr Address\n\
Address is the rebase start address for drivers that\n\
run in Flash. It supports DEC or HEX digital format.\n\
If it is set to zero, no rebase action will be taken\n");
fprintf (stdout, " -a AddressFile, --addrfile AddressFile\n\
AddressFile is one file used to record boot driver base\n\
address and runtime driver base address. And this tool\n\
will update these two addresses after it relocates all\n\
boot drivers and runtime drivers in this fv iamge to\n\
the preferred loaded memory address.\n");
fprintf (stdout, " -m logfile, --map logfile\n\
Logfile is the output fv map file name. if it is not\n\
given, the FvName.map will be the default map file name\n");
fprintf (stdout, " -g Guid, --guid GuidValue\n\
GuidValue is one specific capsule guid value\n\
or fv file system guid value.\n\
Its format is xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n");
fprintf (stdout, " --FvNameGuid GuidValue is the Fv Name Guid value.\n\
Its format is xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n");
fprintf (stdout, " --capflag CapFlag Capsule Reset Flag can be PersistAcrossReset,\n\
or PopulateSystemTable or not set.\n");
fprintf (stdout, " --capheadsize HeadSize\n\
HeadSize is one HEX or DEC format value\n\
HeadSize is required by Capsule Image.\n");
fprintf (stdout, " -c, --capsule Create Capsule Image.\n");
fprintf (stdout, " -p, --dump Dump Capsule Image header.\n");
fprintf (stdout, " -v, --verbose Turn on verbose output with informational messages.\n");
fprintf (stdout, " -q, --quiet Disable all messages except key message and fatal error\n");
fprintf (stdout, " -d, --debug level Enable debug messages, at input debug level.\n");
fprintf (stdout, " --version Show program's version number and exit.\n");
fprintf (stdout, " -h, --help Show this help message and exit.\n");
}
UINT32 mFvTotalSize;
UINT32 mFvTakenSize;
int
main (
IN int argc,
IN char **argv
)
/*++
Routine Description:
This utility uses GenFvImage.Lib to build a firmware volume image.
Arguments:
FvInfFileName The name of an FV image description file or Capsule Image.
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;
CHAR8 *AddrFileName;
CHAR8 *MapFileName;
CHAR8 *InfFileImage;
UINT32 InfFileSize;
CHAR8 *OutFileName;
CHAR8 ValueString[_MAX_PATH];
BOOLEAN CapsuleFlag;
BOOLEAN DumpCapsule;
MEMORY_FILE AddrMemoryFile;
FILE *FpFile;
EFI_CAPSULE_HEADER *CapsuleHeader;
UINT64 LogLevel, TempNumber;
UINT32 Index;
InfFileName = NULL;
AddrFileName = NULL;
InfFileImage = NULL;
OutFileName = NULL;
MapFileName = NULL;
InfFileSize = 0;
CapsuleFlag = FALSE;
DumpCapsule = FALSE;
FpFile = NULL;
CapsuleHeader = NULL;
LogLevel = 0;
TempNumber = 0;
Index = 0;
mFvTotalSize = 0;
mFvTakenSize = 0;
SetUtilityName (UTILITY_NAME);
if (argc == 1) {
Error (NULL, 0, 1001, "Missing options", "No input options specified.");
Usage ();
return STATUS_ERROR;
}
//
// Init global data to Zero
//
memset (&mFvDataInfo, 0, sizeof (FV_INFO));
memset (&mCapDataInfo, 0, sizeof (CAP_INFO));
//
// Set the default FvGuid
//
memcpy (&mFvDataInfo.FvFileSystemGuid, &mEfiFirmwareFileSystem2Guid, sizeof (EFI_GUID));
//
// Parse command line
//
argc --;
argv ++;
if ((stricmp (argv[0], "-h") == 0) || (stricmp (argv[0], "--help") == 0)) {
Version ();
Usage ();
return STATUS_SUCCESS;
}
if (stricmp (argv[0], "--version") == 0) {
Version ();
return STATUS_SUCCESS;
}
while (argc > 0) {
if ((stricmp (argv[0], "-i") == 0) || (stricmp (argv[0], "--inputfile") == 0)) {
InfFileName = argv[1];
if (InfFileName == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Input file can't be null");
return STATUS_ERROR;
}
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-a") == 0) || (stricmp (argv[0], "--addrfile") == 0)) {
AddrFileName = argv[1];
if (AddrFileName == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Address file can't be null");
return STATUS_ERROR;
}
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-o") == 0) || (stricmp (argv[0], "--outputfile") == 0)) {
OutFileName = argv[1];
if (OutFileName == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Output file can't be null");
return STATUS_ERROR;
}
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-r") == 0) || (stricmp (argv[0], "--baseaddr") == 0)) {
Status = AsciiStringToUint64 (argv[1], FALSE, &TempNumber);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
return STATUS_ERROR;
}
mFvDataInfo.BaseAddress = TempNumber;
mFvDataInfo.BaseAddressSet = TRUE;
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-b") == 0) || (stricmp (argv[0], "--blocksize") == 0)) {
Status = AsciiStringToUint64 (argv[1], FALSE, &TempNumber);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
return STATUS_ERROR;
}
if (TempNumber == 0) {
Error (NULL, 0, 1003, "Invalid option value", "Fv block size can't be be set to zero");
return STATUS_ERROR;
}
mFvDataInfo.FvBlocks[0].Length = (UINT32) TempNumber;
DebugMsg (NULL, 0, 9, "FV Block Size", "%s = 0x%x", EFI_BLOCK_SIZE_STRING, TempNumber);
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-n") == 0) || (stricmp (argv[0], "--numberblock") == 0)) {
Status = AsciiStringToUint64 (argv[1], FALSE, &TempNumber);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
return STATUS_ERROR;
}
if (TempNumber == 0) {
Error (NULL, 0, 1003, "Invalid option value", "Fv block number can't be set to zero");
return STATUS_ERROR;
}
mFvDataInfo.FvBlocks[0].NumBlocks = (UINT32) TempNumber;
DebugMsg (NULL, 0, 9, "FV Number Block", "%s = 0x%x", EFI_NUM_BLOCKS_STRING, TempNumber);
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-f") == 0) || (stricmp (argv[0], "--ffsfile") == 0)) {
if (argv[1] == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Input Ffsfile can't be null");
return STATUS_ERROR;
}
strcpy (mFvDataInfo.FvFiles[Index], argv[1]);
DebugMsg (NULL, 0, 9, "FV component file", "the %dth name is %s", Index + 1, argv[1]);
argc -= 2;
argv += 2;
if (argc > 0) {
if ((stricmp (argv[0], "-s") == 0) || (stricmp (argv[0], "--filetakensize") == 0)) {
if (argv[1] == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Ffsfile Size can't be null");
return STATUS_ERROR;
}
Status = AsciiStringToUint64 (argv[1], FALSE, &TempNumber);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
return STATUS_ERROR;
}
mFvDataInfo.SizeofFvFiles[Index] = TempNumber;
DebugMsg (NULL, 0, 9, "FV component file size", "the %dth size is %s", Index + 1, argv[1]);
argc -= 2;
argv += 2;
}
}
Index ++;
continue;
}
if ((stricmp (argv[0], "-s") == 0) || (stricmp (argv[0], "--filetakensize") == 0)) {
Error (NULL, 0, 1003, "Invalid option", "It must be specified together with -f option to specify the file size.");
return STATUS_ERROR;
}
if ((stricmp (argv[0], "-c") == 0) || (stricmp (argv[0], "--capsule") == 0)) {
CapsuleFlag = TRUE;
argc --;
argv ++;
continue;
}
if (stricmp (argv[0], "--capheadsize") == 0) {
//
// Get Capsule Image Header Size
//
Status = AsciiStringToUint64 (argv[1], FALSE, &TempNumber);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
return STATUS_ERROR;
}
mCapDataInfo.HeaderSize = (UINT32) TempNumber;
DebugMsg (NULL, 0, 9, "Capsule Header size", "%s = 0x%x", EFI_CAPSULE_HEADER_SIZE_STRING, TempNumber);
argc -= 2;
argv += 2;
continue;
}
if (stricmp (argv[0], "--capflag") == 0) {
//
// Get Capsule Header
//
if (argv[1] == NULL) {
Error (NULL, 0, 1003, "Option value is not set", "%s = %s", argv[0], argv[1]);
return STATUS_ERROR;
}
if (strcmp (argv[1], "PopulateSystemTable") == 0) {
mCapDataInfo.Flags |= CAPSULE_FLAGS_PERSIST_ACROSS_RESET | CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE;
} else if (strcmp (argv[1], "PersistAcrossReset") == 0) {
mCapDataInfo.Flags |= CAPSULE_FLAGS_PERSIST_ACROSS_RESET;
} else {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
return STATUS_ERROR;
}
DebugMsg (NULL, 0, 9, "Capsule Flag", argv[1]);
argc -= 2;
argv += 2;
continue;
}
if (stricmp (argv[0], "--capguid") == 0) {
//
// Get the Capsule Guid
//
Status = StringToGuid (argv[1], &mCapDataInfo.CapGuid);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", EFI_CAPSULE_GUID_STRING, argv[1]);
return STATUS_ERROR;
}
DebugMsg (NULL, 0, 9, "Capsule Guid", "%s = %s", EFI_CAPSULE_GUID_STRING, argv[1]);
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-g") == 0) || (stricmp (argv[0], "--guid") == 0)) {
//
// Get the Capsule or Fv Guid
//
Status = StringToGuid (argv[1], &mCapDataInfo.CapGuid);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", EFI_GUID_STRING, argv[1]);
return STATUS_ERROR;
}
memcpy (&mFvDataInfo.FvFileSystemGuid, &mCapDataInfo.CapGuid, sizeof (EFI_GUID));
mFvDataInfo.FvFileSystemGuidSet = TRUE;
DebugMsg (NULL, 0, 9, "Capsule Guid", "%s = %s", EFI_CAPSULE_GUID_STRING, argv[1]);
DebugMsg (NULL, 0, 9, "FV Guid", "%s = %s", EFI_FV_FILESYSTEMGUID_STRING, argv[1]);
argc -= 2;
argv += 2;
continue;
}
if (stricmp (argv[0], "--FvNameGuid") == 0) {
//
// Get Fv Name Guid
//
Status = StringToGuid (argv[1], &mFvDataInfo.FvNameGuid);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", EFI_GUID_STRING, argv[1]);
return STATUS_ERROR;
}
mFvDataInfo.FvNameGuidSet = TRUE;
DebugMsg (NULL, 0, 9, "FV Name Guid", "%s = %s", EFI_FV_NAMEGUID_STRING, argv[1]);
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-p") == 0) || (stricmp (argv[0], "--dump") == 0)) {
DumpCapsule = TRUE;
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-m") == 0) || (stricmp (argv[0], "--map") == 0)) {
MapFileName = argv[1];
if (MapFileName == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Map file can't be null");
return STATUS_ERROR;
}
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-v") == 0) || (stricmp (argv[0], "--verbose") == 0)) {
SetPrintLevel (VERBOSE_LOG_LEVEL);
VerboseMsg ("Verbose output Mode Set!");
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-q") == 0) || (stricmp (argv[0], "--quiet") == 0)) {
SetPrintLevel (KEY_LOG_LEVEL);
KeyMsg ("Quiet output Mode Set!");
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-d") == 0) || (stricmp (argv[0], "--debug") == 0)) {
Status = AsciiStringToUint64 (argv[1], FALSE, &LogLevel);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[0], argv[1]);
return STATUS_ERROR;
}
if (LogLevel > 9) {
Error (NULL, 0, 1003, "Invalid option value", "Debug Level range is 0-9, current input level is %d", LogLevel);
return STATUS_ERROR;
}
SetPrintLevel (LogLevel);
DebugMsg (NULL, 0, 9, "Debug Mode Set", "Debug Output Mode Level %s is set!", argv[1]);
argc -= 2;
argv += 2;
continue;
}
//
// Don't recognize the parameter.
//
Error (NULL, 0, 1000, "Unknown option", "%s", argv[0]);
return STATUS_ERROR;
}
VerboseMsg ("%s tool start.", UTILITY_NAME);
//
// check input parameter, InfFileName can be NULL
//
if (InfFileName == NULL && DumpCapsule) {
Error (NULL, 0, 1001, "Missing option", "Input Capsule Image");
return STATUS_ERROR;
}
VerboseMsg ("the input FvInf or CapInf file name is %s", InfFileName);
if (!DumpCapsule && OutFileName == NULL) {
Error (NULL, 0, 1001, "Missing option", "Output File");
return STATUS_ERROR;
}
if (OutFileName != NULL) {
VerboseMsg ("the output file name is %s", OutFileName);
}
//
// Read boot and runtime address from address file
//
if (AddrFileName != NULL) {
VerboseMsg ("the input address file name is %s", AddrFileName);
Status = GetFileImage (AddrFileName, &InfFileImage, &InfFileSize);
if (EFI_ERROR (Status)) {
return STATUS_ERROR;
}
AddrMemoryFile.FileImage = InfFileImage;
AddrMemoryFile.CurrentFilePointer = InfFileImage;
AddrMemoryFile.Eof = InfFileImage + InfFileSize;
//
// Read the boot driver base address for this FV image
//
Status = FindToken (&AddrMemoryFile, OPTIONS_SECTION_STRING, EFI_FV_BOOT_DRIVER_BASE_ADDRESS_STRING, 0, ValueString);
if (Status == EFI_SUCCESS) {
//
// Get the base address
//
Status = AsciiStringToUint64 (ValueString, FALSE, &TempNumber);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 2000, "Invalid parameter", "%s = %s", EFI_FV_BOOT_DRIVER_BASE_ADDRESS_STRING, ValueString);
return STATUS_ERROR;
}
mFvDataInfo.BootBaseAddress = TempNumber;
DebugMsg (NULL, 0, 9, "Boot driver base address", "%s = %s", EFI_FV_BOOT_DRIVER_BASE_ADDRESS_STRING, ValueString);
}
//
// Read the FV runtime driver base address
//
Status = FindToken (&AddrMemoryFile, OPTIONS_SECTION_STRING, EFI_FV_RUNTIME_DRIVER_BASE_ADDRESS_STRING, 0, ValueString);
if (Status == EFI_SUCCESS) {
//
// Get the base address
//
Status = AsciiStringToUint64 (ValueString, FALSE, &TempNumber);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 2000, "Invalid parameter", "%s = %s", EFI_FV_RUNTIME_DRIVER_BASE_ADDRESS_STRING, ValueString);
return STATUS_ERROR;
}
mFvDataInfo.RuntimeBaseAddress = TempNumber;
DebugMsg (NULL, 0, 9, "Runtime driver base address", "%s = %s", EFI_FV_RUNTIME_DRIVER_BASE_ADDRESS_STRING, ValueString);
}
//
// free the allocated memory space for addr file.
//
free (InfFileImage);
InfFileImage = NULL;
InfFileSize = 0;
}
//
// Read the INF file image
//
if (InfFileName != NULL) {
Status = GetFileImage (InfFileName, &InfFileImage, &InfFileSize);
if (EFI_ERROR (Status)) {
return STATUS_ERROR;
}
}
if (DumpCapsule) {
VerboseMsg ("Dump the capsule header information for the input capsule image %s", InfFileName);
//
// Dump Capsule Image Header Information
//
CapsuleHeader = (EFI_CAPSULE_HEADER *) InfFileImage;
if (OutFileName == NULL) {
FpFile = stdout;
} else {
FpFile = fopen (OutFileName, "w");
if (FpFile == NULL) {
Error (NULL, 0, 0001, "Error opening file", OutFileName);
return STATUS_ERROR;
}
}
fprintf (FpFile, "Capsule %s Image Header Information\n", InfFileName);
fprintf (FpFile, " GUID %08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X\n",
CapsuleHeader->CapsuleGuid.Data1,
(UINT32) CapsuleHeader->CapsuleGuid.Data2,
(UINT32) CapsuleHeader->CapsuleGuid.Data3,
(UINT32) CapsuleHeader->CapsuleGuid.Data4[0],
(UINT32) CapsuleHeader->CapsuleGuid.Data4[1],
(UINT32) CapsuleHeader->CapsuleGuid.Data4[2],
(UINT32) CapsuleHeader->CapsuleGuid.Data4[3],
(UINT32) CapsuleHeader->CapsuleGuid.Data4[4],
(UINT32) CapsuleHeader->CapsuleGuid.Data4[5],
(UINT32) CapsuleHeader->CapsuleGuid.Data4[6],
(UINT32) CapsuleHeader->CapsuleGuid.Data4[7]);
fprintf (FpFile, " Header size 0x%08X\n", CapsuleHeader->HeaderSize);
fprintf (FpFile, " Flags 0x%08X\n", CapsuleHeader->Flags);
fprintf (FpFile, " Capsule image size 0x%08X\n", CapsuleHeader->CapsuleImageSize);
fclose (FpFile);
} else if (CapsuleFlag) {
VerboseMsg ("Create capsule image");
//
// Call the GenerateCapImage to generate Capsule Image
//
for (Index = 0; mFvDataInfo.FvFiles[Index][0] != '\0'; Index ++) {
strcpy (mCapDataInfo.CapFiles[Index], mFvDataInfo.FvFiles[Index]);
}
Status = GenerateCapImage (
InfFileImage,
InfFileSize,
OutFileName
);
} else {
VerboseMsg ("Create Fv image and its map file");
if (mFvDataInfo.BaseAddress != 0) {
VerboseMsg ("FvImage Rebase Address is 0x%X", mFvDataInfo.BaseAddress);
}
//
// Call the GenerateFvImage to generate Fv Image
//
Status = GenerateFvImage (
InfFileImage,
InfFileSize,
OutFileName,
MapFileName
);
}
//
// free InfFileImage memory
//
if (InfFileImage != NULL) {
free (InfFileImage);
}
//
// update boot driver address and runtime driver address in address file
//
if (Status == EFI_SUCCESS && AddrFileName != NULL) {
FpFile = fopen (AddrFileName, "w");
if (FpFile == NULL) {
Error (NULL, 0, 0001, "Error opening file", AddrFileName);
return STATUS_ERROR;
}
fprintf (FpFile, OPTIONS_SECTION_STRING);
fprintf (FpFile, "\n");
if (mFvDataInfo.BootBaseAddress != 0) {
fprintf (FpFile, EFI_FV_BOOT_DRIVER_BASE_ADDRESS_STRING);
fprintf (FpFile, " = 0x%lx\n", mFvDataInfo.BootBaseAddress);
DebugMsg (NULL, 0, 9, "Updated boot driver base address", "%s = 0x%x", EFI_FV_RUNTIME_DRIVER_BASE_ADDRESS_STRING, mFvDataInfo.BootBaseAddress);
}
if (mFvDataInfo.RuntimeBaseAddress != 0) {
fprintf (FpFile, EFI_FV_RUNTIME_DRIVER_BASE_ADDRESS_STRING);
fprintf (FpFile, " = 0x%lx\n", mFvDataInfo.RuntimeBaseAddress);
DebugMsg (NULL, 0, 9, "Updated runtime driver base address", "%s = 0x%x", EFI_FV_RUNTIME_DRIVER_BASE_ADDRESS_STRING, mFvDataInfo.RuntimeBaseAddress);
}
fclose (FpFile);
}
if (Status == EFI_SUCCESS) {
DebugMsg (NULL, 0, 9, "The Total Fv Size", "%s = 0x%x", EFI_FV_TOTAL_SIZE_STRING, mFvTotalSize);
DebugMsg (NULL, 0, 9, "The used Fv Size", "%s = 0x%x", EFI_FV_TAKEN_SIZE_STRING, mFvTakenSize);
DebugMsg (NULL, 0, 9, "The space Fv size", "%s = 0x%x", EFI_FV_SPACE_SIZE_STRING, mFvTotalSize - mFvTakenSize);
}
VerboseMsg ("%s tool done with return code is 0x%x.", UTILITY_NAME, GetUtilityStatus ());
return GetUtilityStatus ();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,421 @@
/** @file
Copyright (c) 2004 - 2008, 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:
GenFvInternalLib.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_INTERNAL_LIB_H
#define _EFI_GEN_FV_INTERNAL_LIB_H
//
// Include files
//
#include <stdlib.h>
#include <Common/UefiBaseTypes.h>
#include <Common/UefiCapsule.h>
#include <Common/PiFirmwareFile.h>
#include <Common/PiFirmwareVolume.h>
#include <Guid/PiFirmwareFileSystem.h>
#include <IndustryStandard/PeImage.h>
#include "CommonLib.h"
#include "ParseInf.h"
#include "EfiUtilityMsgs.h"
//
// Different file separater for Linux and Windows
//
#define FILE_SEP_CHAR '/'
//
// The maximum number of Pad file guid entries.
//
#define MAX_NUMBER_OF_PAD_FILE_GUIDS 1024
//
// 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_FILES_IN_CAP 1000
#define EFI_FFS_FILE_HEADER_ALIGNMENT 8
//
// INF file strings
//
#define OPTIONS_SECTION_STRING "[options]"
#define ATTRIBUTES_SECTION_STRING "[attributes]"
#define FILES_SECTION_STRING "[files]"
//
// Options section
//
#define EFI_FV_BASE_ADDRESS_STRING "EFI_BASE_ADDRESS"
#define EFI_FV_FILE_NAME_STRING "EFI_FILE_NAME"
#define EFI_NUM_BLOCKS_STRING "EFI_NUM_BLOCKS"
#define EFI_BLOCK_SIZE_STRING "EFI_BLOCK_SIZE"
#define EFI_GUID_STRING "EFI_GUID"
#define EFI_FV_FILESYSTEMGUID_STRING "EFI_FV_GUID"
#define EFI_FV_NAMEGUID_STRING "EFI_FVNAME_GUID"
#define EFI_CAPSULE_GUID_STRING "EFI_CAPSULE_GUID"
#define EFI_CAPSULE_HEADER_SIZE_STRING "EFI_CAPSULE_HEADER_SIZE"
#define EFI_CAPSULE_FLAGS_STRING "EFI_CAPSULE_FLAGS"
#define EFI_CAPSULE_VERSION_STRING "EFI_CAPSULE_VERSION"
#define EFI_FV_BOOT_DRIVER_BASE_ADDRESS_STRING "EFI_BOOT_DRIVER_BASE_ADDRESS"
#define EFI_FV_RUNTIME_DRIVER_BASE_ADDRESS_STRING "EFI_RUNTIME_DRIVER_BASE_ADDRESS"
#define EFI_FV_TOTAL_SIZE_STRING "EFI_FV_TOTAL_SIZE"
#define EFI_FV_TAKEN_SIZE_STRING "EFI_FV_TAKEN_SIZE"
#define EFI_FV_SPACE_SIZE_STRING "EFI_FV_SPACE_SIZE"
//
// Attributes section
//
#define EFI_FVB2_READ_DISABLED_CAP_STRING "EFI_READ_DISABLED_CAP"
#define EFI_FVB2_READ_ENABLED_CAP_STRING "EFI_READ_ENABLED_CAP"
#define EFI_FVB2_READ_STATUS_STRING "EFI_READ_STATUS"
#define EFI_FVB2_WRITE_DISABLED_CAP_STRING "EFI_WRITE_DISABLED_CAP"
#define EFI_FVB2_WRITE_ENABLED_CAP_STRING "EFI_WRITE_ENABLED_CAP"
#define EFI_FVB2_WRITE_STATUS_STRING "EFI_WRITE_STATUS"
#define EFI_FVB2_LOCK_CAP_STRING "EFI_LOCK_CAP"
#define EFI_FVB2_LOCK_STATUS_STRING "EFI_LOCK_STATUS"
#define EFI_FVB2_STICKY_WRITE_STRING "EFI_STICKY_WRITE"
#define EFI_FVB2_MEMORY_MAPPED_STRING "EFI_MEMORY_MAPPED"
#define EFI_FVB2_ERASE_POLARITY_STRING "EFI_ERASE_POLARITY"
#define EFI_FVB2_READ_LOCK_CAP_STRING "EFI_READ_LOCK_CAP"
#define EFI_FVB2_READ_LOCK_STATUS_STRING "EFI_READ_LOCK_STATUS"
#define EFI_FVB2_WRITE_LOCK_CAP_STRING "EFI_WRITE_LOCK_CAP"
#define EFI_FVB2_WRITE_LOCK_STATUS_STRING "EFI_WRITE_LOCK_STATUS"
#define EFI_FVB2_ALIGNMENT_1_STRING "EFI_FVB2_ALIGNMENT_1"
#define EFI_FVB2_ALIGNMENT_2_STRING "EFI_FVB2_ALIGNMENT_2"
#define EFI_FVB2_ALIGNMENT_4_STRING "EFI_FVB2_ALIGNMENT_4"
#define EFI_FVB2_ALIGNMENT_8_STRING "EFI_FVB2_ALIGNMENT_8"
#define EFI_FVB2_ALIGNMENT_16_STRING "EFI_FVB2_ALIGNMENT_16"
#define EFI_FVB2_ALIGNMENT_32_STRING "EFI_FVB2_ALIGNMENT_32"
#define EFI_FVB2_ALIGNMENT_64_STRING "EFI_FVB2_ALIGNMENT_64"
#define EFI_FVB2_ALIGNMENT_128_STRING "EFI_FVB2_ALIGNMENT_128"
#define EFI_FVB2_ALIGNMENT_256_STRING "EFI_FVB2_ALIGNMENT_256"
#define EFI_FVB2_ALIGNMENT_512_STRING "EFI_FVB2_ALIGNMENT_512"
#define EFI_FVB2_ALIGNMENT_1K_STRING "EFI_FVB2_ALIGNMENT_1K"
#define EFI_FVB2_ALIGNMENT_2K_STRING "EFI_FVB2_ALIGNMENT_2K"
#define EFI_FVB2_ALIGNMENT_4K_STRING "EFI_FVB2_ALIGNMENT_4K"
#define EFI_FVB2_ALIGNMENT_8K_STRING "EFI_FVB2_ALIGNMENT_8K"
#define EFI_FVB2_ALIGNMENT_16K_STRING "EFI_FVB2_ALIGNMENT_16K"
#define EFI_FVB2_ALIGNMENT_32K_STRING "EFI_FVB2_ALIGNMENT_32K"
#define EFI_FVB2_ALIGNMENT_64K_STRING "EFI_FVB2_ALIGNMENT_64K"
#define EFI_FVB2_ALIGNMENT_128K_STRING "EFI_FVB2_ALIGNMENT_128K"
#define EFI_FVB2_ALIGNMENT_256K_STRING "EFI_FVB2_ALIGNMENT_256K"
#define EFI_FVB2_ALIGNMNET_512K_STRING "EFI_FVB2_ALIGNMENT_512K"
#define EFI_FVB2_ALIGNMENT_1M_STRING "EFI_FVB2_ALIGNMENT_1M"
#define EFI_FVB2_ALIGNMENT_2M_STRING "EFI_FVB2_ALIGNMENT_2M"
#define EFI_FVB2_ALIGNMENT_4M_STRING "EFI_FVB2_ALIGNMENT_4M"
#define EFI_FVB2_ALIGNMENT_8M_STRING "EFI_FVB2_ALIGNMENT_8M"
#define EFI_FVB2_ALIGNMENT_16M_STRING "EFI_FVB2_ALIGNMENT_16M"
#define EFI_FVB2_ALIGNMENT_32M_STRING "EFI_FVB2_ALIGNMENT_32M"
#define EFI_FVB2_ALIGNMENT_64M_STRING "EFI_FVB2_ALIGNMENT_64M"
#define EFI_FVB2_ALIGNMENT_128M_STRING "EFI_FVB2_ALIGNMENT_128M"
#define EFI_FVB2_ALIGNMENT_256M_STRING "EFI_FVB2_ALIGNMENT_256M"
#define EFI_FVB2_ALIGNMENT_512M_STRING "EFI_FVB2_ALIGNMENT_512M"
#define EFI_FVB2_ALIGNMENT_1G_STRING "EFI_FVB2_ALIGNMENT_1G"
#define EFI_FVB2_ALIGNMENT_2G_STRING "EFI_FVB2_ALIGNMENT_2G"
//
// File sections
//
#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"
//
// VTF (Firmware Volume Top File) signatures
//
#define IA32_X64_VTF_SIGNATURE_OFFSET 0x14
#define IA32_X64_VTF0_SIGNATURE EFI_SIGNATURE_32('V','T','F',0)
//
// Defines to calculate the offset for PEI CORE entry points
//
#define IA32_PEI_CORE_ENTRY_OFFSET 0x20
//
// Defines to calculate the offset for IA32 SEC CORE entry point
//
#define IA32_SEC_CORE_ENTRY_OFFSET 0xD
//
// 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 0x100000000ULL
//
// 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
//
// Rebase File type
//
#define REBASE_XIP_FILE 0x1
#define REBASE_BOOTTIME_FILE 0x2
#define REBASE_RUNTIME_FILE 0x4
//
// Private data types
//
//
// Component information
//
typedef struct {
UINTN Size;
CHAR8 ComponentName[_MAX_PATH];
} COMPONENT_INFO;
//
// FV and capsule information holder
//
typedef struct {
BOOLEAN BaseAddressSet;
EFI_PHYSICAL_ADDRESS BaseAddress;
EFI_PHYSICAL_ADDRESS BootBaseAddress;
EFI_PHYSICAL_ADDRESS RuntimeBaseAddress;
EFI_GUID FvFileSystemGuid;
BOOLEAN FvFileSystemGuidSet;
EFI_GUID FvNameGuid;
BOOLEAN FvNameGuidSet;
UINTN Size;
EFI_FVB_ATTRIBUTES FvAttributes;
CHAR8 FvName[_MAX_PATH];
EFI_FV_BLOCK_MAP_ENTRY FvBlocks[MAX_NUMBER_OF_FV_BLOCKS];
CHAR8 FvFiles[MAX_NUMBER_OF_FILES_IN_FV][_MAX_PATH];
UINT32 SizeofFvFiles[MAX_NUMBER_OF_FILES_IN_FV];
BOOLEAN IsPiFvImage;
} FV_INFO;
typedef struct {
EFI_GUID CapGuid;
UINT32 HeaderSize;
UINT32 Flags;
CHAR8 CapName[_MAX_PATH];
CHAR8 CapFiles[MAX_NUMBER_OF_FILES_IN_CAP][_MAX_PATH];
} CAP_INFO;
#pragma pack(1)
typedef struct {
UINT64 CompAddress;
UINT32 CompSize;
UINT16 CompVersion;
UINT8 CvAndType;
UINT8 CheckSum;
} FIT_TABLE;
#pragma pack()
#define FV_DEFAULT_ATTRIBUTE 0x0004FEFF
extern FV_INFO mFvDataInfo;
extern CAP_INFO mCapDataInfo;
extern EFI_GUID mEfiFirmwareFileSystem2Guid;
extern UINT32 mFvTotalSize;
extern UINT32 mFvTakenSize;
//
// Local function prototypes
//
EFI_STATUS
ParseFvInf (
IN MEMORY_FILE *InfFile,
OUT FV_INFO *FvInfo
)
;
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.
--*/
;
EFI_STATUS
GetPe32Info (
IN UINT8 *Pe32,
OUT UINT32 *EntryPoint,
OUT UINT32 *BaseOfCode,
OUT UINT16 *MachineType
);
EFI_STATUS
ParseCapInf (
IN MEMORY_FILE *InfFile,
OUT CAP_INFO *CapInfo
);
EFI_STATUS
FindApResetVectorPosition (
IN MEMORY_FILE *FvImage,
OUT UINT8 **Pointer
);
EFI_STATUS
CalculateFvSize (
FV_INFO *FvInfoPtr
);
EFI_STATUS
FfsRebase (
IN OUT FV_INFO *FvInfo,
IN CHAR8 *FileName,
IN OUT EFI_FFS_FILE_HEADER *FfsFile,
IN UINTN XipOffset,
IN FILE *FvMapFile
);
//
// Exported function prototypes
//
EFI_STATUS
GenerateCapImage (
IN CHAR8 *InfFileImage,
IN UINTN InfFileSize,
IN CHAR8 *CapFileName
)
/*++
Routine Description:
This is the main function which will be called from application to
generate UEFI Capsule image.
Arguments:
InfFileImage Buffer containing the INF file contents.
InfFileSize Size of the contents of the InfFileImage buffer.
CapFileName Requested name for the Cap 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
GenerateFvImage (
IN CHAR8 *InfFileImage,
IN UINTN InfFileSize,
IN CHAR8 *FvFileName,
IN CHAR8 *MapFileName
)
/*++
Routine Description:
This is the main function which will be called from application to
generate Firmware Image conforms to PI spec.
Arguments:
InfFileImage Buffer containing the INF file contents.
InfFileSize Size of the contents of the InfFileImage buffer.
FvFileName Requested name for the FV file.
MapFileName Fv map file to log fv driver information.
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.
--*/
;
#endif

View File

@@ -0,0 +1,10 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = GenFv
LIBS = $(LIB_PATH)\Common.lib RpcRT4.lib
OBJECTS = GenFv.obj GenFvInternalLib.obj
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,18 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = GenFw
OBJECTS = GenFw.o
include $(MAKEROOT)/Makefiles/app.makefile
LIBS = -lCommon
ifeq ($(CYGWIN), CYGWIN)
LIBS += -L/lib/e2fsprogs -luuid
endif
ifeq ($(LINUX), Linux)
LIBS += -luuid
endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = GenFw
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = GenFw.obj
#CFLAGS = $(CFLAGS) /nodefaultlib:libc.lib
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,244 @@
/*-
* Copyright (c) 1996-1998 John D. Polstra.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/sys/elf32.h,v 1.8.14.2 2007/12/03 21:30:36 marius Exp $
*/
#ifndef _SYS_ELF32_H_
#define _SYS_ELF32_H_ 1
/*
* ELF definitions common to all 32-bit architectures.
*/
typedef UINT32 Elf32_Addr;
typedef UINT16 Elf32_Half;
typedef UINT32 Elf32_Off;
typedef INT32 Elf32_Sword;
typedef UINT32 Elf32_Word;
typedef UINT64 Elf32_Lword;
typedef Elf32_Word Elf32_Hashelt;
/* Non-standard class-dependent datatype used for abstraction. */
typedef Elf32_Word Elf32_Size;
typedef Elf32_Sword Elf32_Ssize;
/*
* ELF header.
*/
typedef struct {
unsigned char e_ident[EI_NIDENT]; /* File identification. */
Elf32_Half e_type; /* File type. */
Elf32_Half e_machine; /* Machine architecture. */
Elf32_Word e_version; /* ELF format version. */
Elf32_Addr e_entry; /* Entry point. */
Elf32_Off e_phoff; /* Program header file offset. */
Elf32_Off e_shoff; /* Section header file offset. */
Elf32_Word e_flags; /* Architecture-specific flags. */
Elf32_Half e_ehsize; /* Size of ELF header in bytes. */
Elf32_Half e_phentsize; /* Size of program header entry. */
Elf32_Half e_phnum; /* Number of program header entries. */
Elf32_Half e_shentsize; /* Size of section header entry. */
Elf32_Half e_shnum; /* Number of section header entries. */
Elf32_Half e_shstrndx; /* Section name strings section. */
} Elf32_Ehdr;
/*
* Section header.
*/
typedef struct {
Elf32_Word sh_name; /* Section name (index into the
section header string table). */
Elf32_Word sh_type; /* Section type. */
Elf32_Word sh_flags; /* Section flags. */
Elf32_Addr sh_addr; /* Address in memory image. */
Elf32_Off sh_offset; /* Offset in file. */
Elf32_Word sh_size; /* Size in bytes. */
Elf32_Word sh_link; /* Index of a related section. */
Elf32_Word sh_info; /* Depends on section type. */
Elf32_Word sh_addralign; /* Alignment in bytes. */
Elf32_Word sh_entsize; /* Size of each entry in section. */
} Elf32_Shdr;
/*
* Program header.
*/
typedef struct {
Elf32_Word p_type; /* Entry type. */
Elf32_Off p_offset; /* File offset of contents. */
Elf32_Addr p_vaddr; /* Virtual address in memory image. */
Elf32_Addr p_paddr; /* Physical address (not used). */
Elf32_Word p_filesz; /* Size of contents in file. */
Elf32_Word p_memsz; /* Size of contents in memory. */
Elf32_Word p_flags; /* Access permission flags. */
Elf32_Word p_align; /* Alignment in memory and file. */
} Elf32_Phdr;
/*
* Dynamic structure. The ".dynamic" section contains an array of them.
*/
typedef struct {
Elf32_Sword d_tag; /* Entry type. */
union {
Elf32_Word d_val; /* Integer value. */
Elf32_Addr d_ptr; /* Address value. */
} d_un;
} Elf32_Dyn;
/*
* Relocation entries.
*/
/* Relocations that don't need an addend field. */
typedef struct {
Elf32_Addr r_offset; /* Location to be relocated. */
Elf32_Word r_info; /* Relocation type and symbol index. */
} Elf32_Rel;
/* Relocations that need an addend field. */
typedef struct {
Elf32_Addr r_offset; /* Location to be relocated. */
Elf32_Word r_info; /* Relocation type and symbol index. */
Elf32_Sword r_addend; /* Addend. */
} Elf32_Rela;
/* Macros for accessing the fields of r_info. */
#define ELF32_R_SYM(info) ((info) >> 8)
#define ELF32_R_TYPE(info) ((unsigned char)(info))
/* Macro for constructing r_info from field values. */
#define ELF32_R_INFO(sym, type) (((sym) << 8) + (unsigned char)(type))
/*
* Note entry header
*/
typedef Elf_Note Elf32_Nhdr;
/*
* Move entry
*/
typedef struct {
Elf32_Lword m_value; /* symbol value */
Elf32_Word m_info; /* size + index */
Elf32_Word m_poffset; /* symbol offset */
Elf32_Half m_repeat; /* repeat count */
Elf32_Half m_stride; /* stride info */
} Elf32_Move;
/*
* The macros compose and decompose values for Move.r_info
*
* sym = ELF32_M_SYM(M.m_info)
* size = ELF32_M_SIZE(M.m_info)
* M.m_info = ELF32_M_INFO(sym, size)
*/
#define ELF32_M_SYM(info) ((info)>>8)
#define ELF32_M_SIZE(info) ((unsigned char)(info))
#define ELF32_M_INFO(sym, size) (((sym)<<8)+(unsigned char)(size))
/*
* Hardware/Software capabilities entry
*/
typedef struct {
Elf32_Word c_tag; /* how to interpret value */
union {
Elf32_Word c_val;
Elf32_Addr c_ptr;
} c_un;
} Elf32_Cap;
/*
* Symbol table entries.
*/
typedef struct {
Elf32_Word st_name; /* String table index of name. */
Elf32_Addr st_value; /* Symbol value. */
Elf32_Word st_size; /* Size of associated object. */
unsigned char st_info; /* Type and binding information. */
unsigned char st_other; /* Reserved (not used). */
Elf32_Half st_shndx; /* Section index of symbol. */
} Elf32_Sym;
/* Macros for accessing the fields of st_info. */
#define ELF32_ST_BIND(info) ((info) >> 4)
#define ELF32_ST_TYPE(info) ((info) & 0xf)
/* Macro for constructing st_info from field values. */
#define ELF32_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))
/* Macro for accessing the fields of st_other. */
#define ELF32_ST_VISIBILITY(oth) ((oth) & 0x3)
/* Structures used by Sun & GNU symbol versioning. */
typedef struct
{
Elf32_Half vd_version;
Elf32_Half vd_flags;
Elf32_Half vd_ndx;
Elf32_Half vd_cnt;
Elf32_Word vd_hash;
Elf32_Word vd_aux;
Elf32_Word vd_next;
} Elf32_Verdef;
typedef struct
{
Elf32_Word vda_name;
Elf32_Word vda_next;
} Elf32_Verdaux;
typedef struct
{
Elf32_Half vn_version;
Elf32_Half vn_cnt;
Elf32_Word vn_file;
Elf32_Word vn_aux;
Elf32_Word vn_next;
} Elf32_Verneed;
typedef struct
{
Elf32_Word vna_hash;
Elf32_Half vna_flags;
Elf32_Half vna_other;
Elf32_Word vna_name;
Elf32_Word vna_next;
} Elf32_Vernaux;
typedef Elf32_Half Elf32_Versym;
typedef struct {
Elf32_Half si_boundto; /* direct bindings - symbol bound to */
Elf32_Half si_flags; /* per symbol flags */
} Elf32_Syminfo;
#endif /* !_SYS_ELF32_H_ */

View File

@@ -0,0 +1,247 @@
/*-
* Copyright (c) 1996-1998 John D. Polstra.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/sys/elf64.h,v 1.10.14.2 2007/12/03 21:30:36 marius Exp $
*/
#ifndef _SYS_ELF64_H_
#define _SYS_ELF64_H_ 1
/*
* ELF definitions common to all 64-bit architectures.
*/
typedef UINT64 Elf64_Addr;
typedef UINT16 Elf64_Half;
typedef UINT64 Elf64_Off;
typedef INT32 Elf64_Sword;
typedef INT64 Elf64_Sxword;
typedef UINT32 Elf64_Word;
typedef UINT64 Elf64_Lword;
typedef UINT64 Elf64_Xword;
/*
* Types of dynamic symbol hash table bucket and chain elements.
*
* This is inconsistent among 64 bit architectures, so a machine dependent
* typedef is required.
*/
typedef Elf64_Word Elf64_Hashelt;
/* Non-standard class-dependent datatype used for abstraction. */
typedef Elf64_Xword Elf64_Size;
typedef Elf64_Sxword Elf64_Ssize;
/*
* ELF header.
*/
typedef struct {
unsigned char e_ident[EI_NIDENT]; /* File identification. */
Elf64_Half e_type; /* File type. */
Elf64_Half e_machine; /* Machine architecture. */
Elf64_Word e_version; /* ELF format version. */
Elf64_Addr e_entry; /* Entry point. */
Elf64_Off e_phoff; /* Program header file offset. */
Elf64_Off e_shoff; /* Section header file offset. */
Elf64_Word e_flags; /* Architecture-specific flags. */
Elf64_Half e_ehsize; /* Size of ELF header in bytes. */
Elf64_Half e_phentsize; /* Size of program header entry. */
Elf64_Half e_phnum; /* Number of program header entries. */
Elf64_Half e_shentsize; /* Size of section header entry. */
Elf64_Half e_shnum; /* Number of section header entries. */
Elf64_Half e_shstrndx; /* Section name strings section. */
} Elf64_Ehdr;
/*
* Section header.
*/
typedef struct {
Elf64_Word sh_name; /* Section name (index into the
section header string table). */
Elf64_Word sh_type; /* Section type. */
Elf64_Xword sh_flags; /* Section flags. */
Elf64_Addr sh_addr; /* Address in memory image. */
Elf64_Off sh_offset; /* Offset in file. */
Elf64_Xword sh_size; /* Size in bytes. */
Elf64_Word sh_link; /* Index of a related section. */
Elf64_Word sh_info; /* Depends on section type. */
Elf64_Xword sh_addralign; /* Alignment in bytes. */
Elf64_Xword sh_entsize; /* Size of each entry in section. */
} Elf64_Shdr;
/*
* Program header.
*/
typedef struct {
Elf64_Word p_type; /* Entry type. */
Elf64_Word p_flags; /* Access permission flags. */
Elf64_Off p_offset; /* File offset of contents. */
Elf64_Addr p_vaddr; /* Virtual address in memory image. */
Elf64_Addr p_paddr; /* Physical address (not used). */
Elf64_Xword p_filesz; /* Size of contents in file. */
Elf64_Xword p_memsz; /* Size of contents in memory. */
Elf64_Xword p_align; /* Alignment in memory and file. */
} Elf64_Phdr;
/*
* Dynamic structure. The ".dynamic" section contains an array of them.
*/
typedef struct {
Elf64_Sxword d_tag; /* Entry type. */
union {
Elf64_Xword d_val; /* Integer value. */
Elf64_Addr d_ptr; /* Address value. */
} d_un;
} Elf64_Dyn;
/*
* Relocation entries.
*/
/* Relocations that don't need an addend field. */
typedef struct {
Elf64_Addr r_offset; /* Location to be relocated. */
Elf64_Xword r_info; /* Relocation type and symbol index. */
} Elf64_Rel;
/* Relocations that need an addend field. */
typedef struct {
Elf64_Addr r_offset; /* Location to be relocated. */
Elf64_Xword r_info; /* Relocation type and symbol index. */
Elf64_Sxword r_addend; /* Addend. */
} Elf64_Rela;
/* Macros for accessing the fields of r_info. */
#define ELF64_R_SYM(info) ((info) >> 32)
#define ELF64_R_TYPE(info) ((info) & 0xffffffffL)
/* Macro for constructing r_info from field values. */
#define ELF64_R_INFO(sym, type) (((sym) << 32) + ((type) & 0xffffffffL))
#define ELF64_R_TYPE_DATA(info) (((Elf64_Xword)(info)<<32)>>40)
#define ELF64_R_TYPE_ID(info) (((Elf64_Xword)(info)<<56)>>56)
#define ELF64_R_TYPE_INFO(data, type) \
(((Elf64_Xword)(data)<<8)+(Elf64_Xword)(type))
/*
* Note entry header
*/
typedef Elf_Note Elf64_Nhdr;
/*
* Move entry
*/
typedef struct {
Elf64_Lword m_value; /* symbol value */
Elf64_Xword m_info; /* size + index */
Elf64_Xword m_poffset; /* symbol offset */
Elf64_Half m_repeat; /* repeat count */
Elf64_Half m_stride; /* stride info */
} Elf64_Move;
#define ELF64_M_SYM(info) ((info)>>8)
#define ELF64_M_SIZE(info) ((unsigned char)(info))
#define ELF64_M_INFO(sym, size) (((sym)<<8)+(unsigned char)(size))
/*
* Hardware/Software capabilities entry
*/
typedef struct {
Elf64_Xword c_tag; /* how to interpret value */
union {
Elf64_Xword c_val;
Elf64_Addr c_ptr;
} c_un;
} Elf64_Cap;
/*
* Symbol table entries.
*/
typedef struct {
Elf64_Word st_name; /* String table index of name. */
unsigned char st_info; /* Type and binding information. */
unsigned char st_other; /* Reserved (not used). */
Elf64_Half st_shndx; /* Section index of symbol. */
Elf64_Addr st_value; /* Symbol value. */
Elf64_Xword st_size; /* Size of associated object. */
} Elf64_Sym;
/* Macros for accessing the fields of st_info. */
#define ELF64_ST_BIND(info) ((info) >> 4)
#define ELF64_ST_TYPE(info) ((info) & 0xf)
/* Macro for constructing st_info from field values. */
#define ELF64_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))
/* Macro for accessing the fields of st_other. */
#define ELF64_ST_VISIBILITY(oth) ((oth) & 0x3)
/* Structures used by Sun & GNU-style symbol versioning. */
typedef struct {
Elf64_Half vd_version;
Elf64_Half vd_flags;
Elf64_Half vd_ndx;
Elf64_Half vd_cnt;
Elf64_Word vd_hash;
Elf64_Word vd_aux;
Elf64_Word vd_next;
} Elf64_Verdef;
typedef struct {
Elf64_Word vda_name;
Elf64_Word vda_next;
} Elf64_Verdaux;
typedef struct {
Elf64_Half vn_version;
Elf64_Half vn_cnt;
Elf64_Word vn_file;
Elf64_Word vn_aux;
Elf64_Word vn_next;
} Elf64_Verneed;
typedef struct {
Elf64_Word vna_hash;
Elf64_Half vna_flags;
Elf64_Half vna_other;
Elf64_Word vna_name;
Elf64_Word vna_next;
} Elf64_Vernaux;
typedef Elf64_Half Elf64_Versym;
typedef struct {
Elf64_Half si_boundto; /* direct bindings - symbol bound to */
Elf64_Half si_flags; /* per symbol flags */
} Elf64_Syminfo;
#endif /* !_SYS_ELF64_H_ */

View File

@@ -0,0 +1,872 @@
/*-
* Copyright (c) 1998 John D. Polstra.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/sys/elf_common.h,v 1.15.8.2 2007/12/03 21:30:36 marius Exp $
*/
#ifndef _SYS_ELF_COMMON_H_
#define _SYS_ELF_COMMON_H_ 1
/*
* ELF definitions that are independent of architecture or word size.
*/
/*
* Note header. The ".note" section contains an array of notes. Each
* begins with this header, aligned to a word boundary. Immediately
* following the note header is n_namesz bytes of name, padded to the
* next word boundary. Then comes n_descsz bytes of descriptor, again
* padded to a word boundary. The values of n_namesz and n_descsz do
* not include the padding.
*/
typedef struct {
UINT32 n_namesz; /* Length of name. */
UINT32 n_descsz; /* Length of descriptor. */
UINT32 n_type; /* Type of this note. */
} Elf_Note;
/* Indexes into the e_ident array. Keep synced with
http://www.sco.com/developers/gabi/latest/ch4.eheader.html */
#define EI_MAG0 0 /* Magic number, byte 0. */
#define EI_MAG1 1 /* Magic number, byte 1. */
#define EI_MAG2 2 /* Magic number, byte 2. */
#define EI_MAG3 3 /* Magic number, byte 3. */
#define EI_CLASS 4 /* Class of machine. */
#define EI_DATA 5 /* Data format. */
#define EI_VERSION 6 /* ELF format version. */
#define EI_OSABI 7 /* Operating system / ABI identification */
#define EI_ABIVERSION 8 /* ABI version */
#define OLD_EI_BRAND 8 /* Start of architecture identification. */
#define EI_PAD 9 /* Start of padding (per SVR4 ABI). */
#define EI_NIDENT 16 /* Size of e_ident array. */
/* Values for the magic number bytes. */
#define ELFMAG0 0x7f
#define ELFMAG1 'E'
#define ELFMAG2 'L'
#define ELFMAG3 'F'
#define ELFMAG "\177ELF" /* magic string */
#define SELFMAG 4 /* magic string size */
/* Values for e_ident[EI_VERSION] and e_version. */
#define EV_NONE 0
#define EV_CURRENT 1
/* Values for e_ident[EI_CLASS]. */
#define ELFCLASSNONE 0 /* Unknown class. */
#define ELFCLASS32 1 /* 32-bit architecture. */
#define ELFCLASS64 2 /* 64-bit architecture. */
/* Values for e_ident[EI_DATA]. */
#define ELFDATANONE 0 /* Unknown data format. */
#define ELFDATA2LSB 1 /* 2's complement little-endian. */
#define ELFDATA2MSB 2 /* 2's complement big-endian. */
/* Values for e_ident[EI_OSABI]. */
#define ELFOSABI_NONE 0 /* UNIX System V ABI */
#define ELFOSABI_HPUX 1 /* HP-UX operating system */
#define ELFOSABI_NETBSD 2 /* NetBSD */
#define ELFOSABI_LINUX 3 /* GNU/Linux */
#define ELFOSABI_HURD 4 /* GNU/Hurd */
#define ELFOSABI_86OPEN 5 /* 86Open common IA32 ABI */
#define ELFOSABI_SOLARIS 6 /* Solaris */
#define ELFOSABI_AIX 7 /* AIX */
#define ELFOSABI_IRIX 8 /* IRIX */
#define ELFOSABI_FREEBSD 9 /* FreeBSD */
#define ELFOSABI_TRU64 10 /* TRU64 UNIX */
#define ELFOSABI_MODESTO 11 /* Novell Modesto */
#define ELFOSABI_OPENBSD 12 /* OpenBSD */
#define ELFOSABI_OPENVMS 13 /* Open VMS */
#define ELFOSABI_NSK 14 /* HP Non-Stop Kernel */
#define ELFOSABI_ARM 97 /* ARM */
#define ELFOSABI_STANDALONE 255 /* Standalone (embedded) application */
#define ELFOSABI_SYSV ELFOSABI_NONE /* symbol used in old spec */
#define ELFOSABI_MONTEREY ELFOSABI_AIX /* Monterey */
/* e_ident */
#define IS_ELF(ehdr) ((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \
(ehdr).e_ident[EI_MAG1] == ELFMAG1 && \
(ehdr).e_ident[EI_MAG2] == ELFMAG2 && \
(ehdr).e_ident[EI_MAG3] == ELFMAG3)
/* Values for e_type. */
#define ET_NONE 0 /* Unknown type. */
#define ET_REL 1 /* Relocatable. */
#define ET_EXEC 2 /* Executable. */
#define ET_DYN 3 /* Shared object. */
#define ET_CORE 4 /* Core file. */
#define ET_LOOS 0xfe00 /* First operating system specific. */
#define ET_HIOS 0xfeff /* Last operating system-specific. */
#define ET_LOPROC 0xff00 /* First processor-specific. */
#define ET_HIPROC 0xffff /* Last processor-specific. */
/* Values for e_machine. */
#define EM_NONE 0 /* Unknown machine. */
#define EM_M32 1 /* AT&T WE32100. */
#define EM_SPARC 2 /* Sun SPARC. */
#define EM_386 3 /* Intel i386. */
#define EM_68K 4 /* Motorola 68000. */
#define EM_88K 5 /* Motorola 88000. */
#define EM_860 7 /* Intel i860. */
#define EM_MIPS 8 /* MIPS R3000 Big-Endian only. */
#define EM_S370 9 /* IBM System/370. */
#define EM_MIPS_RS3_LE 10 /* MIPS R3000 Little-Endian. */
#define EM_PARISC 15 /* HP PA-RISC. */
#define EM_VPP500 17 /* Fujitsu VPP500. */
#define EM_SPARC32PLUS 18 /* SPARC v8plus. */
#define EM_960 19 /* Intel 80960. */
#define EM_PPC 20 /* PowerPC 32-bit. */
#define EM_PPC64 21 /* PowerPC 64-bit. */
#define EM_S390 22 /* IBM System/390. */
#define EM_V800 36 /* NEC V800. */
#define EM_FR20 37 /* Fujitsu FR20. */
#define EM_RH32 38 /* TRW RH-32. */
#define EM_RCE 39 /* Motorola RCE. */
#define EM_ARM 40 /* ARM. */
#define EM_SH 42 /* Hitachi SH. */
#define EM_SPARCV9 43 /* SPARC v9 64-bit. */
#define EM_TRICORE 44 /* Siemens TriCore embedded processor. */
#define EM_ARC 45 /* Argonaut RISC Core. */
#define EM_H8_300 46 /* Hitachi H8/300. */
#define EM_H8_300H 47 /* Hitachi H8/300H. */
#define EM_H8S 48 /* Hitachi H8S. */
#define EM_H8_500 49 /* Hitachi H8/500. */
#define EM_IA_64 50 /* Intel IA-64 Processor. */
#define EM_MIPS_X 51 /* Stanford MIPS-X. */
#define EM_COLDFIRE 52 /* Motorola ColdFire. */
#define EM_68HC12 53 /* Motorola M68HC12. */
#define EM_MMA 54 /* Fujitsu MMA. */
#define EM_PCP 55 /* Siemens PCP. */
#define EM_NCPU 56 /* Sony nCPU. */
#define EM_NDR1 57 /* Denso NDR1 microprocessor. */
#define EM_STARCORE 58 /* Motorola Star*Core processor. */
#define EM_ME16 59 /* Toyota ME16 processor. */
#define EM_ST100 60 /* STMicroelectronics ST100 processor. */
#define EM_TINYJ 61 /* Advanced Logic Corp. TinyJ processor. */
#define EM_X86_64 62 /* Advanced Micro Devices x86-64 */
#define EM_AMD64 EM_X86_64 /* Advanced Micro Devices x86-64 (compat) */
/* Non-standard or deprecated. */
#define EM_486 6 /* Intel i486. */
#define EM_MIPS_RS4_BE 10 /* MIPS R4000 Big-Endian */
#define EM_ALPHA_STD 41 /* Digital Alpha (standard value). */
#define EM_ALPHA 0x9026 /* Alpha (written in the absence of an ABI) */
/* Special section indexes. */
#define SHN_UNDEF 0 /* Undefined, missing, irrelevant. */
#define SHN_LORESERVE 0xff00 /* First of reserved range. */
#define SHN_LOPROC 0xff00 /* First processor-specific. */
#define SHN_HIPROC 0xff1f /* Last processor-specific. */
#define SHN_LOOS 0xff20 /* First operating system-specific. */
#define SHN_HIOS 0xff3f /* Last operating system-specific. */
#define SHN_ABS 0xfff1 /* Absolute values. */
#define SHN_COMMON 0xfff2 /* Common data. */
#define SHN_XINDEX 0xffff /* Escape -- index stored elsewhere. */
#define SHN_HIRESERVE 0xffff /* Last of reserved range. */
/* sh_type */
#define SHT_NULL 0 /* inactive */
#define SHT_PROGBITS 1 /* program defined information */
#define SHT_SYMTAB 2 /* symbol table section */
#define SHT_STRTAB 3 /* string table section */
#define SHT_RELA 4 /* relocation section with addends */
#define SHT_HASH 5 /* symbol hash table section */
#define SHT_DYNAMIC 6 /* dynamic section */
#define SHT_NOTE 7 /* note section */
#define SHT_NOBITS 8 /* no space section */
#define SHT_REL 9 /* relocation section - no addends */
#define SHT_SHLIB 10 /* reserved - purpose unknown */
#define SHT_DYNSYM 11 /* dynamic symbol table section */
#define SHT_INIT_ARRAY 14 /* Initialization function pointers. */
#define SHT_FINI_ARRAY 15 /* Termination function pointers. */
#define SHT_PREINIT_ARRAY 16 /* Pre-initialization function ptrs. */
#define SHT_GROUP 17 /* Section group. */
#define SHT_SYMTAB_SHNDX 18 /* Section indexes (see SHN_XINDEX). */
#define SHT_LOOS 0x60000000 /* First of OS specific semantics */
#define SHT_LOSUNW 0x6ffffff4
#define SHT_SUNW_dof 0x6ffffff4
#define SHT_SUNW_cap 0x6ffffff5
#define SHT_SUNW_SIGNATURE 0x6ffffff6
#define SHT_SUNW_ANNOTATE 0x6ffffff7
#define SHT_SUNW_DEBUGSTR 0x6ffffff8
#define SHT_SUNW_DEBUG 0x6ffffff9
#define SHT_SUNW_move 0x6ffffffa
#define SHT_SUNW_COMDAT 0x6ffffffb
#define SHT_SUNW_syminfo 0x6ffffffc
#define SHT_SUNW_verdef 0x6ffffffd
#define SHT_GNU_verdef 0x6ffffffd /* Symbol versions provided */
#define SHT_SUNW_verneed 0x6ffffffe
#define SHT_GNU_verneed 0x6ffffffe /* Symbol versions required */
#define SHT_SUNW_versym 0x6fffffff
#define SHT_GNU_versym 0x6fffffff /* Symbol version table */
#define SHT_HISUNW 0x6fffffff
#define SHT_HIOS 0x6fffffff /* Last of OS specific semantics */
#define SHT_LOPROC 0x70000000 /* reserved range for processor */
#define SHT_AMD64_UNWIND 0x70000001 /* unwind information */
#define SHT_HIPROC 0x7fffffff /* specific section header types */
#define SHT_LOUSER 0x80000000 /* reserved range for application */
#define SHT_HIUSER 0xffffffff /* specific indexes */
/* Flags for sh_flags. */
#define SHF_WRITE 0x1 /* Section contains writable data. */
#define SHF_ALLOC 0x2 /* Section occupies memory. */
#define SHF_EXECINSTR 0x4 /* Section contains instructions. */
#define SHF_MERGE 0x10 /* Section may be merged. */
#define SHF_STRINGS 0x20 /* Section contains strings. */
#define SHF_INFO_LINK 0x40 /* sh_info holds section index. */
#define SHF_LINK_ORDER 0x80 /* Special ordering requirements. */
#define SHF_OS_NONCONFORMING 0x100 /* OS-specific processing required. */
#define SHF_GROUP 0x200 /* Member of section group. */
#define SHF_TLS 0x400 /* Section contains TLS data. */
#define SHF_MASKOS 0x0ff00000 /* OS-specific semantics. */
#define SHF_MASKPROC 0xf0000000 /* Processor-specific semantics. */
/* Values for p_type. */
#define PT_NULL 0 /* Unused entry. */
#define PT_LOAD 1 /* Loadable segment. */
#define PT_DYNAMIC 2 /* Dynamic linking information segment. */
#define PT_INTERP 3 /* Pathname of interpreter. */
#define PT_NOTE 4 /* Auxiliary information. */
#define PT_SHLIB 5 /* Reserved (not used). */
#define PT_PHDR 6 /* Location of program header itself. */
#define PT_TLS 7 /* Thread local storage segment */
#define PT_LOOS 0x60000000 /* First OS-specific. */
#define PT_SUNW_UNWIND 0x6464e550 /* amd64 UNWIND program header */
#define PT_GNU_EH_FRAME 0x6474e550
#define PT_LOSUNW 0x6ffffffa
#define PT_SUNWBSS 0x6ffffffa /* Sun Specific segment */
#define PT_SUNWSTACK 0x6ffffffb /* describes the stack segment */
#define PT_SUNWDTRACE 0x6ffffffc /* private */
#define PT_SUNWCAP 0x6ffffffd /* hard/soft capabilities segment */
#define PT_HISUNW 0x6fffffff
#define PT_HIOS 0x6fffffff /* Last OS-specific. */
#define PT_LOPROC 0x70000000 /* First processor-specific type. */
#define PT_HIPROC 0x7fffffff /* Last processor-specific type. */
/* Values for p_flags. */
#define PF_X 0x1 /* Executable. */
#define PF_W 0x2 /* Writable. */
#define PF_R 0x4 /* Readable. */
#define PF_MASKOS 0x0ff00000 /* Operating system-specific. */
#define PF_MASKPROC 0xf0000000 /* Processor-specific. */
/* Extended program header index. */
#define PN_XNUM 0xffff
/* Values for d_tag. */
#define DT_NULL 0 /* Terminating entry. */
#define DT_NEEDED 1 /* String table offset of a needed shared
library. */
#define DT_PLTRELSZ 2 /* Total size in bytes of PLT relocations. */
#define DT_PLTGOT 3 /* Processor-dependent address. */
#define DT_HASH 4 /* Address of symbol hash table. */
#define DT_STRTAB 5 /* Address of string table. */
#define DT_SYMTAB 6 /* Address of symbol table. */
#define DT_RELA 7 /* Address of ElfNN_Rela relocations. */
#define DT_RELASZ 8 /* Total size of ElfNN_Rela relocations. */
#define DT_RELAENT 9 /* Size of each ElfNN_Rela relocation entry. */
#define DT_STRSZ 10 /* Size of string table. */
#define DT_SYMENT 11 /* Size of each symbol table entry. */
#define DT_INIT 12 /* Address of initialization function. */
#define DT_FINI 13 /* Address of finalization function. */
#define DT_SONAME 14 /* String table offset of shared object
name. */
#define DT_RPATH 15 /* String table offset of library path. [sup] */
#define DT_SYMBOLIC 16 /* Indicates "symbolic" linking. [sup] */
#define DT_REL 17 /* Address of ElfNN_Rel relocations. */
#define DT_RELSZ 18 /* Total size of ElfNN_Rel relocations. */
#define DT_RELENT 19 /* Size of each ElfNN_Rel relocation. */
#define DT_PLTREL 20 /* Type of relocation used for PLT. */
#define DT_DEBUG 21 /* Reserved (not used). */
#define DT_TEXTREL 22 /* Indicates there may be relocations in
non-writable segments. [sup] */
#define DT_JMPREL 23 /* Address of PLT relocations. */
#define DT_BIND_NOW 24 /* [sup] */
#define DT_INIT_ARRAY 25 /* Address of the array of pointers to
initialization functions */
#define DT_FINI_ARRAY 26 /* Address of the array of pointers to
termination functions */
#define DT_INIT_ARRAYSZ 27 /* Size in bytes of the array of
initialization functions. */
#define DT_FINI_ARRAYSZ 28 /* Size in bytes of the array of
terminationfunctions. */
#define DT_RUNPATH 29 /* String table offset of a null-terminated
library search path string. */
#define DT_FLAGS 30 /* Object specific flag values. */
#define DT_ENCODING 32 /* Values greater than or equal to DT_ENCODING
and less than DT_LOOS follow the rules for
the interpretation of the d_un union
as follows: even == 'd_ptr', even == 'd_val'
or none */
#define DT_PREINIT_ARRAY 32 /* Address of the array of pointers to
pre-initialization functions. */
#define DT_PREINIT_ARRAYSZ 33 /* Size in bytes of the array of
pre-initialization functions. */
#define DT_MAXPOSTAGS 34 /* number of positive tags */
#define DT_LOOS 0x6000000d /* First OS-specific */
#define DT_SUNW_AUXILIARY 0x6000000d /* symbol auxiliary name */
#define DT_SUNW_RTLDINF 0x6000000e /* ld.so.1 info (private) */
#define DT_SUNW_FILTER 0x6000000f /* symbol filter name */
#define DT_SUNW_CAP 0x60000010 /* hardware/software */
#define DT_HIOS 0x6ffff000 /* Last OS-specific */
/*
* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the
* Dyn.d_un.d_val field of the Elf*_Dyn structure.
*/
#define DT_VALRNGLO 0x6ffffd00
#define DT_CHECKSUM 0x6ffffdf8 /* elf checksum */
#define DT_PLTPADSZ 0x6ffffdf9 /* pltpadding size */
#define DT_MOVEENT 0x6ffffdfa /* move table entry size */
#define DT_MOVESZ 0x6ffffdfb /* move table size */
#define DT_FEATURE_1 0x6ffffdfc /* feature holder */
#define DT_POSFLAG_1 0x6ffffdfd /* flags for DT_* entries, effecting */
/* the following DT_* entry. */
/* See DF_P1_* definitions */
#define DT_SYMINSZ 0x6ffffdfe /* syminfo table size (in bytes) */
#define DT_SYMINENT 0x6ffffdff /* syminfo entry size (in bytes) */
#define DT_VALRNGHI 0x6ffffdff
/*
* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the
* Dyn.d_un.d_ptr field of the Elf*_Dyn structure.
*
* If any adjustment is made to the ELF object after it has been
* built, these entries will need to be adjusted.
*/
#define DT_ADDRRNGLO 0x6ffffe00
#define DT_CONFIG 0x6ffffefa /* configuration information */
#define DT_DEPAUDIT 0x6ffffefb /* dependency auditing */
#define DT_AUDIT 0x6ffffefc /* object auditing */
#define DT_PLTPAD 0x6ffffefd /* pltpadding (sparcv9) */
#define DT_MOVETAB 0x6ffffefe /* move table */
#define DT_SYMINFO 0x6ffffeff /* syminfo table */
#define DT_ADDRRNGHI 0x6ffffeff
#define DT_VERSYM 0x6ffffff0 /* Address of versym section. */
#define DT_RELACOUNT 0x6ffffff9 /* number of RELATIVE relocations */
#define DT_RELCOUNT 0x6ffffffa /* number of RELATIVE relocations */
#define DT_FLAGS_1 0x6ffffffb /* state flags - see DF_1_* defs */
#define DT_VERDEF 0x6ffffffc /* Address of verdef section. */
#define DT_VERDEFNUM 0x6ffffffd /* Number of elems in verdef section */
#define DT_VERNEED 0x6ffffffe /* Address of verneed section. */
#define DT_VERNEEDNUM 0x6fffffff /* Number of elems in verneed section */
#define DT_LOPROC 0x70000000 /* First processor-specific type. */
#define DT_DEPRECATED_SPARC_REGISTER 0x7000001
#define DT_AUXILIARY 0x7ffffffd /* shared library auxiliary name */
#define DT_USED 0x7ffffffe /* ignored - same as needed */
#define DT_FILTER 0x7fffffff /* shared library filter name */
#define DT_HIPROC 0x7fffffff /* Last processor-specific type. */
/* Values for DT_FLAGS */
#define DF_ORIGIN 0x0001 /* Indicates that the object being loaded may
make reference to the $ORIGIN substitution
string */
#define DF_SYMBOLIC 0x0002 /* Indicates "symbolic" linking. */
#define DF_TEXTREL 0x0004 /* Indicates there may be relocations in
non-writable segments. */
#define DF_BIND_NOW 0x0008 /* Indicates that the dynamic linker should
process all relocations for the object
containing this entry before transferring
control to the program. */
#define DF_STATIC_TLS 0x0010 /* Indicates that the shared object or
executable contains code using a static
thread-local storage scheme. */
/* Values for n_type. Used in core files. */
#define NT_PRSTATUS 1 /* Process status. */
#define NT_FPREGSET 2 /* Floating point registers. */
#define NT_PRPSINFO 3 /* Process state info. */
/* Symbol Binding - ELFNN_ST_BIND - st_info */
#define STB_LOCAL 0 /* Local symbol */
#define STB_GLOBAL 1 /* Global symbol */
#define STB_WEAK 2 /* like global - lower precedence */
#define STB_LOOS 10 /* Reserved range for operating system */
#define STB_HIOS 12 /* specific semantics. */
#define STB_LOPROC 13 /* reserved range for processor */
#define STB_HIPROC 15 /* specific semantics. */
/* Symbol type - ELFNN_ST_TYPE - st_info */
#define STT_NOTYPE 0 /* Unspecified type. */
#define STT_OBJECT 1 /* Data object. */
#define STT_FUNC 2 /* Function. */
#define STT_SECTION 3 /* Section. */
#define STT_FILE 4 /* Source file. */
#define STT_COMMON 5 /* Uninitialized common block. */
#define STT_TLS 6 /* TLS object. */
#define STT_NUM 7
#define STT_LOOS 10 /* Reserved range for operating system */
#define STT_HIOS 12 /* specific semantics. */
#define STT_LOPROC 13 /* reserved range for processor */
#define STT_HIPROC 15 /* specific semantics. */
/* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */
#define STV_DEFAULT 0x0 /* Default visibility (see binding). */
#define STV_INTERNAL 0x1 /* Special meaning in relocatable objects. */
#define STV_HIDDEN 0x2 /* Not visible. */
#define STV_PROTECTED 0x3 /* Visible but not preemptible. */
/* Special symbol table indexes. */
#define STN_UNDEF 0 /* Undefined symbol index. */
/* Symbol versioning flags. */
#define VER_DEF_CURRENT 1
#define VER_DEF_IDX(x) VER_NDX(x)
#define VER_FLG_BASE 0x01
#define VER_FLG_WEAK 0x02
#define VER_NEED_CURRENT 1
#define VER_NEED_WEAK (1u << 15)
#define VER_NEED_HIDDEN VER_NDX_HIDDEN
#define VER_NEED_IDX(x) VER_NDX(x)
#define VER_NDX_LOCAL 0
#define VER_NDX_GLOBAL 1
#define VER_NDX_GIVEN 2
#define VER_NDX_HIDDEN (1u << 15)
#define VER_NDX(x) ((x) & ~(1u << 15))
#define CA_SUNW_NULL 0
#define CA_SUNW_HW_1 1 /* first hardware capabilities entry */
#define CA_SUNW_SF_1 2 /* first software capabilities entry */
/*
* Syminfo flag values
*/
#define SYMINFO_FLG_DIRECT 0x0001 /* symbol ref has direct association */
/* to object containing defn. */
#define SYMINFO_FLG_PASSTHRU 0x0002 /* ignored - see SYMINFO_FLG_FILTER */
#define SYMINFO_FLG_COPY 0x0004 /* symbol is a copy-reloc */
#define SYMINFO_FLG_LAZYLOAD 0x0008 /* object containing defn should be */
/* lazily-loaded */
#define SYMINFO_FLG_DIRECTBIND 0x0010 /* ref should be bound directly to */
/* object containing defn. */
#define SYMINFO_FLG_NOEXTDIRECT 0x0020 /* don't let an external reference */
/* directly bind to this symbol */
#define SYMINFO_FLG_FILTER 0x0002 /* symbol ref is associated to a */
#define SYMINFO_FLG_AUXILIARY 0x0040 /* standard or auxiliary filter */
/*
* Syminfo.si_boundto values.
*/
#define SYMINFO_BT_SELF 0xffff /* symbol bound to self */
#define SYMINFO_BT_PARENT 0xfffe /* symbol bound to parent */
#define SYMINFO_BT_NONE 0xfffd /* no special symbol binding */
#define SYMINFO_BT_EXTERN 0xfffc /* symbol defined as external */
#define SYMINFO_BT_LOWRESERVE 0xff00 /* beginning of reserved entries */
/*
* Syminfo version values.
*/
#define SYMINFO_NONE 0 /* Syminfo version */
#define SYMINFO_CURRENT 1
#define SYMINFO_NUM 2
/*
* Relocation types.
*
* All machine architectures are defined here to allow tools on one to
* handle others.
*/
#define R_386_NONE 0 /* No relocation. */
#define R_386_32 1 /* Add symbol value. */
#define R_386_PC32 2 /* Add PC-relative symbol value. */
#define R_386_GOT32 3 /* Add PC-relative GOT offset. */
#define R_386_PLT32 4 /* Add PC-relative PLT offset. */
#define R_386_COPY 5 /* Copy data from shared object. */
#define R_386_GLOB_DAT 6 /* Set GOT entry to data address. */
#define R_386_JMP_SLOT 7 /* Set GOT entry to code address. */
#define R_386_RELATIVE 8 /* Add load address of shared object. */
#define R_386_GOTOFF 9 /* Add GOT-relative symbol address. */
#define R_386_GOTPC 10 /* Add PC-relative GOT table address. */
#define R_386_TLS_TPOFF 14 /* Negative offset in static TLS block */
#define R_386_TLS_IE 15 /* Absolute address of GOT for -ve static TLS */
#define R_386_TLS_GOTIE 16 /* GOT entry for negative static TLS block */
#define R_386_TLS_LE 17 /* Negative offset relative to static TLS */
#define R_386_TLS_GD 18 /* 32 bit offset to GOT (index,off) pair */
#define R_386_TLS_LDM 19 /* 32 bit offset to GOT (index,zero) pair */
#define R_386_TLS_GD_32 24 /* 32 bit offset to GOT (index,off) pair */
#define R_386_TLS_GD_PUSH 25 /* pushl instruction for Sun ABI GD sequence */
#define R_386_TLS_GD_CALL 26 /* call instruction for Sun ABI GD sequence */
#define R_386_TLS_GD_POP 27 /* popl instruction for Sun ABI GD sequence */
#define R_386_TLS_LDM_32 28 /* 32 bit offset to GOT (index,zero) pair */
#define R_386_TLS_LDM_PUSH 29 /* pushl instruction for Sun ABI LD sequence */
#define R_386_TLS_LDM_CALL 30 /* call instruction for Sun ABI LD sequence */
#define R_386_TLS_LDM_POP 31 /* popl instruction for Sun ABI LD sequence */
#define R_386_TLS_LDO_32 32 /* 32 bit offset from start of TLS block */
#define R_386_TLS_IE_32 33 /* 32 bit offset to GOT static TLS offset entry */
#define R_386_TLS_LE_32 34 /* 32 bit offset within static TLS block */
#define R_386_TLS_DTPMOD32 35 /* GOT entry containing TLS index */
#define R_386_TLS_DTPOFF32 36 /* GOT entry containing TLS offset */
#define R_386_TLS_TPOFF32 37 /* GOT entry of -ve static TLS offset */
#define R_ALPHA_NONE 0 /* No reloc */
#define R_ALPHA_REFLONG 1 /* Direct 32 bit */
#define R_ALPHA_REFQUAD 2 /* Direct 64 bit */
#define R_ALPHA_GPREL32 3 /* GP relative 32 bit */
#define R_ALPHA_LITERAL 4 /* GP relative 16 bit w/optimization */
#define R_ALPHA_LITUSE 5 /* Optimization hint for LITERAL */
#define R_ALPHA_GPDISP 6 /* Add displacement to GP */
#define R_ALPHA_BRADDR 7 /* PC+4 relative 23 bit shifted */
#define R_ALPHA_HINT 8 /* PC+4 relative 16 bit shifted */
#define R_ALPHA_SREL16 9 /* PC relative 16 bit */
#define R_ALPHA_SREL32 10 /* PC relative 32 bit */
#define R_ALPHA_SREL64 11 /* PC relative 64 bit */
#define R_ALPHA_OP_PUSH 12 /* OP stack push */
#define R_ALPHA_OP_STORE 13 /* OP stack pop and store */
#define R_ALPHA_OP_PSUB 14 /* OP stack subtract */
#define R_ALPHA_OP_PRSHIFT 15 /* OP stack right shift */
#define R_ALPHA_GPVALUE 16
#define R_ALPHA_GPRELHIGH 17
#define R_ALPHA_GPRELLOW 18
#define R_ALPHA_IMMED_GP_16 19
#define R_ALPHA_IMMED_GP_HI32 20
#define R_ALPHA_IMMED_SCN_HI32 21
#define R_ALPHA_IMMED_BR_HI32 22
#define R_ALPHA_IMMED_LO32 23
#define R_ALPHA_COPY 24 /* Copy symbol at runtime */
#define R_ALPHA_GLOB_DAT 25 /* Create GOT entry */
#define R_ALPHA_JMP_SLOT 26 /* Create PLT entry */
#define R_ALPHA_RELATIVE 27 /* Adjust by program base */
#define R_ARM_NONE 0 /* No relocation. */
#define R_ARM_PC24 1
#define R_ARM_ABS32 2
#define R_ARM_REL32 3
#define R_ARM_PC13 4
#define R_ARM_ABS16 5
#define R_ARM_ABS12 6
#define R_ARM_THM_ABS5 7
#define R_ARM_ABS8 8
#define R_ARM_SBREL32 9
#define R_ARM_THM_PC22 10
#define R_ARM_THM_PC8 11
#define R_ARM_AMP_VCALL9 12
#define R_ARM_SWI24 13
#define R_ARM_THM_SWI8 14
#define R_ARM_XPC25 15
#define R_ARM_THM_XPC22 16
#define R_ARM_COPY 20 /* Copy data from shared object. */
#define R_ARM_GLOB_DAT 21 /* Set GOT entry to data address. */
#define R_ARM_JUMP_SLOT 22 /* Set GOT entry to code address. */
#define R_ARM_RELATIVE 23 /* Add load address of shared object. */
#define R_ARM_GOTOFF 24 /* Add GOT-relative symbol address. */
#define R_ARM_GOTPC 25 /* Add PC-relative GOT table address. */
#define R_ARM_GOT32 26 /* Add PC-relative GOT offset. */
#define R_ARM_PLT32 27 /* Add PC-relative PLT offset. */
#define R_ARM_GNU_VTENTRY 100
#define R_ARM_GNU_VTINHERIT 101
#define R_ARM_RSBREL32 250
#define R_ARM_THM_RPC22 251
#define R_ARM_RREL32 252
#define R_ARM_RABS32 253
#define R_ARM_RPC24 254
#define R_ARM_RBASE 255
/* Name Value Field Calculation */
#define R_IA_64_NONE 0 /* None */
#define R_IA_64_IMM14 0x21 /* immediate14 S + A */
#define R_IA_64_IMM22 0x22 /* immediate22 S + A */
#define R_IA_64_IMM64 0x23 /* immediate64 S + A */
#define R_IA_64_DIR32MSB 0x24 /* word32 MSB S + A */
#define R_IA_64_DIR32LSB 0x25 /* word32 LSB S + A */
#define R_IA_64_DIR64MSB 0x26 /* word64 MSB S + A */
#define R_IA_64_DIR64LSB 0x27 /* word64 LSB S + A */
#define R_IA_64_GPREL22 0x2a /* immediate22 @gprel(S + A) */
#define R_IA_64_GPREL64I 0x2b /* immediate64 @gprel(S + A) */
#define R_IA_64_GPREL32MSB 0x2c /* word32 MSB @gprel(S + A) */
#define R_IA_64_GPREL32LSB 0x2d /* word32 LSB @gprel(S + A) */
#define R_IA_64_GPREL64MSB 0x2e /* word64 MSB @gprel(S + A) */
#define R_IA_64_GPREL64LSB 0x2f /* word64 LSB @gprel(S + A) */
#define R_IA_64_LTOFF22 0x32 /* immediate22 @ltoff(S + A) */
#define R_IA_64_LTOFF64I 0x33 /* immediate64 @ltoff(S + A) */
#define R_IA_64_PLTOFF22 0x3a /* immediate22 @pltoff(S + A) */
#define R_IA_64_PLTOFF64I 0x3b /* immediate64 @pltoff(S + A) */
#define R_IA_64_PLTOFF64MSB 0x3e /* word64 MSB @pltoff(S + A) */
#define R_IA_64_PLTOFF64LSB 0x3f /* word64 LSB @pltoff(S + A) */
#define R_IA_64_FPTR64I 0x43 /* immediate64 @fptr(S + A) */
#define R_IA_64_FPTR32MSB 0x44 /* word32 MSB @fptr(S + A) */
#define R_IA_64_FPTR32LSB 0x45 /* word32 LSB @fptr(S + A) */
#define R_IA_64_FPTR64MSB 0x46 /* word64 MSB @fptr(S + A) */
#define R_IA_64_FPTR64LSB 0x47 /* word64 LSB @fptr(S + A) */
#define R_IA_64_PCREL60B 0x48 /* immediate60 form1 S + A - P */
#define R_IA_64_PCREL21B 0x49 /* immediate21 form1 S + A - P */
#define R_IA_64_PCREL21M 0x4a /* immediate21 form2 S + A - P */
#define R_IA_64_PCREL21F 0x4b /* immediate21 form3 S + A - P */
#define R_IA_64_PCREL32MSB 0x4c /* word32 MSB S + A - P */
#define R_IA_64_PCREL32LSB 0x4d /* word32 LSB S + A - P */
#define R_IA_64_PCREL64MSB 0x4e /* word64 MSB S + A - P */
#define R_IA_64_PCREL64LSB 0x4f /* word64 LSB S + A - P */
#define R_IA_64_LTOFF_FPTR22 0x52 /* immediate22 @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR64I 0x53 /* immediate64 @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR32MSB 0x54 /* word32 MSB @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR32LSB 0x55 /* word32 LSB @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR64MSB 0x56 /* word64 MSB @ltoff(@fptr(S + A)) */
#define R_IA_64_LTOFF_FPTR64LSB 0x57 /* word64 LSB @ltoff(@fptr(S + A)) */
#define R_IA_64_SEGREL32MSB 0x5c /* word32 MSB @segrel(S + A) */
#define R_IA_64_SEGREL32LSB 0x5d /* word32 LSB @segrel(S + A) */
#define R_IA_64_SEGREL64MSB 0x5e /* word64 MSB @segrel(S + A) */
#define R_IA_64_SEGREL64LSB 0x5f /* word64 LSB @segrel(S + A) */
#define R_IA_64_SECREL32MSB 0x64 /* word32 MSB @secrel(S + A) */
#define R_IA_64_SECREL32LSB 0x65 /* word32 LSB @secrel(S + A) */
#define R_IA_64_SECREL64MSB 0x66 /* word64 MSB @secrel(S + A) */
#define R_IA_64_SECREL64LSB 0x67 /* word64 LSB @secrel(S + A) */
#define R_IA_64_REL32MSB 0x6c /* word32 MSB BD + A */
#define R_IA_64_REL32LSB 0x6d /* word32 LSB BD + A */
#define R_IA_64_REL64MSB 0x6e /* word64 MSB BD + A */
#define R_IA_64_REL64LSB 0x6f /* word64 LSB BD + A */
#define R_IA_64_LTV32MSB 0x74 /* word32 MSB S + A */
#define R_IA_64_LTV32LSB 0x75 /* word32 LSB S + A */
#define R_IA_64_LTV64MSB 0x76 /* word64 MSB S + A */
#define R_IA_64_LTV64LSB 0x77 /* word64 LSB S + A */
#define R_IA_64_PCREL21BI 0x79 /* immediate21 form1 S + A - P */
#define R_IA_64_PCREL22 0x7a /* immediate22 S + A - P */
#define R_IA_64_PCREL64I 0x7b /* immediate64 S + A - P */
#define R_IA_64_IPLTMSB 0x80 /* function descriptor MSB special */
#define R_IA_64_IPLTLSB 0x81 /* function descriptor LSB speciaal */
#define R_IA_64_SUB 0x85 /* immediate64 A - S */
#define R_IA_64_LTOFF22X 0x86 /* immediate22 special */
#define R_IA_64_LDXMOV 0x87 /* immediate22 special */
#define R_IA_64_TPREL14 0x91 /* imm14 @tprel(S + A) */
#define R_IA_64_TPREL22 0x92 /* imm22 @tprel(S + A) */
#define R_IA_64_TPREL64I 0x93 /* imm64 @tprel(S + A) */
#define R_IA_64_TPREL64MSB 0x96 /* word64 MSB @tprel(S + A) */
#define R_IA_64_TPREL64LSB 0x97 /* word64 LSB @tprel(S + A) */
#define R_IA_64_LTOFF_TPREL22 0x9a /* imm22 @ltoff(@tprel(S+A)) */
#define R_IA_64_DTPMOD64MSB 0xa6 /* word64 MSB @dtpmod(S + A) */
#define R_IA_64_DTPMOD64LSB 0xa7 /* word64 LSB @dtpmod(S + A) */
#define R_IA_64_LTOFF_DTPMOD22 0xaa /* imm22 @ltoff(@dtpmod(S+A)) */
#define R_IA_64_DTPREL14 0xb1 /* imm14 @dtprel(S + A) */
#define R_IA_64_DTPREL22 0xb2 /* imm22 @dtprel(S + A) */
#define R_IA_64_DTPREL64I 0xb3 /* imm64 @dtprel(S + A) */
#define R_IA_64_DTPREL32MSB 0xb4 /* word32 MSB @dtprel(S + A) */
#define R_IA_64_DTPREL32LSB 0xb5 /* word32 LSB @dtprel(S + A) */
#define R_IA_64_DTPREL64MSB 0xb6 /* word64 MSB @dtprel(S + A) */
#define R_IA_64_DTPREL64LSB 0xb7 /* word64 LSB @dtprel(S + A) */
#define R_IA_64_LTOFF_DTPREL22 0xba /* imm22 @ltoff(@dtprel(S+A)) */
#define R_PPC_NONE 0 /* No relocation. */
#define R_PPC_ADDR32 1
#define R_PPC_ADDR24 2
#define R_PPC_ADDR16 3
#define R_PPC_ADDR16_LO 4
#define R_PPC_ADDR16_HI 5
#define R_PPC_ADDR16_HA 6
#define R_PPC_ADDR14 7
#define R_PPC_ADDR14_BRTAKEN 8
#define R_PPC_ADDR14_BRNTAKEN 9
#define R_PPC_REL24 10
#define R_PPC_REL14 11
#define R_PPC_REL14_BRTAKEN 12
#define R_PPC_REL14_BRNTAKEN 13
#define R_PPC_GOT16 14
#define R_PPC_GOT16_LO 15
#define R_PPC_GOT16_HI 16
#define R_PPC_GOT16_HA 17
#define R_PPC_PLTREL24 18
#define R_PPC_COPY 19
#define R_PPC_GLOB_DAT 20
#define R_PPC_JMP_SLOT 21
#define R_PPC_RELATIVE 22
#define R_PPC_LOCAL24PC 23
#define R_PPC_UADDR32 24
#define R_PPC_UADDR16 25
#define R_PPC_REL32 26
#define R_PPC_PLT32 27
#define R_PPC_PLTREL32 28
#define R_PPC_PLT16_LO 29
#define R_PPC_PLT16_HI 30
#define R_PPC_PLT16_HA 31
#define R_PPC_SDAREL16 32
#define R_PPC_SECTOFF 33
#define R_PPC_SECTOFF_LO 34
#define R_PPC_SECTOFF_HI 35
#define R_PPC_SECTOFF_HA 36
/*
* TLS relocations
*/
#define R_PPC_TLS 67
#define R_PPC_DTPMOD32 68
#define R_PPC_TPREL16 69
#define R_PPC_TPREL16_LO 70
#define R_PPC_TPREL16_HI 71
#define R_PPC_TPREL16_HA 72
#define R_PPC_TPREL32 73
#define R_PPC_DTPREL16 74
#define R_PPC_DTPREL16_LO 75
#define R_PPC_DTPREL16_HI 76
#define R_PPC_DTPREL16_HA 77
#define R_PPC_DTPREL32 78
#define R_PPC_GOT_TLSGD16 79
#define R_PPC_GOT_TLSGD16_LO 80
#define R_PPC_GOT_TLSGD16_HI 81
#define R_PPC_GOT_TLSGD16_HA 82
#define R_PPC_GOT_TLSLD16 83
#define R_PPC_GOT_TLSLD16_LO 84
#define R_PPC_GOT_TLSLD16_HI 85
#define R_PPC_GOT_TLSLD16_HA 86
#define R_PPC_GOT_TPREL16 87
#define R_PPC_GOT_TPREL16_LO 88
#define R_PPC_GOT_TPREL16_HI 89
#define R_PPC_GOT_TPREL16_HA 90
/*
* The remaining relocs are from the Embedded ELF ABI, and are not in the
* SVR4 ELF ABI.
*/
#define R_PPC_EMB_NADDR32 101
#define R_PPC_EMB_NADDR16 102
#define R_PPC_EMB_NADDR16_LO 103
#define R_PPC_EMB_NADDR16_HI 104
#define R_PPC_EMB_NADDR16_HA 105
#define R_PPC_EMB_SDAI16 106
#define R_PPC_EMB_SDA2I16 107
#define R_PPC_EMB_SDA2REL 108
#define R_PPC_EMB_SDA21 109
#define R_PPC_EMB_MRKREF 110
#define R_PPC_EMB_RELSEC16 111
#define R_PPC_EMB_RELST_LO 112
#define R_PPC_EMB_RELST_HI 113
#define R_PPC_EMB_RELST_HA 114
#define R_PPC_EMB_BIT_FLD 115
#define R_PPC_EMB_RELSDA 116
#define R_SPARC_NONE 0
#define R_SPARC_8 1
#define R_SPARC_16 2
#define R_SPARC_32 3
#define R_SPARC_DISP8 4
#define R_SPARC_DISP16 5
#define R_SPARC_DISP32 6
#define R_SPARC_WDISP30 7
#define R_SPARC_WDISP22 8
#define R_SPARC_HI22 9
#define R_SPARC_22 10
#define R_SPARC_13 11
#define R_SPARC_LO10 12
#define R_SPARC_GOT10 13
#define R_SPARC_GOT13 14
#define R_SPARC_GOT22 15
#define R_SPARC_PC10 16
#define R_SPARC_PC22 17
#define R_SPARC_WPLT30 18
#define R_SPARC_COPY 19
#define R_SPARC_GLOB_DAT 20
#define R_SPARC_JMP_SLOT 21
#define R_SPARC_RELATIVE 22
#define R_SPARC_UA32 23
#define R_SPARC_PLT32 24
#define R_SPARC_HIPLT22 25
#define R_SPARC_LOPLT10 26
#define R_SPARC_PCPLT32 27
#define R_SPARC_PCPLT22 28
#define R_SPARC_PCPLT10 29
#define R_SPARC_10 30
#define R_SPARC_11 31
#define R_SPARC_64 32
#define R_SPARC_OLO10 33
#define R_SPARC_HH22 34
#define R_SPARC_HM10 35
#define R_SPARC_LM22 36
#define R_SPARC_PC_HH22 37
#define R_SPARC_PC_HM10 38
#define R_SPARC_PC_LM22 39
#define R_SPARC_WDISP16 40
#define R_SPARC_WDISP19 41
#define R_SPARC_GLOB_JMP 42
#define R_SPARC_7 43
#define R_SPARC_5 44
#define R_SPARC_6 45
#define R_SPARC_DISP64 46
#define R_SPARC_PLT64 47
#define R_SPARC_HIX22 48
#define R_SPARC_LOX10 49
#define R_SPARC_H44 50
#define R_SPARC_M44 51
#define R_SPARC_L44 52
#define R_SPARC_REGISTER 53
#define R_SPARC_UA64 54
#define R_SPARC_UA16 55
#define R_SPARC_TLS_GD_HI22 56
#define R_SPARC_TLS_GD_LO10 57
#define R_SPARC_TLS_GD_ADD 58
#define R_SPARC_TLS_GD_CALL 59
#define R_SPARC_TLS_LDM_HI22 60
#define R_SPARC_TLS_LDM_LO10 61
#define R_SPARC_TLS_LDM_ADD 62
#define R_SPARC_TLS_LDM_CALL 63
#define R_SPARC_TLS_LDO_HIX22 64
#define R_SPARC_TLS_LDO_LOX10 65
#define R_SPARC_TLS_LDO_ADD 66
#define R_SPARC_TLS_IE_HI22 67
#define R_SPARC_TLS_IE_LO10 68
#define R_SPARC_TLS_IE_LD 69
#define R_SPARC_TLS_IE_LDX 70
#define R_SPARC_TLS_IE_ADD 71
#define R_SPARC_TLS_LE_HIX22 72
#define R_SPARC_TLS_LE_LOX10 73
#define R_SPARC_TLS_DTPMOD32 74
#define R_SPARC_TLS_DTPMOD64 75
#define R_SPARC_TLS_DTPOFF32 76
#define R_SPARC_TLS_DTPOFF64 77
#define R_SPARC_TLS_TPOFF32 78
#define R_SPARC_TLS_TPOFF64 79
#define R_X86_64_NONE 0 /* No relocation. */
#define R_X86_64_64 1 /* Add 64 bit symbol value. */
#define R_X86_64_PC32 2 /* PC-relative 32 bit signed sym value. */
#define R_X86_64_GOT32 3 /* PC-relative 32 bit GOT offset. */
#define R_X86_64_PLT32 4 /* PC-relative 32 bit PLT offset. */
#define R_X86_64_COPY 5 /* Copy data from shared object. */
#define R_X86_64_GLOB_DAT 6 /* Set GOT entry to data address. */
#define R_X86_64_JMP_SLOT 7 /* Set GOT entry to code address. */
#define R_X86_64_RELATIVE 8 /* Add load address of shared object. */
#define R_X86_64_GOTPCREL 9 /* Add 32 bit signed pcrel offset to GOT. */
#define R_X86_64_32 10 /* Add 32 bit zero extended symbol value */
#define R_X86_64_32S 11 /* Add 32 bit sign extended symbol value */
#define R_X86_64_16 12 /* Add 16 bit zero extended symbol value */
#define R_X86_64_PC16 13 /* Add 16 bit signed extended pc relative symbol value */
#define R_X86_64_8 14 /* Add 8 bit zero extended symbol value */
#define R_X86_64_PC8 15 /* Add 8 bit signed extended pc relative symbol value */
#define R_X86_64_DTPMOD64 16 /* ID of module containing symbol */
#define R_X86_64_DTPOFF64 17 /* Offset in TLS block */
#define R_X86_64_TPOFF64 18 /* Offset in static TLS block */
#define R_X86_64_TLSGD 19 /* PC relative offset to GD GOT entry */
#define R_X86_64_TLSLD 20 /* PC relative offset to LD GOT entry */
#define R_X86_64_DTPOFF32 21 /* Offset in TLS block */
#define R_X86_64_GOTTPOFF 22 /* PC relative offset to IE GOT entry */
#define R_X86_64_TPOFF32 23 /* Offset in static TLS block */
#endif /* !_SYS_ELF_COMMON_H_ */

View File

@@ -0,0 +1,88 @@
/*-
* Copyright (c) 1998 John D. Polstra.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD: src/sys/sys/elf_generic.h,v 1.6.14.2 2007/12/03 21:30:36 marius Exp $
*/
#ifndef _SYS_ELF_GENERIC_H_
#define _SYS_ELF_GENERIC_H_ 1
#include <sys/cdefs.h>
/*
* Definitions of generic ELF names which relieve applications from
* needing to know the word size.
*/
#if __ELF_WORD_SIZE != 32 && __ELF_WORD_SIZE != 64
#error "__ELF_WORD_SIZE must be defined as 32 or 64"
#endif
#define ELF_CLASS __CONCAT(ELFCLASS,__ELF_WORD_SIZE)
#if BYTE_ORDER == LITTLE_ENDIAN
#define ELF_DATA ELFDATA2LSB
#elif BYTE_ORDER == BIG_ENDIAN
#define ELF_DATA ELFDATA2MSB
#else
#error "Unknown byte order"
#endif
#define __elfN(x) __CONCAT(__CONCAT(__CONCAT(elf,__ELF_WORD_SIZE),_),x)
#define __ElfN(x) __CONCAT(__CONCAT(__CONCAT(Elf,__ELF_WORD_SIZE),_),x)
#define __ELFN(x) __CONCAT(__CONCAT(__CONCAT(ELF,__ELF_WORD_SIZE),_),x)
#define __ElfType(x) typedef __ElfN(x) __CONCAT(Elf_,x)
__ElfType(Addr);
__ElfType(Half);
__ElfType(Off);
__ElfType(Sword);
__ElfType(Word);
__ElfType(Ehdr);
__ElfType(Shdr);
__ElfType(Phdr);
__ElfType(Dyn);
__ElfType(Rel);
__ElfType(Rela);
__ElfType(Sym);
__ElfType(Verdef);
__ElfType(Verdaux);
__ElfType(Verneed);
__ElfType(Vernaux);
__ElfType(Versym);
/* Non-standard ELF types. */
__ElfType(Hashelt);
__ElfType(Size);
__ElfType(Ssize);
#define ELF_R_SYM __ELFN(R_SYM)
#define ELF_R_TYPE __ELFN(R_TYPE)
#define ELF_R_INFO __ELFN(R_INFO)
#define ELF_ST_BIND __ELFN(ST_BIND)
#define ELF_ST_TYPE __ELFN(ST_TYPE)
#define ELF_ST_INFO __ELFN(ST_INFO)
#endif /* !_SYS_ELF_GENERIC_H_ */

View File

@@ -0,0 +1,10 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = GenPage
LIBS = -lCommon
OBJECTS = GenPage.o
include $(MAKEROOT)/Makefiles/app.makefile

View File

@@ -0,0 +1,424 @@
/** @file
Copyright 2006 - 2008, 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 <string.h>
#include "VirtualMemory.h"
#include "EfiUtilityMsgs.h"
#define EFI_PAGE_BASE_OFFSET_IN_LDR 0x70000
#define EFI_PAGE_BASE_ADDRESS (EFI_PAGE_BASE_OFFSET_IN_LDR + 0x20000)
UINT32 gPageTableBaseAddress = EFI_PAGE_BASE_ADDRESS;
UINT32 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)
//
// Utility Name
//
#define UTILITY_NAME "GenBootSector"
//
// Utility version information
//
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
void
Version (
void
)
/*++
Routine Description:
Displays the standard utility information to SDTOUT
Arguments:
None
Returns:
None
--*/
{
printf ("%s v%d.%d -Utility to generate the EfiLoader image containing page table.\n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION);
printf ("Copyright (c) 2008 - 2009 Intel Corporation. All rights reserved.\n");
}
VOID
Usage (
void
)
{
Version();
printf ("\nUsage: \n\
GenPage\n\
-o, --output Filename containing page table\n\
[-b, --baseaddr baseaddress of page table]\n\
[-f, --offset offset in the file that page table will reside]\n\
[-v, --verbose]\n\
[--version]\n\
[-q, --quiet disable all messages except fatal errors]\n\
[-d, --debug[#]\n\
[-h, --help]\n\
EfiLoaderImageName\n");
}
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;
}
INT32
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) {
Error (NoPageFileName, 0, 0x4002, "Invalid parameter option", "Output File %s open failure", PageFileName);
return -1;
}
NoPageFile = fopen (NoPageFileName, "r+b");
if (NoPageFile == NULL) {
Error (NoPageFileName, 0, 0x4002, "Invalid parameter option", "Input File %s open failure", 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) {
Error (NoPageFileName, 0, 0x4002, "Invalid parameter option", "Input file size (0x%x) exceeds the Page Table Offset (0x%x)", FileSize, gPageTableOffsetInFile);
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;
INTN result;
CHAR8 *OutputFile = NULL;
CHAR8 *InputFile = NULL;
EFI_STATUS Status;
UINT64 TempValue;
SetUtilityName("GenPage");
if (argc == 1) {
Usage();
return STATUS_ERROR;
}
argc --;
argv ++;
if ((stricmp (argv[0], "-h") == 0) || (stricmp (argv[0], "--help") == 0)) {
Usage();
return 0;
}
if (stricmp (argv[0], "--version") == 0) {
Version();
return 0;
}
while (argc > 0) {
if ((stricmp (argv[0], "-o") == 0) || (stricmp (argv[0], "--output") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Output file is missing for -o option");
return STATUS_ERROR;
}
OutputFile = argv[1];
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-b") == 0) || (stricmp (argv[0], "--baseaddr") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Base address is missing for -b option");
return STATUS_ERROR;
}
Status = AsciiStringToUint64 (argv[1], FALSE, &TempValue);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "Base address is not valid intergrator");
return STATUS_ERROR;
}
gPageTableBaseAddress = (UINT32) TempValue;
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-f") == 0) || (stricmp (argv[0], "--offset") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Offset is missing for -f option");
return STATUS_ERROR;
}
Status = AsciiStringToUint64 (argv[1], FALSE, &TempValue);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "Offset is not valid intergrator");
return STATUS_ERROR;
}
gPageTableOffsetInFile = (UINT32) TempValue;
argc -= 2;
argv += 2;
continue;
}
if ((stricmp (argv[0], "-q") == 0) || (stricmp (argv[0], "--quiet") == 0)) {
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-v") ==0) || (stricmp (argv[0], "--verbose") == 0)) {
argc --;
argv ++;
continue;
}
if ((stricmp (argv[0], "-d") == 0) || (stricmp (argv[0], "--debug") == 0)) {
if (argv[1] == NULL || argv[1][0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Debug Level is not specified.");
return STATUS_ERROR;
}
Status = AsciiStringToUint64 (argv[1], FALSE, &TempValue);
if (EFI_ERROR (Status)) {
Error (NULL, 0, 1003, "Invalid option value", "Debug Level is not valid intergrator.");
return STATUS_ERROR;
}
if (TempValue > 9) {
Error (NULL, 0, 1003, "Invalid option value", "Debug Level range is 0-9, currnt input level is %d", TempValue);
return STATUS_ERROR;
}
argc -= 2;
argv += 2;
continue;
}
if (argv[0][0] == '-') {
Error (NULL, 0, 1000, "Unknown option", argv[0]);
return STATUS_ERROR;
}
//
// Don't recognize the paramter.
//
InputFile = argv[0];
argc--;
argv++;
}
if (InputFile == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Input file is not specified");
return STATUS_ERROR;
}
//
// Create X64 page table
//
BaseMemory = CreateIdentityMappingPageTables ();
//
// Add page table to binary file
//
result = GenBinPage (BaseMemory, InputFile, OutputFile);
if (result < 0) {
return STATUS_ERROR;
}
return 0;
}

View File

@@ -0,0 +1,10 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = GenPage
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = GenPage.obj
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,127 @@
/** @file
Copyright 2006 - 2008, 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 "CommonLib.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,18 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = GenSec
OBJECTS = GenSec.o
include $(MAKEROOT)/Makefiles/app.makefile
LIBS = -lCommon
ifeq ($(CYGWIN), CYGWIN)
LIBS += -L/lib/e2fsprogs -luuid
endif
ifeq ($(LINUX), Linux)
LIBS += -luuid
endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = GenSec
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = GenSec.obj
#CFLAGS = $(CFLAGS) /nodefaultlib:libc.lib
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,10 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = GenVtf
LIBS = -lCommon
OBJECTS = GenVtf.o
include $(MAKEROOT)/Makefiles/app.makefile

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,330 @@
/** @file
Copyright (c) 1999 - 2008 Intel Corporation. All rights reserved
This software and associated documentation (if any) is furnished
under a license and may only be used or copied in accordance
with the terms of the license. Except as permitted by such
license, no part of this software or documentation may be
reproduced, stored in a retrieval system, or transmitted in any
form or by any means without the express written consent of
Intel Corporation.
Module Name:
GenVtf.h
Abstract:
This file contains the relevant declarations required
to generate Boot Strap File
**/
//
// Module Coded to EFI 2.0 Coding Conventions
//
#ifndef __GEN_VTF_H__
#define __GEN_VTF_H__
//
// External Files Referenced
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "assert.h"
#include <Common/PiFirmwareFile.h>
#include "ParseInf.h"
//
// Internal Constants
//
#define CV_N_TYPE(a,b) (UINT8)(((UINT8)a << 7) + (UINT8)b) // Keeps the CV and Type in same byte field
#define MAKE_VERSION(a,b) (UINT16)(((UINT16)a << 8) + (UINT16)b)
#define FILE_NAME_SIZE 256
#define COMPONENT_NAME_SIZE 128
#define VTF_INPUT_FILE "VTF.INF"
#define VTF_OUTPUT_FILE1 "VTF1.RAW"
#define VTF_OUTPUT_FILE2 "VTF2.RAW"
#define VTF_SYM_FILE "Vtf.SYM"
#define FIT_SIGNATURE "_FIT_ "
//
//Fit Type Definition
//
#define COMP_TYPE_FIT_HEADER 0x00
#define COMP_TYPE_FIT_PAL_B 0x01
//
// This is generic PAL_A
//
#define COMP_TYPE_FIT_PAL_A 0x0F
#define COMP_TYPE_FIT_PEICORE 0x10
#define COMP_TYPE_FIT_AUTOSCAN 0x30
#define COMP_TYPE_FIT_FV_BOOT 0x7E
//
//This is processor Specific PAL_A
//
#define COMP_TYPE_FIT_PAL_A_SPECIFIC 0x0E
#define COMP_TYPE_FIT_UNUSED 0x7F
#define FIT_TYPE_MASK 0x7F
#define CHECKSUM_BIT_MASK 0x80
//
// IPF processor address is cached bit
//
#define IPF_CACHE_BIT 0x8000000000000000ULL
//
// Size definition to calculate the location from top of address for
// each component
//
#define SIZE_IA32_RESET_VECT 0x10 // 16 Bytes
#define SIZE_SALE_ENTRY_POINT 0x08 // 8 Byte
#define SIZE_FIT_TABLE_ADD 0x08 // 8 Byte
#define SIZE_FIT_TABLE_PAL_A 0x10
#define SIZE_RESERVED 0x10
#define SIZE_TO_OFFSET_PAL_A_END (SIZE_IA32_RESET_VECT + SIZE_SALE_ENTRY_POINT + \
SIZE_FIT_TABLE_ADD + SIZE_FIT_TABLE_PAL_A + \
SIZE_RESERVED)
#define SIZE_TO_PAL_A_FIT (SIZE_IA32_RESET_VECT + SIZE_SALE_ENTRY_POINT + \
SIZE_FIT_TABLE_ADD + SIZE_FIT_TABLE_PAL_A)
#define SIZE_OF_PAL_HEADER 0x40 //PAL has 64 byte header
//
// Utility Name
//
#define UTILITY_NAME "GenVtf"
//
// 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 ONE_VTF_ARGS 10
#define TWO_VTF_ARGS 12
#define THREE_VTF_ARGS 16
static BOOLEAN VerboseMode = FALSE;
//
// Internal Data Structure
//
typedef enum _LOC_TYPE
{
NONE, // In case there is - INF file
FIRST_VTF, // First VTF
SECOND_VTF, // Outside VTF
} LOC_TYPE;
typedef struct _PARSED_VTF_INFO {
CHAR8 CompName[COMPONENT_NAME_SIZE];
LOC_TYPE LocationType;
UINT8 CompType;
UINT8 MajorVer;
UINT8 MinorVer;
UINT8 CheckSumRequired;
BOOLEAN VersionPresent; // If it is TRUE, then, Version is in INF file
BOOLEAN PreferredSize;
BOOLEAN PreferredAddress;
CHAR8 CompBinName[FILE_NAME_SIZE];
CHAR8 CompSymName[FILE_NAME_SIZE];
UINTN CompSize;
UINT64 CompPreferredAddress;
UINT32 Align;
//
// Fixed - warning C4133: '=' : incompatible types - from 'struct _ParsedVtfInfo *' to 'struct _PARSED_VTF_INFO *'
// Fixed - warning C4133: '=' : incompatible types - from 'struct _ParsedVtfInfo *' to 'struct _PARSED_VTF_INFO *'
// Fixed - warning C4133: '=' : incompatible types - from 'struct _ParsedVtfInfo *' to 'struct _PARSED_VTF_INFO *'
// Fixed - warning C4133: '=' : incompatible types - from 'struct _ParsedVtfInfo *' to 'struct _PARSED_VTF_INFO *'
//
struct _PARSED_VTF_INFO *NextVtfInfo;
} PARSED_VTF_INFO;
#pragma pack (1)
typedef struct {
UINT64 CompAddress;
UINT32 CompSize;
UINT16 CompVersion;
UINT8 CvAndType;
UINT8 CheckSum;
} FIT_TABLE;
#pragma pack ()
//
// Function Prototype Declarations
//
EFI_STATUS
UpdateVtfBuffer(
IN UINT64 StartAddress,
IN UINT8 *Buffer,
IN UINT64 DataSize,
IN LOC_TYPE LocType
)
/*++
Routine Description:
Update the Firmware Volume Buffer with requested buffer data
Arguments:
StartAddress - StartAddress in buffer. This number will automatically
point to right address in buffer where data needed
to be updated.
Buffer - Buffer pointer from data will be copied to memory mapped buffer.
DataSize - Size of the data needed to be copied.
LocType - The type of the VTF
Returns:
EFI_ABORTED - The input parameter is error
EFI_SUCCESS - The function completed successfully
--*/
;
EFI_STATUS
UpdateSymFile (
IN UINT64 BaseAddress,
IN CHAR8 *DestFileName,
IN CHAR8 *SourceFileName
)
/*++
Routine Description:
This function adds the SYM tokens in the source file to the destination file.
The SYM tokens are updated to reflect the base address.
Arguments:
BaseAddress - The base address for the new SYM tokens.
DestFileName - The destination file.
SourceFileName - The source file.
Returns:
EFI_SUCCESS - The function completed successfully.
EFI_INVALID_PARAMETER - One of the input parameters was invalid.
EFI_ABORTED - An error occurred.
--*/
;
EFI_STATUS
CalculateFitTableChecksum (
VOID
)
/*++
Routine Description:
This function will perform byte checksum on the FIT table, if the the checksum required
field is set to CheckSum required. If the checksum is not required then checksum byte
will have value as 0;.
Arguments:
NONE
Returns:
Status - Value returned by call to CalculateChecksum8 ()
EFI_SUCCESS - The function completed successfully
--*/
;
EFI_STATUS
GenerateVtfImage (
IN UINT64 StartAddress1,
IN UINT64 Size1,
IN UINT64 StartAddress2,
IN UINT64 Size2,
IN FILE *fp
)
/*++
Routine Description:
This is the main function which will be called from application.
Arguments:
StartAddress1 - The start address of the first VTF
Size1 - The size of the first VTF
StartAddress2 - The start address of the second VTF
Size2 - The size of the second VTF
Returns:
EFI_OUT_OF_RESOURCES - Can not allocate memory
The return value can be any of the values
returned by the calls to following functions:
GetVtfRelatedInfoFromInfFile
ProcessAndCreateVtf
UpdateIA32ResetVector
UpdateFfsHeader
WriteVtfBinary
--*/
;
EFI_STATUS
PeimFixupInFitTable (
IN UINT64 StartAddress
)
/*++
Routine Description:
This function is an entry point to fixup SAL-E entry point.
Arguments:
StartAddress - StartAddress for PEIM.....
Returns:
EFI_SUCCESS - The function completed successfully
EFI_ABORTED - Error Opening File
--*/
;
VOID
Usage (
VOID
)
/*++
Routine Description:
Displays the utility usage syntax to STDOUT
Arguments:
None
Returns:
None
--*/
;
#endif

View File

@@ -0,0 +1,10 @@
!INCLUDE ..\Makefiles\ms.common
APPNAME = GenVtf
LIBS = $(LIB_PATH)\Common.lib
OBJECTS = GenVtf.obj
!INCLUDE ..\Makefiles\ms.app

View File

@@ -0,0 +1,152 @@
/** @file
Fat file system structure and definition.
Copyright 2006 - 2008, 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.
--*/
#ifndef _FAT_BPB_H_
#define _FAT_BPB_H_
#include "CommonLib.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,10 @@
ARCH ?= IA32
MAKEROOT ?= ..
APPNAME = GnuGenBootSector
LIBS = -lCommon
OBJECTS = GnuGenBootSector.o
include $(MAKEROOT)/Makefiles/app.makefile

View File

@@ -0,0 +1,457 @@
/** @file
Copyright 2006 - 2009, 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:
GnuGenBootSector.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 "CommonLib.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <Common/UefiBaseTypes.h>
//
// Utility Name
//
#define UTILITY_NAME "GnuGenBootSector"
//
// Utility version information
//
#define UTILITY_MAJOR_VERSION 0
#define UTILITY_MINOR_VERSION 1
#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
#define DRIVE_UNKNOWN 0
#define DRIVE_NO_ROOT_DIR 1
#define DRIVE_REMOVABLE 2
#define DRIVE_FIXED 3
#define DRIVE_REMOTE 4
#define DRIVE_CDROM 5
#define DRIVE_RAMDISK 6
typedef struct _DRIVE_TYPE_DESC {
UINTN Type;
CHAR8 *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),
{(UINTN) -1, NULL}
};
typedef struct _DRIVE_INFO {
CHAR8 VolumeLetter;
DRIVE_TYPE_DESC *DriveType;
UINTN DiskNumber;
} DRIVE_INFO;
typedef enum {
PathUnknown,
PathFile,
PathFloppy,
PathUsb,
PathIde
} PATH_TYPE;
typedef struct _PATH_INFO {
CHAR8 *Path;
CHAR8 PhysicalPath[260];
PATH_TYPE Type;
BOOLEAN Input;
} PATH_INFO;
typedef enum {
ErrorSuccess,
ErrorFileCreate,
ErrorFileReadWrite,
ErrorNoMbr,
ErrorFatType,
ErrorPath,
} ERROR_STATUS;
CHAR8 *ErrorStatusDesc[] = {
"Success",
"Failed to create files",
"Failed to read/write files",
"No MBR exists",
"Failed to detect Fat type",
"Inavlid path"
};
//UnSupported Windows API functions.
UINTN GetLogicalDrives(void) { return 1; }
/**
Get path information, including physical path for Linux platform.
@param PathInfo Point to PATH_INFO structure.
@return whether path is valid.
**/
ERROR_STATUS
GetPathInfo (
PATH_INFO *PathInfo
)
{
FILE *f;
if (strncmp(PathInfo->Path, "/dev/", 5) == 0) {
//
// Process disk path here.
//
// Process floppy disk
if (PathInfo->Path[5] == 'f' && PathInfo->Path[6] == 'd' && PathInfo->Path[8] == '\0') {
PathInfo->Type = PathFloppy;
strcpy (PathInfo->PhysicalPath, PathInfo->Path);
return ErrorSuccess;
} else {
// Other disk types is not supported yet.
fprintf (stderr, "ERROR: It's not a floppy disk!\n");
return ErrorPath;
}
// Try to open the device.
f = fopen(PathInfo->Path,"r");
if (f == NULL) {
printf ("error :open device failed!\n");
return ErrorPath;
}
fclose (f);
return ErrorSuccess;
}
// Process file path here.
PathInfo->Type = PathFile;
if (PathInfo->Input) {
// If path is file path, check whether file is valid.
printf("Path = %s\n",PathInfo->Path);
f = fopen (PathInfo->Path, "r");
if (f == NULL) {
fprintf (stderr, "Test error E2003: File was not provided!\n");
return ErrorPath;
}
fclose (f);
}
strcpy(PathInfo->PhysicalPath, PathInfo->Path);
return ErrorSuccess;
}
VOID
ListDrive (
VOID
)
{
printf("-l or -list not supported!\n");
}
/**
Writing or reading boot sector or MBR according to the argument.
@param InputInfo PATH_INFO instance for input path
@param OutputInfo PATH_INFO instance for output path
@param ProcessMbr TRUE is to process MBR, otherwise, processing boot sector
@return ERROR_STATUS
**/
ERROR_STATUS
ProcessBsOrMbr (
PATH_INFO *InputInfo,
PATH_INFO *OutputInfo,
BOOLEAN ProcessMbr
)
{
CHAR8 FirstSector[0x200] = {0};
CHAR8 FirstSectorBackup[0x200] = {0};
FILE *InputFile;
FILE *OutputFile;
InputFile = fopen(InputInfo->PhysicalPath, "r");
if (InputFile == NULL) {
return ErrorFileReadWrite;
}
if (0x200 != fread(FirstSector, 1, 0x200, InputFile)) {
fclose(InputFile);
return ErrorFileReadWrite;
}
fclose(InputFile);
//Not support USB and IDE.
if (InputInfo->Type == PathUsb) {
printf("USB has not been supported yet!");
return ErrorSuccess;
}
if (InputInfo->Type == PathIde) {
printf("IDE has not been supported yet!");
return ErrorSuccess;
}
//Process Floppy Disk
OutputFile = fopen(OutputInfo->PhysicalPath, "w");
if (OutputFile == NULL) {
return ErrorFileReadWrite;
}
if (OutputInfo->Type != PathFile) {
if (ProcessMbr) {
//
// Use original partition table
//
if (0x200 != fread (FirstSectorBackup, 1, 0x200, OutputFile)) {
fclose(OutputFile);
return ErrorFileReadWrite;
}
memcpy (FirstSector + 0x1BE, FirstSectorBackup + 0x1BE, 0x40);
}
}
if(0x200 != fwrite(FirstSector, 1, 0x200, OutputFile)) {
fclose(OutputFile);
return ErrorFileReadWrite;
}
fclose(OutputFile);
return ErrorSuccess;
}
/**
Displays the standard utility information to SDTOUT
**/
VOID
Version (
VOID
)
{
printf ("%s v%d.%d -Utility to retrieve and update the boot sector or MBR.\n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION);
printf ("Copyright (c) 2007-2009 Intel Corporation. All rights reserved.\n");
}
VOID
PrintUsage (
VOID
)
{
Version();
printf ("\nUsage: \n\
GenBootSector\n\
[-l, --list list disks]\n\
[-i, --input Filename]\n\
[-o, --output Filename]\n\
[-m, --mbr process the MBR also]\n\
[-v, --verbose]\n\
[--version]\n\
[-q, --quiet disable all messages except fatal errors]\n\
[-d, --debug[#]\n\
[-h, --help]\n");
}
INTN
main (
INTN argc,
CHAR8 *argv[]
)
{
CHAR8 *AppName;
INTN Index;
BOOLEAN ProcessMbr;
ERROR_STATUS Status;
EFI_STATUS EfiStatus;
PATH_INFO InputPathInfo;
PATH_INFO OutputPathInfo;
UINT64 LogLevel;
SetUtilityName (UTILITY_NAME);
ZeroMem(&InputPathInfo, sizeof(PATH_INFO));
ZeroMem(&OutputPathInfo, sizeof(PATH_INFO));
AppName = *argv;
argv ++;
argc --;
ProcessMbr = FALSE;
if (argc == 0) {
PrintUsage();
return 0;
}
//
// Parse command line
//
for (Index = 0; Index < argc; Index ++) {
if ((stricmp (argv[Index], "-l") == 0) || (stricmp (argv[Index], "--list") == 0)) {
ListDrive ();
return 0;
}
if ((stricmp (argv[Index], "-m") == 0) || (stricmp (argv[Index], "--mbr") == 0)) {
ProcessMbr = TRUE;
continue;
}
if ((stricmp (argv[Index], "-i") == 0) || (stricmp (argv[Index], "--input") == 0)) {
InputPathInfo.Path = argv[Index + 1];
InputPathInfo.Input = TRUE;
if (InputPathInfo.Path == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Input file name can't be NULL");
return 1;
}
if (InputPathInfo.Path[0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Input file is missing");
return 1;
}
++Index;
continue;
}
if ((stricmp (argv[Index], "-o") == 0) || (stricmp (argv[Index], "--output") == 0)) {
OutputPathInfo.Path = argv[Index + 1];
OutputPathInfo.Input = FALSE;
if (OutputPathInfo.Path == NULL) {
Error (NULL, 0, 1003, "Invalid option value", "Output file name can't be NULL");
return 1;
}
if (OutputPathInfo.Path[0] == '-') {
Error (NULL, 0, 1003, "Invalid option value", "Output file is missing");
return 1;
}
++Index;
continue;
}
if ((stricmp (argv[Index], "-h") == 0) || (stricmp (argv[Index], "--help") == 0)) {
PrintUsage ();
return 0;
}
if (stricmp (argv[Index], "--version") == 0) {
Version ();
return 0;
}
if ((stricmp (argv[Index], "-v") == 0) || (stricmp (argv[Index], "--verbose") == 0)) {
continue;
}
if ((stricmp (argv[Index], "-q") == 0) || (stricmp (argv[Index], "--quiet") == 0)) {
continue;
}
if ((stricmp (argv[Index], "-d") == 0) || (stricmp (argv[Index], "--debug") == 0)) {
EfiStatus = AsciiStringToUint64 (argv[Index + 1], FALSE, &LogLevel);
if (EFI_ERROR (EfiStatus)) {
Error (NULL, 0, 1003, "Invalid option value", "%s = %s", argv[Index], argv[Index + 1]);
return 1;
}
if (LogLevel > 9) {
Error (NULL, 0, 1003, "Invalid option value", "Debug Level range is 0-9, currnt input level is %d", LogLevel);
return 1;
}
SetPrintLevel (LogLevel);
DebugMsg (NULL, 0, 9, "Debug Mode Set", "Debug Output Mode Level %s is set!", argv[Index + 1]);
++Index;
continue;
}
//
// Don't recognize the parameter.
//
Error (NULL, 0, 1000, "Unknown option", "%s", argv[Index]);
return 1;
}
if (InputPathInfo.Path == NULL) {
Error (NULL, 0, 1001, "Missing options", "Input file is missing");
return 1;
}
if (OutputPathInfo.Path == NULL) {
Error (NULL, 0, 1001, "Missing options", "Output file is missing");
return 1;
}
if (GetPathInfo(&InputPathInfo) != ErrorSuccess) {
Error (NULL, 0, 1003, "Invalid option value", "Input file can't be found.");
return 1;
}
if (GetPathInfo(&OutputPathInfo) != ErrorSuccess) {
Error (NULL, 0, 1003, "Invalid option value", "Output file can't be found.");
return 1;
}
//
// Process DBR (Patch or Read)
//
Status = ProcessBsOrMbr (&InputPathInfo, &OutputPathInfo, ProcessMbr);
if (Status == ErrorSuccess) {
fprintf (
stdout,
"%s %s: successful!\n",
(OutputPathInfo.Type != PathFile) ? "Write" : "Read",
ProcessMbr ? "MBR" : "DBR"
);
return 0;
} else {
fprintf (
stderr,
"%s: %s %s: failed - %s (LastError: 0x%x)!\n",
(Status == ErrorNoMbr) ? "WARNING" : "ERROR",
(OutputPathInfo.Type != PathFile) ? "Write" : "Read",
ProcessMbr ? "MBR" : "DBR",
ErrorStatusDesc[Status],
errno
);
return 1;
}
}

View File

@@ -0,0 +1,223 @@
/** @file
Processor or Compiler specific defines for all supported processors.
This file is stand alone self consistent set of definitions.
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.
File Name: BaseTypes.h
**/
#ifndef __BASE_TYPES_H__
#define __BASE_TYPES_H__
//
// Include processor specific binding
//
#include <ProcessorBind.h>
#include <stdarg.h>
//
// Modifiers to absract standard types to aid in debug of problems
//
#define CONST const
#define STATIC static
#define VOID void
//
// Modifiers for Data Types used to self document code.
// This concept is borrowed for UEFI specification.
//
#ifndef IN
//
// Some other envirnments use this construct, so #ifndef to prevent
// mulitple definition.
//
#define IN
#define OUT
#define OPTIONAL
#endif
//
// Constants. They may exist in other build structures, so #ifndef them.
//
#ifndef TRUE
//
// BugBug: UEFI specification claims 1 and 0. We are concerned about the
// complier portability so we did it this way.
//
#define TRUE ((BOOLEAN)(1==1))
#endif
#ifndef FALSE
#define FALSE ((BOOLEAN)(0==1))
#endif
#ifndef NULL
#define NULL ((VOID *) 0)
#endif
//
// Support for variable length argument lists using the ANSI standard.
//
// Since we are using the ANSI standard we used the standard nameing and
// did not folow the coding convention
//
// VA_LIST - typedef for argument list.
// VA_START (VA_LIST Marker, argument before the ...) - Init Marker for use.
// VA_END (VA_LIST Marker) - Clear Marker
// VA_ARG (VA_LIST Marker, var arg size) - Use Marker to get an argumnet from
// the ... list. You must know the size and pass it in this macro.
//
// example:
//
// UINTN
// ExampleVarArg (
// IN UINTN NumberOfArgs,
// ...
// )
// {
// VA_LIST Marker;
// UINTN Index;
// UINTN Result;
//
// //
// // Initialize the Marker
// //
// VA_START (Marker, NumberOfArgs);
// for (Index = 0, Result = 0; Index < NumberOfArgs; Index++) {
// //
// // The ... list is a series of UINTN values, so average them up.
// //
// Result += VA_ARG (Marker, UINTN);
// }
//
// VA_END (Marker);
// return Result
// }
//
#define _INT_SIZE_OF(n) ((sizeof (n) + sizeof (UINTN) - 1) &~(sizeof (UINTN) - 1))
//
// Also support coding convention rules for var arg macros
//
#ifndef VA_START
// typedef CHAR8 *VA_LIST;
// #define VA_START(ap, v) (ap = (VA_LIST) & (v) + _INT_SIZE_OF (v))
// #define VA_ARG(ap, t) (*(t *) ((ap += _INT_SIZE_OF (t)) - _INT_SIZE_OF (t)))
// #define VA_END(ap) (ap = (VA_LIST) 0)
// Use the native arguments for tools.
#define VA_START va_start
#define VA_ARG va_arg
#define VA_END va_end
#define VA_LIST va_list
#endif
//
// Macro that returns the byte offset of a field in a data structure.
//
#define OFFSET_OF(TYPE, Field) ((UINTN) &(((TYPE *)0)->Field))
///
/// _CR - returns a pointer to the structure
/// from one of it's elements.
///
#define _CR(Record, TYPE, Field) ((TYPE *) ((CHAR8 *) (Record) - (CHAR8 *) &(((TYPE *) 0)->Field)))
///
/// ALIGN_POINTER - aligns a pointer to the lowest boundry
///
#define ALIGN_POINTER(p, s) ((VOID *) ((UINTN)(p) + (((s) - ((UINTN) (p))) & ((s) - 1))))
///
/// ALIGN_VARIABLE - aligns a variable up to the next natural boundry for int size of a processor
///
#define ALIGN_VARIABLE(Value, Adjustment) \
Adjustment = 0U; \
if ((UINTN) (Value) % sizeof (UINTN)) { \
(Adjustment) = (UINTN)(sizeof (UINTN) - ((UINTN) (Value) % sizeof (UINTN))); \
} \
(Value) = (UINTN)((UINTN) (Value) + (UINTN) (Adjustment))
//
// Return the maximum of two operands.
// This macro returns the maximum of two operand specified by a and b.
// Both a and b must be the same numerical types, signed or unsigned.
//
#define MAX(a, b) \
(((a) > (b)) ? (a) : (b))
//
// Return the minimum of two operands.
// This macro returns the minimal of two operand specified by a and b.
// Both a and b must be the same numerical types, signed or unsigned.
//
#define MIN(a, b) \
(((a) < (b)) ? (a) : (b))
//
// EFI Error Codes common to all execution phases
//
typedef INTN RETURN_STATUS;
///
/// Set the upper bit to indicate EFI Error.
///
#define ENCODE_ERROR(a) (MAX_BIT | (a))
#define ENCODE_WARNING(a) (a)
#define RETURN_ERROR(a) ((a) < 0)
#define RETURN_SUCCESS 0
#define RETURN_LOAD_ERROR ENCODE_ERROR (1)
#define RETURN_INVALID_PARAMETER ENCODE_ERROR (2)
#define RETURN_UNSUPPORTED ENCODE_ERROR (3)
#define RETURN_BAD_BUFFER_SIZE ENCODE_ERROR (4)
#define RETURN_BUFFER_TOO_SMALL ENCODE_ERROR (5)
#define RETURN_NOT_READY ENCODE_ERROR (6)
#define RETURN_DEVICE_ERROR ENCODE_ERROR (7)
#define RETURN_WRITE_PROTECTED ENCODE_ERROR (8)
#define RETURN_OUT_OF_RESOURCES ENCODE_ERROR (9)
#define RETURN_VOLUME_CORRUPTED ENCODE_ERROR (10)
#define RETURN_VOLUME_FULL ENCODE_ERROR (11)
#define RETURN_NO_MEDIA ENCODE_ERROR (12)
#define RETURN_MEDIA_CHANGED ENCODE_ERROR (13)
#define RETURN_NOT_FOUND ENCODE_ERROR (14)
#define RETURN_ACCESS_DENIED ENCODE_ERROR (15)
#define RETURN_NO_RESPONSE ENCODE_ERROR (16)
#define RETURN_NO_MAPPING ENCODE_ERROR (17)
#define RETURN_TIMEOUT ENCODE_ERROR (18)
#define RETURN_NOT_STARTED ENCODE_ERROR (19)
#define RETURN_ALREADY_STARTED ENCODE_ERROR (20)
#define RETURN_ABORTED ENCODE_ERROR (21)
#define RETURN_ICMP_ERROR ENCODE_ERROR (22)
#define RETURN_TFTP_ERROR ENCODE_ERROR (23)
#define RETURN_PROTOCOL_ERROR ENCODE_ERROR (24)
#define RETURN_INCOMPATIBLE_VERSION ENCODE_ERROR (25)
#define RETURN_SECURITY_VIOLATION ENCODE_ERROR (26)
#define RETURN_CRC_ERROR ENCODE_ERROR (27)
#define RETURN_END_OF_MEDIA ENCODE_ERROR (28)
#define RETURN_END_OF_FILE ENCODE_ERROR (31)
#define RETURN_WARN_UNKNOWN_GLYPH ENCODE_WARNING (1)
#define RETURN_WARN_DELETE_FAILURE ENCODE_WARNING (2)
#define RETURN_WARN_WRITE_FAILURE ENCODE_WARNING (3)
#define RETURN_WARN_BUFFER_TOO_SMALL ENCODE_WARNING (4)
typedef UINT64 PHYSICAL_ADDRESS;
#endif

View File

@@ -0,0 +1,154 @@
/** @file
EDK II specific HII relative definition.
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.
File Name: MdeModuleHii.h
**/
#ifndef _MDEMODULE_HII_H
#define _MDEMODULE_HII_H
#define NARROW_CHAR 0xFFF0
#define WIDE_CHAR 0xFFF1
#define NON_BREAKING_CHAR 0xFFF2
#define GLYPH_WIDTH EFI_GLYPH_WIDTH
#define GLYPH_HEIGHT EFI_GLYPH_HEIGHT
//
// State defined for password statemachine
//
#define BROWSER_STATE_VALIDATE_PASSWORD 0
#define BROWSER_STATE_SET_PASSWORD 1
//
// Tiano Implementation specific Device Path definition.
//
#pragma pack(1)
typedef struct {
VENDOR_DEVICE_PATH VendorDevicePath;
UINT32 Reserved;
UINT64 UniqueId;
} HII_VENDOR_DEVICE_PATH_NODE;
#pragma pack()
typedef struct {
HII_VENDOR_DEVICE_PATH_NODE Node;
EFI_DEVICE_PATH_PROTOCOL End;
} HII_VENDOR_DEVICE_PATH;
//
// GUIDed opcodes defined for Tiano
//
#define EFI_IFR_TIANO_GUID \
{ 0xf0b1735, 0x87a0, 0x4193, {0xb2, 0x66, 0x53, 0x8c, 0x38, 0xaf, 0x48, 0xce} }
#pragma pack(1)
#define EFI_IFR_EXTEND_OP_LABEL 0x0
#define EFI_IFR_EXTEND_OP_BANNER 0x1
#define EFI_IFR_EXTEND_OP_TIMEOUT 0x2
#define EFI_IFR_EXTEND_OP_CLASS 0x3
#define EFI_IFR_EXTEND_OP_SUBCLASS 0x4
typedef struct _EFI_IFR_GUID_LABEL {
EFI_IFR_OP_HEADER Header;
EFI_GUID Guid;
UINT8 ExtendOpCode;
UINT16 Number;
} EFI_IFR_GUID_LABEL;
#define EFI_IFR_BANNER_ALIGN_LEFT 0
#define EFI_IFR_BANNER_ALIGN_CENTER 1
#define EFI_IFR_BANNER_ALIGN_RIGHT 2
typedef struct _EFI_IFR_GUID_BANNER {
EFI_IFR_OP_HEADER Header;
EFI_GUID Guid;
UINT8 ExtendOpCode; // Extended opcode is EFI_IFR_EXTEND_OP_BANNER
EFI_STRING_ID Title; // The string token for the banner title
UINT16 LineNumber; // 1-based line number
UINT8 Alignment; // left, center, or right-aligned
} EFI_IFR_GUID_BANNER;
typedef struct _EFI_IFR_GUID_TIMEOUT {
EFI_IFR_OP_HEADER Header;
EFI_GUID Guid;
UINT8 ExtendOpCode;
UINT16 TimeOut;
} EFI_IFR_GUID_TIMEOUT;
#define EFI_NON_DEVICE_CLASS 0x00
#define EFI_DISK_DEVICE_CLASS 0x01
#define EFI_VIDEO_DEVICE_CLASS 0x02
#define EFI_NETWORK_DEVICE_CLASS 0x04
#define EFI_INPUT_DEVICE_CLASS 0x08
#define EFI_ON_BOARD_DEVICE_CLASS 0x10
#define EFI_OTHER_DEVICE_CLASS 0x20
typedef struct _EFI_IFR_GUID_CLASS {
EFI_IFR_OP_HEADER Header;
EFI_GUID Guid;
UINT8 ExtendOpCode;
UINT16 Class;
} EFI_IFR_GUID_CLASS;
#define EFI_SETUP_APPLICATION_SUBCLASS 0x00
#define EFI_GENERAL_APPLICATION_SUBCLASS 0x01
#define EFI_FRONT_PAGE_SUBCLASS 0x02
#define EFI_SINGLE_USE_SUBCLASS 0x03
typedef struct _EFI_IFR_GUID_SUBCLASS {
EFI_IFR_OP_HEADER Header;
EFI_GUID Guid;
UINT8 ExtendOpCode;
UINT16 SubClass;
} EFI_IFR_GUID_SUBCLASS;
//
// GUIDed opcodes defined for Tiano
//
#define EFI_IFR_FRAMEWORK_GUID \
{ 0x31ca5d1a, 0xd511, 0x4931, { 0xb7, 0x82, 0xae, 0x6b, 0x2b, 0x17, 0x8c, 0xd7 } }
#define EFI_IFR_EXTEND_OP_OPTIONKEY 0x0
#define EFI_IFR_EXTEND_OP_VAREQNAME 0x1
//
// Store the framework vfr option key value
//
typedef struct _EFI_IFR_GUID_OPTIONKEY {
EFI_IFR_OP_HEADER Header;
EFI_GUID Guid;
UINT8 ExtendOpCode;
EFI_QUESTION_ID QuestionId;
EFI_IFR_TYPE_VALUE OptionValue;
EFI_QUESTION_ID KeyValue;
} EFI_IFR_GUID_OPTIONKEY;
//
// Store the framework vfr vareqval name number
//
typedef struct _EFI_IFR_GUID_VAREQNAME {
EFI_IFR_OP_HEADER Header;
EFI_GUID Guid;
UINT8 ExtendOpCode;
EFI_QUESTION_ID QuestionId;
EFI_STRING_ID NameId;
} EFI_IFR_GUID_VAREQNAME;
#pragma pack()
#endif

View File

@@ -0,0 +1,270 @@
/** @file
The firmware file related definitions in PI.
Copyright (c) 2006 - 2008, 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.
File Name: PiFirmwareFile.h
@par Revision Reference:
Version 1.0.
**/
#ifndef __PI_FIRMWARE_FILE_H__
#define __PI_FIRMWARE_FILE_H__
#pragma pack(1)
//
// Used to verify the integrity of the file.
//
typedef union {
struct {
UINT8 Header;
UINT8 File;
} Checksum;
UINT16 Checksum16;
} EFI_FFS_INTEGRITY_CHECK;
typedef UINT8 EFI_FV_FILETYPE;
typedef UINT8 EFI_FFS_FILE_ATTRIBUTES;
typedef UINT8 EFI_FFS_FILE_STATE;
//
// File Types Definitions
//
#define EFI_FV_FILETYPE_ALL 0x00
#define EFI_FV_FILETYPE_RAW 0x01
#define EFI_FV_FILETYPE_FREEFORM 0x02
#define EFI_FV_FILETYPE_SECURITY_CORE 0x03
#define EFI_FV_FILETYPE_PEI_CORE 0x04
#define EFI_FV_FILETYPE_DXE_CORE 0x05
#define EFI_FV_FILETYPE_PEIM 0x06
#define EFI_FV_FILETYPE_DRIVER 0x07
#define EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER 0x08
#define EFI_FV_FILETYPE_APPLICATION 0x09
#define EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE 0x0B
#define EFI_FV_FILETYPE_OEM_MIN 0xc0
#define EFI_FV_FILETYPE_OEM_MAX 0xdf
#define EFI_FV_FILETYPE_DEBUG_MIN 0xe0
#define EFI_FV_FILETYPE_DEBUG_MAX 0xef
#define EFI_FV_FILETYPE_FFS_MIN 0xf0
#define EFI_FV_FILETYPE_FFS_MAX 0xff
#define EFI_FV_FILETYPE_FFS_PAD 0xf0
//
// FFS File Attributes.
//
#define FFS_ATTRIB_FIXED 0x04
#define FFS_ATTRIB_DATA_ALIGNMENT 0x38
#define FFS_ATTRIB_CHECKSUM 0x40
//
// FFS_FIXED_CHECKSUM is the default checksum value used when the
// FFS_ATTRIB_CHECKSUM attribute bit is clear
// note this is NOT an architecturally defined value, but is in this file for
// implementation convenience
//
#define FFS_FIXED_CHECKSUM 0x5A
//
// FFS File State Bits.
//
#define EFI_FILE_HEADER_CONSTRUCTION 0x01
#define EFI_FILE_HEADER_VALID 0x02
#define EFI_FILE_DATA_VALID 0x04
#define EFI_FILE_MARKED_FOR_UPDATE 0x08
#define EFI_FILE_DELETED 0x10
#define EFI_FILE_HEADER_INVALID 0x20
#define EFI_FILE_ALL_STATE_BITS (EFI_FILE_HEADER_CONSTRUCTION | \
EFI_FILE_HEADER_VALID | \
EFI_FILE_DATA_VALID | \
EFI_FILE_MARKED_FOR_UPDATE | \
EFI_FILE_DELETED | \
EFI_FILE_HEADER_INVALID \
)
//
// Each file begins with the header that describe the
// contents and state of the files.
//
typedef struct {
EFI_GUID Name;
EFI_FFS_INTEGRITY_CHECK IntegrityCheck;
EFI_FV_FILETYPE Type;
EFI_FFS_FILE_ATTRIBUTES Attributes;
UINT8 Size[3];
EFI_FFS_FILE_STATE State;
} EFI_FFS_FILE_HEADER;
typedef UINT8 EFI_SECTION_TYPE;
//
// Pseudo type. It is
// used as a wild card when retrieving sections. The section
// type EFI_SECTION_ALL matches all section types.
//
#define EFI_SECTION_ALL 0x00
//
// Encapsulation section Type values
//
#define EFI_SECTION_COMPRESSION 0x01
#define EFI_SECTION_GUID_DEFINED 0x02
//
// Leaf section Type values
//
#define EFI_SECTION_PE32 0x10
#define EFI_SECTION_PIC 0x11
#define EFI_SECTION_TE 0x12
#define EFI_SECTION_DXE_DEPEX 0x13
#define EFI_SECTION_VERSION 0x14
#define EFI_SECTION_USER_INTERFACE 0x15
#define EFI_SECTION_COMPATIBILITY16 0x16
#define EFI_SECTION_FIRMWARE_VOLUME_IMAGE 0x17
#define EFI_SECTION_FREEFORM_SUBTYPE_GUID 0x18
#define EFI_SECTION_RAW 0x19
#define EFI_SECTION_PEI_DEPEX 0x1B
typedef struct {
UINT8 Size[3];
EFI_SECTION_TYPE Type;
} EFI_COMMON_SECTION_HEADER;
//
// Leaf section type that contains an
// IA-32 16-bit executable image.
//
typedef EFI_COMMON_SECTION_HEADER EFI_COMPATIBILITY16_SECTION;
//
// CompressionType of EFI_COMPRESSION_SECTION.
//
#define EFI_NOT_COMPRESSED 0x00
#define EFI_STANDARD_COMPRESSION 0x01
//
// An encapsulation section type in which the
// section data is compressed.
//
typedef struct {
EFI_COMMON_SECTION_HEADER CommonHeader;
UINT32 UncompressedLength;
UINT8 CompressionType;
} EFI_COMPRESSION_SECTION;
//
// Leaf section which could be used to determine the dispatch order of DXEs.
//
typedef EFI_COMMON_SECTION_HEADER EFI_DXE_DEPEX_SECTION;
//
// Leaf section witch contains a PI FV.
//
typedef EFI_COMMON_SECTION_HEADER EFI_FIRMWARE_VOLUME_IMAGE_SECTION;
//
// Leaf section which contains a single GUID.
//
typedef struct {
EFI_COMMON_SECTION_HEADER CommonHeader;
EFI_GUID SubTypeGuid;
} EFI_FREEFORM_SUBTYPE_GUID_SECTION;
//
// Attributes of EFI_GUID_DEFINED_SECTION
//
#define EFI_GUIDED_SECTION_PROCESSING_REQUIRED 0x01
#define EFI_GUIDED_SECTION_AUTH_STATUS_VALID 0x02
//
// Leaf section which is encapsulation defined by specific GUID
//
typedef struct {
EFI_COMMON_SECTION_HEADER CommonHeader;
EFI_GUID SectionDefinitionGuid;
UINT16 DataOffset;
UINT16 Attributes;
} EFI_GUID_DEFINED_SECTION;
//
// Leaf section which contains PE32+ image.
//
typedef EFI_COMMON_SECTION_HEADER EFI_PE32_SECTION;
//
// Leaf section which contains PIC image.
//
typedef EFI_COMMON_SECTION_HEADER EFI_PIC_SECTION;
//
// Leaf section which used to determine the dispatch order of PEIMs.
//
typedef EFI_COMMON_SECTION_HEADER EFI_PEI_DEPEX_SECTION;
//
// Leaf section which constains the position-independent-code image.
//
typedef EFI_COMMON_SECTION_HEADER EFI_TE_SECTION;
//
// Leaf section which contains an array of zero or more bytes.
//
typedef EFI_COMMON_SECTION_HEADER EFI_RAW_SECTION;
//
// Leaf section which contains a unicode string that
// is human readable file name.
//
typedef struct {
EFI_COMMON_SECTION_HEADER CommonHeader;
//
// Array of unicode string.
//
CHAR16 FileNameString[1];
} EFI_USER_INTERFACE_SECTION;
//
// Leaf section which contains a numeric build number and
// an optional unicode string that represent the file revision.
//
typedef struct {
EFI_COMMON_SECTION_HEADER CommonHeader;
UINT16 BuildNumber;
CHAR16 VersionString[1];
} EFI_VERSION_SECTION;
#define SECTION_SIZE(SectionHeaderPtr) \
((UINT32) (*((UINT32 *) ((EFI_COMMON_SECTION_HEADER *) SectionHeaderPtr)->Size) & 0x00ffffff))
#pragma pack()
typedef union {
EFI_COMMON_SECTION_HEADER *CommonHeader;
EFI_COMPRESSION_SECTION *CompressionSection;
EFI_GUID_DEFINED_SECTION *GuidDefinedSection;
EFI_PE32_SECTION *Pe32Section;
EFI_PIC_SECTION *PicSection;
EFI_TE_SECTION *TeSection;
EFI_PEI_DEPEX_SECTION *PeimHeaderSection;
EFI_DXE_DEPEX_SECTION *DependencySection;
EFI_VERSION_SECTION *VersionSection;
EFI_USER_INTERFACE_SECTION *UISection;
EFI_COMPATIBILITY16_SECTION *Code16Section;
EFI_FIRMWARE_VOLUME_IMAGE_SECTION *FVImageSection;
EFI_FREEFORM_SUBTYPE_GUID_SECTION *FreeformSubtypeSection;
EFI_RAW_SECTION *RawSection;
} EFI_FILE_SECTION_POINTER;
#endif

View File

@@ -0,0 +1,146 @@
/** @file
The firmware volume related definitions in PI.
Copyright (c) 2006 - 2008, 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.
File Name: PiFirmwareVolume.h
@par Revision Reference:
Version 1.0.
**/
#ifndef __PI_FIRMWAREVOLUME_H__
#define __PI_FIRMWAREVOLUME_H__
//
// EFI_FV_FILE_ATTRIBUTES
//
typedef UINT32 EFI_FV_FILE_ATTRIBUTES;
//
// Value of EFI_FV_FILE_ATTRIBUTES.
//
#define EFI_FV_FILE_ATTRIB_ALIGNMENT 0x0000001F
#define EFI_FV_FILE_ATTRIB_FIXED 0x00000100
#define EFI_FV_FILE_ATTRIB_MEMORY_MAPPED 0x00000200
typedef UINT32 EFI_FVB_ATTRIBUTES;
//
// Attributes bit definitions
//
#define EFI_FVB2_READ_DISABLED_CAP 0x00000001
#define EFI_FVB2_READ_ENABLED_CAP 0x00000002
#define EFI_FVB2_READ_STATUS 0x00000004
#define EFI_FVB2_WRITE_DISABLED_CAP 0x00000008
#define EFI_FVB2_WRITE_ENABLED_CAP 0x00000010
#define EFI_FVB2_WRITE_STATUS 0x00000020
#define EFI_FVB2_LOCK_CAP 0x00000040
#define EFI_FVB2_LOCK_STATUS 0x00000080
#define EFI_FVB2_STICKY_WRITE 0x00000200
#define EFI_FVB2_MEMORY_MAPPED 0x00000400
#define EFI_FVB2_ERASE_POLARITY 0x00000800
#define EFI_FVB2_READ_LOCK_CAP 0x00001000
#define EFI_FVB2_READ_LOCK_STATUS 0x00002000
#define EFI_FVB2_WRITE_LOCK_CAP 0x00004000
#define EFI_FVB2_WRITE_LOCK_STATUS 0x00008000
#define EFI_FVB2_ALIGNMENT 0x001F0000
#define EFI_FVB2_ALIGNMENT_1 0x00000000
#define EFI_FVB2_ALIGNMENT_2 0x00010000
#define EFI_FVB2_ALIGNMENT_4 0x00020000
#define EFI_FVB2_ALIGNMENT_8 0x00030000
#define EFI_FVB2_ALIGNMENT_16 0x00040000
#define EFI_FVB2_ALIGNMENT_32 0x00050000
#define EFI_FVB2_ALIGNMENT_64 0x00060000
#define EFI_FVB2_ALIGNMENT_128 0x00070000
#define EFI_FVB2_ALIGNMENT_256 0x00080000
#define EFI_FVB2_ALIGNMENT_512 0x00090000
#define EFI_FVB2_ALIGNMENT_1K 0x000A0000
#define EFI_FVB2_ALIGNMENT_2K 0x000B0000
#define EFI_FVB2_ALIGNMENT_4K 0x000C0000
#define EFI_FVB2_ALIGNMENT_8K 0x000D0000
#define EFI_FVB2_ALIGNMENT_16K 0x000E0000
#define EFI_FVB2_ALIGNMENT_32K 0x000F0000
#define EFI_FVB2_ALIGNMENT_64K 0x00100000
#define EFI_FVB2_ALIGNMENT_128K 0x00110000
#define EFI_FVB2_ALIGNMENT_256K 0x00120000
#define EFI_FVB2_ALIGNMNET_512K 0x00130000
#define EFI_FVB2_ALIGNMENT_1M 0x00140000
#define EFI_FVB2_ALIGNMENT_2M 0x00150000
#define EFI_FVB2_ALIGNMENT_4M 0x00160000
#define EFI_FVB2_ALIGNMENT_8M 0x00170000
#define EFI_FVB2_ALIGNMENT_16M 0x00180000
#define EFI_FVB2_ALIGNMENT_32M 0x00190000
#define EFI_FVB2_ALIGNMENT_64M 0x001A0000
#define EFI_FVB2_ALIGNMENT_128M 0x001B0000
#define EFI_FVB2_ALIGNMENT_256M 0x001C0000
#define EFI_FVB2_ALIGNMENT_512M 0x001D0000
#define EFI_FVB2_ALIGNMENT_1G 0x001E0000
#define EFI_FVB2_ALIGNMENT_2G 0x001F0000
typedef struct {
UINT32 NumBlocks;
UINT32 Length;
} EFI_FV_BLOCK_MAP_ENTRY;
//
// Describes the features and layout of the firmware volume.
//
typedef struct {
UINT8 ZeroVector[16];
EFI_GUID FileSystemGuid;
UINT64 FvLength;
UINT32 Signature;
EFI_FVB_ATTRIBUTES Attributes;
UINT16 HeaderLength;
UINT16 Checksum;
UINT16 ExtHeaderOffset;
UINT8 Reserved[1];
UINT8 Revision;
EFI_FV_BLOCK_MAP_ENTRY BlockMap[1];
} EFI_FIRMWARE_VOLUME_HEADER;
#define EFI_FVH_SIGNATURE EFI_SIGNATURE_32 ('_', 'F', 'V', 'H')
///
/// Firmware Volume Header Revision definition
///
#define EFI_FVH_REVISION 0x02
//
// Extension header pointed by ExtHeaderOffset of volume header.
//
typedef struct {
EFI_GUID FvName;
UINT32 ExtHeaderSize;
} EFI_FIRMWARE_VOLUME_EXT_HEADER;
typedef struct {
UINT16 ExtEntrySize;
UINT16 ExtEntryType;
} EFI_FIRMWARE_VOLUME_EXT_ENTRY;
#define EFI_FV_EXT_TYPE_OEM_TYPE 0x01
typedef struct {
EFI_FIRMWARE_VOLUME_EXT_ENTRY Hdr;
UINT32 TypeMask;
//
// Array of GUIDs.
// Each GUID represents an OEM file type.
//
EFI_GUID Types[1];
} EFI_FIRMWARE_VOLUME_EXT_ENTRY_OEM_TYPE;
#endif

View File

@@ -0,0 +1,177 @@
/** @file
Defines data types and constants introduced in UEFI.
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.
File Name: UefiBaseTypes.h
**/
#ifndef __UEFI_BASETYPE_H__
#define __UEFI_BASETYPE_H__
#include <Common/BaseTypes.h>
//
// Basical data type definitions introduced in UEFI.
//
typedef struct {
UINT32 Data1;
UINT16 Data2;
UINT16 Data3;
UINT8 Data4[8];
} EFI_GUID;
typedef RETURN_STATUS EFI_STATUS;
typedef VOID *EFI_HANDLE;
typedef VOID *EFI_EVENT;
typedef UINTN EFI_TPL;
typedef UINT64 EFI_LBA;
typedef UINT16 STRING_REF;
typedef UINT64 EFI_PHYSICAL_ADDRESS;
typedef UINT64 EFI_VIRTUAL_ADDRESS;
//
// EFI Time Abstraction:
// Year: 2000 - 20XX
// Month: 1 - 12
// Day: 1 - 31
// Hour: 0 - 23
// Minute: 0 - 59
// Second: 0 - 59
// Nanosecond: 0 - 999,999,999
// TimeZone: -1440 to 1440 or 2047
//
typedef struct {
UINT16 Year;
UINT8 Month;
UINT8 Day;
UINT8 Hour;
UINT8 Minute;
UINT8 Second;
UINT8 Pad1;
UINT32 Nanosecond;
INT16 TimeZone;
UINT8 Daylight;
UINT8 Pad2;
} EFI_TIME;
//
// Networking Definitions
//
typedef struct {
UINT8 Addr[4];
} EFI_IPv4_ADDRESS;
typedef struct {
UINT8 Addr[16];
} EFI_IPv6_ADDRESS;
typedef struct {
UINT8 Addr[32];
} EFI_MAC_ADDRESS;
typedef union {
UINT32 Addr[4];
EFI_IPv4_ADDRESS v4;
EFI_IPv6_ADDRESS v6;
} EFI_IP_ADDRESS;
//
// Enumeration of EFI_STATUS.
//
#define EFI_SUCCESS RETURN_SUCCESS
#define EFI_LOAD_ERROR RETURN_LOAD_ERROR
#define EFI_INVALID_PARAMETER RETURN_INVALID_PARAMETER
#define EFI_UNSUPPORTED RETURN_UNSUPPORTED
#define EFI_BAD_BUFFER_SIZE RETURN_BAD_BUFFER_SIZE
#define EFI_BUFFER_TOO_SMALL RETURN_BUFFER_TOO_SMALL
#define EFI_NOT_READY RETURN_NOT_READY
#define EFI_DEVICE_ERROR RETURN_DEVICE_ERROR
#define EFI_WRITE_PROTECTED RETURN_WRITE_PROTECTED
#define EFI_OUT_OF_RESOURCES RETURN_OUT_OF_RESOURCES
#define EFI_VOLUME_CORRUPTED RETURN_VOLUME_CORRUPTED
#define EFI_VOLUME_FULL RETURN_VOLUME_FULL
#define EFI_NO_MEDIA RETURN_NO_MEDIA
#define EFI_MEDIA_CHANGED RETURN_MEDIA_CHANGED
#define EFI_NOT_FOUND RETURN_NOT_FOUND
#define EFI_ACCESS_DENIED RETURN_ACCESS_DENIED
#define EFI_NO_RESPONSE RETURN_NO_RESPONSE
#define EFI_NO_MAPPING RETURN_NO_MAPPING
#define EFI_TIMEOUT RETURN_TIMEOUT
#define EFI_NOT_STARTED RETURN_NOT_STARTED
#define EFI_ALREADY_STARTED RETURN_ALREADY_STARTED
#define EFI_ABORTED RETURN_ABORTED
#define EFI_ICMP_ERROR RETURN_ICMP_ERROR
#define EFI_TFTP_ERROR RETURN_TFTP_ERROR
#define EFI_PROTOCOL_ERROR RETURN_PROTOCOL_ERROR
#define EFI_INCOMPATIBLE_VERSION RETURN_INCOMPATIBLE_VERSION
#define EFI_SECURITY_VIOLATION RETURN_SECURITY_VIOLATION
#define EFI_CRC_ERROR RETURN_CRC_ERROR
#define EFI_END_OF_MEDIA RETURN_END_OF_MEDIA
#define EFI_END_OF_FILE RETURN_END_OF_FILE
#define EFI_WARN_UNKNOWN_GLYPH RETURN_WARN_UNKNOWN_GLYPH
#define EFI_WARN_DELETE_FAILURE RETURN_WARN_DELETE_FAILURE
#define EFI_WARN_WRITE_FAILURE RETURN_WARN_WRITE_FAILURE
#define EFI_WARN_BUFFER_TOO_SMALL RETURN_WARN_BUFFER_TOO_SMALL
#define NULL_HANDLE ((VOID *) 0)
//
// Define macro to encode the status code.
//
#define EFIERR(_a) ENCODE_ERROR(_a)
#define EFI_ERROR(A) RETURN_ERROR(A)
//
// Define macros to build data structure signatures from characters.
//
#define EFI_SIGNATURE_16(A, B) ((A) | (B << 8))
#define EFI_SIGNATURE_32(A, B, C, D) (EFI_SIGNATURE_16 (A, B) | (EFI_SIGNATURE_16 (C, D) << 16))
#define EFI_SIGNATURE_64(A, B, C, D, E, F, G, H) \
(EFI_SIGNATURE_32 (A, B, C, D) | ((UINT64) (EFI_SIGNATURE_32 (E, F, G, H)) << 32))
//
// Returns the byte offset to a field within a structure
//
#define EFI_FIELD_OFFSET(TYPE,Field) ((UINTN)(&(((TYPE *) 0)->Field)))
//
// The EFI memory allocation functions work in units of EFI_PAGEs that are
// 4K. This should in no way be confused with the page size of the processor.
// An EFI_PAGE is just the quanta of memory in EFI.
//
#define EFI_PAGE_SIZE 0x1000
#define EFI_PAGE_MASK 0xFFF
#define EFI_PAGE_SHIFT 12
#define EFI_SIZE_TO_PAGES(a) (((a) >> EFI_PAGE_SHIFT) + (((a) & EFI_PAGE_MASK) ? 1 : 0))
#define EFI_PAGES_TO_SIZE(a) ( (a) << EFI_PAGE_SHIFT)
#define EFI_MAX_BIT MAX_BIT
#define EFI_MAX_ADDRESS MAX_ADDRESS
#endif

View File

@@ -0,0 +1,34 @@
/** @file
Defines for the EFI Capsule functionality.
Copyright (c) 2006 - 2008, 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.
File Name: Capsule.h
@par Revision Reference:
These definitions are from Uefi Spec.
**/
#ifndef _EFI_CAPSULE_H_
#define _EFI_CAPSULE_H_
typedef struct {
EFI_GUID CapsuleGuid;
UINT32 HeaderSize;
UINT32 Flags;
UINT32 CapsuleImageSize;
} EFI_CAPSULE_HEADER;
#define CAPSULE_FLAGS_PERSIST_ACROSS_RESET 0x00010000
#define CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE 0x00020000
#endif // #ifndef _EFI_CAPSULE_H_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,231 @@
/** @file
This includes some definitions introduced in UEFI that will be used in both PEI and DXE phases.
Copyright (c) 2006 - 2008, 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.
File Name: UefiMultiPhase.h
**/
#ifndef __UEFI_MULTIPHASE_H__
#define __UEFI_MULTIPHASE_H__
//
// Enumeration of memory types introduced in UEFI.
//
typedef enum {
EfiReservedMemoryType,
EfiLoaderCode,
EfiLoaderData,
EfiBootServicesCode,
EfiBootServicesData,
EfiRuntimeServicesCode,
EfiRuntimeServicesData,
EfiConventionalMemory,
EfiUnusableMemory,
EfiACPIReclaimMemory,
EfiACPIMemoryNVS,
EfiMemoryMappedIO,
EfiMemoryMappedIOPortSpace,
EfiPalCode,
EfiMaxMemoryType
} EFI_MEMORY_TYPE;
//
// Data structure that precedes all of the standard EFI table types.
//
typedef struct {
UINT64 Signature;
UINT32 Revision;
UINT32 HeaderSize;
UINT32 CRC32;
UINT32 Reserved;
} EFI_TABLE_HEADER;
//
// Attributes of variable.
//
#define EFI_VARIABLE_NON_VOLATILE 0x00000001
#define EFI_VARIABLE_BOOTSERVICE_ACCESS 0x00000002
#define EFI_VARIABLE_RUNTIME_ACCESS 0x00000004
#define EFI_VARIABLE_HARDWARE_ERROR_RECORD 0x00000008
//
// This attribute is identified by the mnemonic 'HR'
// elsewhere in this specification.
//
#define EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS 0x00000010
//
// _WIN_CERTIFICATE.wCertificateType
//
#define WIN_CERT_TYPE_EFI_PKCS115 0x0EF0
#define WIN_CERT_TYPE_EFI_GUID 0x0EF1
/**
The WIN_CERTIFICATE structure is part of the PE/COFF
specification and has the following definition:
@param dwLength The length of the entire certificate,
including the length of the header, in
bytes.
@param wRevision The revision level of the WIN_CERTIFICATE
structure. The current revision level is
0x0200.
@param wCertificateType The certificate type. See
WIN_CERT_TYPE_xxx for the UEFI
certificate types. The UEFI
specification reserves the range of
certificate type values from 0x0EF0
to 0x0EFF.
@param bCertificate The actual certificate. The format of
the certificate depends on
wCertificateType. The format of the UEFI
certificates is defined below.
**/
typedef struct _WIN_CERTIFICATE {
UINT32 dwLength;
UINT16 wRevision;
UINT16 wCertificateType;
//UINT8 bCertificate[ANYSIZE_ARRAY];
} WIN_CERTIFICATE;
//
// WIN_CERTIFICATE_UEFI_GUID.CertType
//
#define EFI_CERT_TYPE_RSA2048_SHA256_GUID \
{0xa7717414, 0xc616, 0x4977, {0x94, 0x20, 0x84, 0x47, 0x12, 0xa7, 0x35, 0xbf } }
//
// WIN_CERTIFICATE_UEFI_GUID.CertData
//
typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 {
UINT32 HashType;
UINT8 PublicKey[256];
UINT8 Signature[256];
} EFI_CERT_BLOCK_RSA_2048_SHA256;
/**
@param Hdr This is the standard WIN_CERTIFICATE header, where
wCertificateType is set to
WIN_CERT_TYPE_UEFI_GUID.
@param CertType This is the unique id which determines the
format of the CertData. In this case, the
value is EFI_CERT_TYPE_RSA2048_SHA256_GUID.
@param CertData This is the certificate data. The format of
the data is determined by the CertType. In
this case the value is
EFI_CERT_BLOCK_RSA_2048_SHA256.
@param Information The WIN_CERTIFICATE_UEFI_GUID certificate
type allows new types of certificates to
be developed for driver authentication
without requiring a new certificate type.
The CertType defines the format of the
CertData, which length is defined by the
size of the certificate less the fixed
size of the WIN_CERTIFICATE_UEFI_GUID
structure.
**/
typedef struct _WIN_CERTIFICATE_UEFI_GUID {
WIN_CERTIFICATE Hdr;
EFI_GUID CertType;
// UINT8 CertData[ANYSIZE_ARRAY];
} WIN_CERTIFICATE_UEFI_GUID;
/**
Certificate which encapsulates the RSASSA_PKCS1-v1_5 digital
signature.
The WIN_CERTIFICATE_UEFI_PKCS1_15 structure is derived from
WIN_CERTIFICATE and encapsulate the information needed to
implement the RSASSA-PKCS1-v1_5 digital signature algorithm as
specified in RFC2437.
@param Hdr This is the standard WIN_CERTIFICATE header, where
wCertificateType is set to
WIN_CERT_TYPE_UEFI_PKCS1_15.
@param HashAlgorithm This is the hashing algorithm which was
performed on the UEFI executable when
creating the digital signature. It is
one of the enumerated values pre-defined
in Section 26.4.1. See
EFI_HASH_ALGORITHM_x.
@param Signature This is the actual digital signature. The
size of the signature is the same size as
the key (1024-bit key is 128 bytes) and can
be determined by subtracting the length of
the other parts of this header from the
total length of the certificate as found in
Hdr.dwLength.
**/
typedef struct _WIN_CERTIFICATE_EFI_PKCS1_15 {
WIN_CERTIFICATE Hdr;
EFI_GUID HashAlgorithm;
// UINT8 Signature[ANYSIZE_ARRAY];
} WIN_CERTIFICATE_EFI_PKCS1_15;
/**
AuthInfo is a WIN_CERTIFICATE using the wCertificateType
WIN_CERTIFICATE_UEFI_GUID and the CertType
EFI_CERT_TYPE_RSA2048_SHA256. If the attribute specifies
authenticated access, then the Data buffer should begin with an
authentication descriptor prior to the data payload and DataSize
should reflect the the data.and descriptor size. The caller
shall digest the Monotonic Count value and the associated data
for the variable update using the SHA-256 1-way hash algorithm.
The ensuing the 32-byte digest will be signed using the private
key associated w/ the public/private 2048-bit RSA key-pair. The
WIN_CERTIFICATE shall be used to describe the signature of the
Variable data *Data. In addition, the signature will also
include the MonotonicCount value to guard against replay attacks
@param MonotonicCount Included in the signature of
AuthInfo.Used to ensure freshness/no
replay. Incremented during each
"Write" access.
@param AuthInfo Provides the authorization for the variable
access. It is a signature across the
variable data and the Monotonic Count
value. Caller uses Private key that is
associated with a public key that has been
provisioned via the key exchange.
**/
typedef struct {
UINT64 MonotonicCount;
WIN_CERTIFICATE_UEFI_GUID AuthInfo;
} EFI_VARIABLE_AUTHENTICATION;
#endif

View File

@@ -0,0 +1,54 @@
/**@file
Header file for EFI Variable Services.
Copyright (c) 2007 - 2008, Intel Corporation. All rights reserved. <BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at:
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
File Name: VariableFormat.h
**/
#ifndef __VARIABLE_FORMAT_H__
#define __VARIABLE_FORMAT_H__
#define VARIABLE_STORE_SIGNATURE EFI_SIGNATURE_32 ('$', 'V', 'S', 'S')
#define VARIABLE_DATA 0x55AA
//
// Variable Store Header flags
//
#define VARIABLE_STORE_FORMATTED 0x5a
#define VARIABLE_STORE_HEALTHY 0xfe
#pragma pack(1)
typedef struct {
UINT32 Signature;
UINT32 Size;
UINT8 Format;
UINT8 State;
UINT16 Reserved;
UINT32 Reserved1;
} VARIABLE_STORE_HEADER;
typedef struct {
UINT16 StartId;
UINT8 State;
UINT8 Reserved;
UINT32 Attributes;
UINT32 NameSize;
UINT32 DataSize;
EFI_GUID VendorGuid;
} VARIABLE_HEADER;
#pragma pack()
#endif // _EFI_VARIABLE_H_

View File

@@ -0,0 +1,43 @@
/** @file
Defines data structure that is the headers found at the runtime
updatable firmware volumes, such as the FileSystemGuid of the
working block, the header structure of the variable block, FTW
working block, or event log block.
Copyright (c) 2006 - 2008, 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.
File Name: WorkingBlockHeader.h
**/
#ifndef __EFI_WORKING_BLOCK_HEADER_H__
#define __EFI_WORKING_BLOCK_HEADER_H__
//
// EFI Fault tolerant working block header
// The header is immediately followed by the write queue.
//
typedef struct {
EFI_GUID Signature;
UINT32 Crc;
UINT8 WorkingBlockValid : 1;
UINT8 WorkingBlockInvalid : 1;
#define WORKING_BLOCK_VALID 0x1
#define WORKING_BLOCK_INVALID 0x2
UINT8 Reserved : 6;
UINT8 Reserved3[3];
UINT32 WriteQueueSize;
//
// UINT8 WriteQueue[WriteQueueSize];
//
} EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER;
#endif

View File

@@ -0,0 +1,61 @@
/** @file
Terminal Device Path Vendor Guid.
Copyright (c) 2006 - 2008, 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.
File Name: PcAnsi.h
@par Revision Reference:
GUIDs defined in UEFI 2.0 spec.
**/
#ifndef __PC_ANSI_H__
#define __PC_ANSI_H__
#define EFI_PC_ANSI_GUID \
{ \
0xe0c14753, 0xf9be, 0x11d2, {0x9a, 0x0c, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } \
}
#define EFI_VT_100_GUID \
{ \
0xdfa66065, 0xb419, 0x11d3, {0x9a, 0x2d, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } \
}
#define EFI_VT_100_PLUS_GUID \
{ \
0x7baec70b, 0x57e0, 0x4c76, {0x8e, 0x87, 0x2f, 0x9e, 0x28, 0x08, 0x83, 0x43 } \
}
#define EFI_VT_UTF8_GUID \
{ \
0xad15a0d6, 0x8bec, 0x4acf, {0xa0, 0x73, 0xd0, 0x1d, 0xe7, 0x7e, 0x2d, 0x88 } \
}
#define EFI_UART_DEVICE_PATH_GUID \
{ \
0x37499a9d, 0x542f, 0x4c89, {0xa0, 0x26, 0x35, 0xda, 0x14, 0x20, 0x94, 0xe4 } \
}
#define EFI_SAS_DEVICE_PATH_GUID \
{ \
0xd487ddb4, 0x008b, 0x11d9, {0xaf, 0xdc, 0x00, 0x10, 0x83, 0xff, 0xca, 0x4d } \
}
extern EFI_GUID gEfiPcAnsiGuid;
extern EFI_GUID gEfiVT100Guid;
extern EFI_GUID gEfiVT100PlusGuid;
extern EFI_GUID gEfiVTUTF8Guid;
extern EFI_GUID gEfiUartDevicePathGuid;
extern EFI_GUID gEfiSasDevicePathGuid;
#endif

View File

@@ -0,0 +1,41 @@
/** @file
Guid used to define the Firmware File System. See PI spec volume 3 for more
details.
Copyright (c) 2006 - 2008, 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.
File Name: PiFirmwareFileSystem.h
@par Revision Reference:
Guids defined in PI Spec Volume 3
**/
#ifndef __FIRMWARE_FILE_SYSTEM2_GUID_H__
#define __FIRMWARE_FILE_SYSTEM2_GUID_H__
//
// GUIDs defined by the PI specification.
//
#define EFI_FIRMWARE_FILE_SYSTEM2_GUID \
{ \
0x8c8ce578, 0x8a3d, 0x4f1c, {0x99, 0x35, 0x89, 0x61, 0x85, 0xc3, 0x2d, 0xd3 } \
}
#define EFI_FFS_VOLUME_TOP_FILE_GUID \
{ \
0x1BA0062E, 0xC779, 0x4582, {0x85, 0x66, 0x33, 0x6A, 0xE8, 0xF7, 0x8F, 0x09 } \
}
extern EFI_GUID gEfiFirmwareFileSystem2Guid;
extern EFI_GUID gEfiFirmwareVolumeTopFileGuid;
#endif

View File

@@ -0,0 +1,168 @@
/** @file
Processor or Compiler specific defines and types for x64.
Copyright (c) 2006 - 2008, 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.
File Name: ProcessorBind.h
**/
#ifndef __PROCESSOR_BIND_H__
#define __PROCESSOR_BIND_H__
//
// Define the processor type so other code can make processor based choices
//
#define MDE_CPU_IA32
//
// Make sure we are useing the correct packing rules per EFI specification
//
#ifndef __GNUC__
#pragma pack()
#endif
#if _MSC_EXTENSIONS
//
// Disable warning that make it impossible to compile at /W4
// This only works for Microsoft* tools
//
//
// Disabling bitfield type checking warnings.
//
#pragma warning ( disable : 4214 )
//
// Disabling the unreferenced formal parameter warnings.
//
#pragma warning ( disable : 4100 )
//
// Disable slightly different base types warning as CHAR8 * can not be set
// to a constant string.
//
#pragma warning ( disable : 4057 )
//
// ASSERT(FALSE) or while (TRUE) are legal constructes so supress this warning
//
#pragma warning ( disable : 4127 )
#endif
#if !defined(__GNUC__) && (__STDC_VERSION__ < 199901L)
//
// No ANSI C 2000 stdint.h integer width declarations, so define equivalents
//
#if _MSC_EXTENSIONS
//
// use Microsoft* C complier dependent interger width types
//
typedef unsigned __int64 UINT64;
typedef __int64 INT64;
typedef unsigned __int32 UINT32;
typedef __int32 INT32;
typedef unsigned short UINT16;
typedef unsigned short CHAR16;
typedef short INT16;
typedef unsigned char BOOLEAN;
typedef unsigned char UINT8;
typedef char CHAR8;
typedef char INT8;
#else
//
// Assume standard IA-32 alignment.
// BugBug: Need to check portability of long long
//
typedef unsigned long long UINT64;
typedef long long INT64;
typedef unsigned int UINT32;
typedef int INT32;
typedef unsigned short UINT16;
typedef unsigned short CHAR16;
typedef short INT16;
typedef unsigned char BOOLEAN;
typedef unsigned char UINT8;
typedef char CHAR8;
typedef char INT8;
#endif
#define UINT8_MAX 0xff
#else
//
// Use ANSI C 2000 stdint.h integer width declarations
//
#include "stdint.h"
typedef uint8_t BOOLEAN;
typedef int8_t INT8;
typedef uint8_t UINT8;
typedef int16_t INT16;
typedef uint16_t UINT16;
typedef int32_t INT32;
typedef uint32_t UINT32;
typedef int64_t INT64;
typedef uint64_t UINT64;
typedef char CHAR8;
typedef uint16_t CHAR16;
#endif
typedef UINT32 UINTN;
typedef INT32 INTN;
//
// Processor specific defines
//
#define MAX_BIT 0x80000000
#define MAX_2_BITS 0xC0000000
//
// Maximum legal IA-32 address
//
#define MAX_ADDRESS 0xFFFFFFFF
//
// Modifier to ensure that all protocol member functions and EFI intrinsics
// use the correct C calling convention. All protocol member functions and
// EFI intrinsics are required to modify thier member functions with EFIAPI.
//
#if _MSC_EXTENSIONS
//
// Microsoft* compiler requires _EFIAPI useage, __cdecl is Microsoft* specific C.
//
#define EFIAPI __cdecl
#endif
#if __GNUC__
#define EFIAPI __attribute__((cdecl))
#endif
//
// The Microsoft* C compiler can removed references to unreferenced data items
// if the /OPT:REF linker option is used. We defined a macro as this is a
// a non standard extension
//
#if _MSC_EXTENSIONS
#define GLOBAL_REMOVE_IF_UNREFERENCED __declspec(selectany)
#else
#define GLOBAL_REMOVE_IF_UNREFERENCED
#endif
#endif

View File

@@ -0,0 +1,125 @@
/** @file
This file contains some basic ACPI definitions that are consumed by drivers
that do not care about ACPI versions.
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.
File Name: Acpi.h
**/
#ifndef _ACPI_H_
#define _ACPI_H_
//
// Common table header, this prefaces all ACPI tables, including FACS, but
// excluding the RSD PTR structure
//
typedef struct {
UINT32 Signature;
UINT32 Length;
} EFI_ACPI_COMMON_HEADER;
//
// Common ACPI description table header. This structure prefaces most ACPI tables.
//
#pragma pack(1)
typedef struct {
UINT32 Signature;
UINT32 Length;
UINT8 Revision;
UINT8 Checksum;
UINT8 OemId[6];
UINT64 OemTableId;
UINT32 OemRevision;
UINT32 CreatorId;
UINT32 CreatorRevision;
} EFI_ACPI_DESCRIPTION_HEADER;
#pragma pack()
//
// Define for Pci Host Bridge Resource Allocation
//
#define ACPI_ADDRESS_SPACE_DESCRIPTOR 0x8A
#define ACPI_END_TAG_DESCRIPTOR 0x79
#define ACPI_ADDRESS_SPACE_TYPE_MEM 0x00
#define ACPI_ADDRESS_SPACE_TYPE_IO 0x01
#define ACPI_ADDRESS_SPACE_TYPE_BUS 0x02
//
// Power Management Timer frequency is fixed at 3.579545MHz
//
#define ACPI_TIMER_FREQUENCY 3579545
//
// Make sure structures match spec
//
#pragma pack(1)
typedef struct {
UINT8 Desc;
UINT16 Len;
UINT8 ResType;
UINT8 GenFlag;
UINT8 SpecificFlag;
UINT64 AddrSpaceGranularity;
UINT64 AddrRangeMin;
UINT64 AddrRangeMax;
UINT64 AddrTranslationOffset;
UINT64 AddrLen;
} EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR;
typedef struct {
UINT8 Desc;
UINT8 Checksum;
} EFI_ACPI_END_TAG_DESCRIPTOR;
//
// General use definitions
//
#define EFI_ACPI_RESERVED_BYTE 0x00
#define EFI_ACPI_RESERVED_WORD 0x0000
#define EFI_ACPI_RESERVED_DWORD 0x00000000
#define EFI_ACPI_RESERVED_QWORD 0x0000000000000000
//
// Resource Type Specific Flags
// Ref ACPI specification 6.4.3.5.5
//
// Bit [0] : Write Status, _RW
//
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_READ_WRITE (1 << 0)
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_READ_ONLY (0 << 0)
//
// Bit [2:1] : Memory Attributes, _MEM
//
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_NON_CACHEABLE (0 << 1)
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE (1 << 1)
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_WRITE_COMBINING (2 << 1)
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE (3 << 1)
//
// Bit [4:3] : Memory Attributes, _MTP
//
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_ADDRESS_RANGE_MEMORY (0 << 3)
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_ADDRESS_RANGE_RESERVED (1 << 3)
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_ADDRESS_RANGE_ACPI (2 << 3)
#define EFI_APCI_MEMORY_RESOURCE_SPECIFIC_FLAG_ADDRESS_RANGE_NVS (3 << 3)
//
// Bit [5] : Memory to I/O Translation, _TTP
//
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_TYPE_TRANSLATION (1 << 5)
#define EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_TYPE_STATIC (0 << 5)
#pragma pack()
#endif

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