From nobody Mon Feb 9 08:58:04 2026 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of groups.io designates 66.175.222.12 as permitted sender) client-ip=66.175.222.12; envelope-from=bounce+27952+42669+1787277+3901457@groups.io; helo=web01.groups.io; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zoho.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+42669+1787277+3901457@groups.io; dmarc=fail(p=none dis=none) header.from=intel.com ARC-Seal: i=1; a=rsa-sha256; t=1561080413; cv=none; d=zoho.com; s=zohoarc; b=miJ3nmw5BnQ2+yYhd1qTyftkFdBzPR7X95XZrTTvtVObV0K+eQZs+vJUn7mCYZtK6DIf++5CzSDw1pHmTc7OoxqcROhHgmTWShTHxZ5wEN+ptE7hWoQWdr8aQ4uWwe49MNjBep3y+Efy8gE0VV4j4oq/1duJVdZFje9Nh1YBPs0= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zoho.com; s=zohoarc; t=1561080413; h=Cc:Date:From:In-Reply-To:List-Id:List-Unsubscribe:Message-ID:Reply-To:References:Sender:Subject:To:ARC-Authentication-Results; bh=8XHN7JAThAAwmRIs3nPxliro0eupON4Sh0uZeQ2tvRc=; b=RbzQrZUwQj6ah7dYvFME66wYFgr+iPx+D/SDH47TOiKTatcJpsBSs4aU5O+0+32bnYm4CtHUXk3esQG+tNeSQ2kP9N6OpjspsOvQdT9vCHwFbZLJHNAbFPWb77h+ZSukdQ5Bq6QWHQXzfxh+0mgwrOp1iIYL4ZGoFsvmCehOnxI= ARC-Authentication-Results: i=1; mx.zoho.com; dkim=pass; spf=pass (zoho.com: domain of groups.io designates 66.175.222.12 as permitted sender) smtp.mailfrom=bounce+27952+42669+1787277+3901457@groups.io; dmarc=fail header.from= (p=none dis=none) header.from= Received: from web01.groups.io (web01.groups.io [66.175.222.12]) by mx.zohomail.com with SMTPS id 1561080413531842.6075362149264; Thu, 20 Jun 2019 18:26:53 -0700 (PDT) Return-Path: X-Received: from mga01.intel.com (mga01.intel.com []) by groups.io with SMTP; Thu, 20 Jun 2019 18:26:52 -0700 X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-Received: from fmsmga005.fm.intel.com ([10.253.24.32]) by fmsmga101.fm.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 20 Jun 2019 18:26:51 -0700 X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.63,398,1557212400"; d="scan'208";a="358723158" X-Received: from shenglei-dev.ccr.corp.intel.com ([10.239.158.52]) by fmsmga005.fm.intel.com with ESMTP; 20 Jun 2019 18:26:48 -0700 From: "Zhang, Shenglei" To: devel@edk2.groups.io Cc: Bob Feng , Liming Gao Subject: [edk2-devel] [edk2-platform patch 1/6] Platform\Tools: Add a tool FMMT Date: Fri, 21 Jun 2019 09:26:38 +0800 Message-Id: <20190621012643.9352-2-shenglei.zhang@intel.com> In-Reply-To: <20190621012643.9352-1-shenglei.zhang@intel.com> References: <20190621012643.9352-1-shenglei.zhang@intel.com> Precedence: Bulk List-Unsubscribe: Sender: devel@edk2.groups.io List-Id: Mailing-List: list devel@edk2.groups.io; contact devel+owner@edk2.groups.io Reply-To: devel@edk2.groups.io,shenglei.zhang@intel.com DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=groups.io; q=dns/txt; s=20140610; t=1561080412; bh=vEKXn4CDLrAxgeYdvLFw/1SgDNp3Ol1XlZx493g4WWo=; h=Cc:Date:From:Reply-To:Subject:To; b=xC8Ye0ND4ftdKNGPNQ3fI+vpIyLNNa5nuYJaE8BxGd/z4QYyHw2IOUX1jyOCQ7WFQVh QcDIJcarReEUMn2XJKOLhTEyYdrp5VBrxpi8vDBRSZU1Avyy6WOC1NEl0LhelHcTD8jyX 2sLZ6wmLVXI2qdsAi0jVavMwsIzNDyYtgYI= X-ZohoMail-DKIM: pass (identity @groups.io) Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" FMMT is a tool to enable removal, addition and replacement of FFS files in FD image binaries. https://bugzilla.tianocore.org/show_bug.cgi?id=3D1847 Cc: Bob Feng Cc: Liming Gao Signed-off-by: Shenglei Zhang --- .../Tools/FMMT/FirmwareModuleManagement.c | 2559 +++++++++ .../Tools/FMMT/FirmwareModuleManagement.h | 479 ++ Platform/Intel/Tools/FMMT/FmmtConf.ini | 6 + Platform/Intel/Tools/FMMT/FmmtLib.c | 5051 +++++++++++++++++ Platform/Intel/Tools/FMMT/GNUmakefile | 16 + Platform/Intel/Tools/FMMT/Makefile | 17 + Platform/Intel/Tools/FMMT/Rebase.c | 846 +++ Platform/Intel/Tools/FMMT/Rebase.h | 31 + 8 files changed, 9005 insertions(+) create mode 100644 Platform/Intel/Tools/FMMT/FirmwareModuleManagement.c create mode 100644 Platform/Intel/Tools/FMMT/FirmwareModuleManagement.h create mode 100644 Platform/Intel/Tools/FMMT/FmmtConf.ini create mode 100644 Platform/Intel/Tools/FMMT/FmmtLib.c create mode 100644 Platform/Intel/Tools/FMMT/GNUmakefile create mode 100644 Platform/Intel/Tools/FMMT/Makefile create mode 100644 Platform/Intel/Tools/FMMT/Rebase.c create mode 100644 Platform/Intel/Tools/FMMT/Rebase.h diff --git a/Platform/Intel/Tools/FMMT/FirmwareModuleManagement.c b/Platfor= m/Intel/Tools/FMMT/FirmwareModuleManagement.c new file mode 100644 index 0000000000..63ae3c45a4 --- /dev/null +++ b/Platform/Intel/Tools/FMMT/FirmwareModuleManagement.c @@ -0,0 +1,2559 @@ +/** @file + + FMMT main routine. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "FirmwareModuleManagement.h" +#include "Rebase.h" +#include +#include + +CHAR8* mGuidToolDefinition =3D "FmmtConf.ini"; +extern EFI_FIRMWARE_VOLUME_HEADER *mFvHeader; +extern UINT32 mFvLength; + +// +// Store GUIDed Section guid->tool mapping +// +EFI_HANDLE mParsedGuidedSectionTools =3D NULL; +#define EFI_FFS_VOLUME_TOP_FILE_GUID \ +{ \ + 0x1BA0062E, 0xC779, 0x4582, { 0x85, 0x66, 0x33, 0x6A, 0xE8, 0xF7, 0x8F, = 0x09 } \ +} +#define FSP_FFS_INFORMATION_FILE_GUID \ +{ 0x912740be, 0x2284, 0x4734, { 0xb9, 0x71, 0x84, 0xb0, 0x27, 0x35, 0x3f, = 0x0c }}; + +static EFI_GUID mVTFGuid =3D EFI_FFS_VOLUME_TOP_FILE_GUID; +static EFI_GUID mFSPGuid =3D FSP_FFS_INFORMATION_FILE_GUID; + + +/** + +Routine Description: + + The Usage of FMMT tool. + +Arguments: + + None + +Returns: + + None + +**/ +VOID +Usage ( + VOID + ) +{ + // + // Summary usage + // + fprintf (stdout, "Usage: %s [options] \n\n", UTILITY_SHORT_NAME); + + // + // Copyright declaration + // + fprintf (stdout, "Copyright (c) 2011 - 2018, Intel Corporation. All righ= ts reserved.\n\n"); + + // + // Details Option + // + fprintf (stdout, "Options:\n"); + + // + // Command Line for View + // + fprintf (stdout, " -v \n\ + View each FV and the named files within each FV.\n"); + + // + // Command Line for Delete entire FV + // + fprintf (stdout, " -d \= n\ + Delete the entire FV in an FD binary\n"); + + // + // Command Line for Delete file from FV + // + fprintf (stdout, " -d [ = ...] \n\ + Delete a file (or files) from the firmware volume in an FD bin= ary\n"); + + // + // Command Line for Add + // + fprintf (stdout, " -a [ ...] \n\ + Add a file (or files) to the firmware volume in an FD binary\n= "); + + // + // Command Line for Replace + // + fprintf (stdout, " -r [ ...] \n\ + The replace command combines the functionality of remove and a= dd into a single operation.\n"); + + fprintf (stdout, "\nNote:\n"); + fprintf (stdout, " is the sequence of the firmware volume inclu= ded in the FD image, it both support the sequentially format like FV0, FV1 = and the FV's file guid value format.\n"); + return; +} + + +BOOLEAN +IsVtf(EFI_FFS_FILE_HEADER2* ffs) { + if (!memcmp(&ffs->Name, &mVTFGuid, sizeof (EFI_GUID))) { + return TRUE; + } else { + return FALSE; + } +} + +BOOLEAN +IsFsp(EFI_FFS_FILE_HEADER2* ffs) { + if (!memcmp(&ffs->Name, &mFSPGuid, sizeof (EFI_GUID))) { + return TRUE; + } else { + return FALSE; + } +} + +static +EFI_STATUS +GetBaseAddrFromVtf(FIRMWARE_DEVICE *FdData, CHAR8 *FvId, UINT64 *BaseAddr)= { + EFI_STATUS Status; + FV_INFORMATION *CurrentFv; + FV_INFORMATION *FvInFd; + + Status =3D LibLocateFvViaFvId(FdData, FvId, &FvInFd); + if (EFI_ERROR(Status)) { + return Status; + } + + // + // Get bottom FV + // + CurrentFv =3D FdData->Fv; + while (CurrentFv->FvNext) { + CurrentFv =3D CurrentFv->FvNext; + } + if (CurrentFv->FfsNumbers > 0 && IsVtf(&CurrentFv->FfsHeader[CurrentFv->= FfsNumbers])) { + // + // Found VTF at the top of FV + // Assume 4G address + // + *BaseAddr =3D 0x100000000 - (FdData->Size - FvInFd->ImageAddress); + return EFI_SUCCESS; + } + return EFI_NOT_FOUND; +} + +static +EFI_STATUS +GetBaseAddrFromFsp(FIRMWARE_DEVICE *FdData, CONST UINT8* FdBuffer, CHAR8 *= FvId, UINT64 *BaseAddr) +{ + EFI_STATUS Status; + FV_INFORMATION *FvInFd; + FV_INFORMATION *CurrentFv; + FV_INFORMATION *FspFv; + UINT32 Offset; + UINT64 ImageSize; + UINT64 Size; + EFI_FFS_FILE_HEADER2 *CurrentFile; + BOOLEAN FspFound; + + Status =3D LibLocateFvViaFvId(FdData, FvId, &FvInFd); + if (EFI_ERROR(Status)) { + return Status; + } + + ImageSize =3D 0; + Size =3D 0; + FspFound =3D FALSE; + FspFv =3D NULL; + CurrentFv =3D FdData->Fv; + while (CurrentFv) { + if (CurrentFv->FfsNumbers > 0 && IsFsp(&CurrentFv->FfsHeader[0])) { + Offset =3D CurrentFv->ImageAddress + CurrentFv->FfsAttuibutes[0].Off= set; + CurrentFile =3D (EFI_FFS_FILE_HEADER2 *)(FdBuffer + Offset); + // + // Skip FFS header + // + Offset +=3D GetFfsHeaderLength((EFI_FFS_FILE_HEADER *)CurrentFile); + // + // Stip section header + // + Offset +=3D GetSectionHeaderLength((EFI_COMMON_SECTION_HEADER *)(FdB= uffer + Offset)); + // + // We have raw FSP here, and 24 is the image size + // + ImageSize =3D *((UINT32 *)(FdBuffer + Offset + 24)); + // + // 28 is the base address + // + *BaseAddr =3D *((UINT32 *)(FdBuffer + Offset + 28)); + FspFound =3D TRUE; + FspFv =3D CurrentFv; + } + if (CurrentFv =3D=3D FvInFd){ + break; + } + CurrentFv =3D CurrentFv->FvNext; + } + if (!FspFound) { + return EFI_NOT_FOUND; + } + // + // Check if FSP binary contains this FV + // + while (FspFv !=3D NULL) { + Size +=3D FspFv->FvHeader->FvLength; + if (FspFv =3D=3D FvInFd) { + break; + } + FspFv =3D FspFv->FvNext; + } + if (Size <=3D ImageSize) { + return EFI_SUCCESS; + } + + return EFI_NOT_FOUND; +} + +static +VOID +AddPadFile(EFI_FIRMWARE_VOLUME_HEADER *Fv, EFI_FFS_FILE_HEADER2 *PadFile, = UINT32 PadFileSize) { + UINT32 hdrSize; + + if (Fv->Attributes & EFI_FVB2_ERASE_POLARITY) { + memset(PadFile, -1, PadFileSize); + } + else { + memset(PadFile, 0, PadFileSize); + } + PadFile->Type =3D EFI_FV_FILETYPE_FFS_PAD; + PadFile->Attributes =3D 0; + + // + // Write pad file size (calculated size minus next file header size) + // + if (PadFileSize >=3D MAX_FFS_SIZE) { + memset(PadFile->Size, 0, sizeof(UINT8)* 3); + ((EFI_FFS_FILE_HEADER2 *)PadFile)->ExtendedSize =3D PadFileSize; + PadFile->Attributes |=3D FFS_ATTRIB_LARGE_FILE; + hdrSize =3D sizeof(EFI_FFS_FILE_HEADER2); + } + else { + PadFile->Size[0] =3D (UINT8)(PadFileSize & 0xFF); + PadFile->Size[1] =3D (UINT8)((PadFileSize >> 8) & 0xFF); + PadFile->Size[2] =3D (UINT8)((PadFileSize >> 16) & 0xFF); + hdrSize =3D sizeof(EFI_FFS_FILE_HEADER); + } + + // + // Fill in checksums and state, they must be 0 for checksumming. + // + PadFile->IntegrityCheck.Checksum.Header =3D 0; + PadFile->IntegrityCheck.Checksum.File =3D 0; + PadFile->State =3D 0; + PadFile->IntegrityCheck.Checksum.Header =3D CalculateChecksum8((UINT8 *)= PadFile, hdrSize); + PadFile->IntegrityCheck.Checksum.File =3D FFS_FIXED_CHECKSUM; + + PadFile->State =3D EFI_FILE_HEADER_CONSTRUCTION | EFI_FILE_HEADER_VALID = | EFI_FILE_DATA_VALID; + if (Fv->Attributes & EFI_FVB2_ERASE_POLARITY) { + PadFile->State =3D (UINT8)~(PadFile->State); + } +} + +static +UINT8* ReadFileToBuffer(CONST CHAR8 *FdName, UINT32 *FdSize) { + FILE* file; + + UINT8 *FdBuffer =3D NULL; + + file =3D fopen(FdName, "rb"); + if (file =3D=3D NULL) + return NULL; + + fseek(file, 0, SEEK_SET); + fseek(file, 0, SEEK_END); + *FdSize =3D ftell(file); + fseek(file, 0, SEEK_SET); + + FdBuffer =3D malloc(*FdSize); + if (FdBuffer =3D=3D NULL) { + goto FAIL; + } + if (fread(FdBuffer, 1, *FdSize, file) !=3D *FdSize) { + goto FAIL; + } + fclose(file); + return FdBuffer; +FAIL: + free(FdBuffer); + fclose(file); + return NULL; +} + +static UINT32 CalcuFfsSize(EFI_FIRMWARE_VOLUME_HEADER* Fv, CONST EFI_FFS_F= ILE_HEADER2 *Ffs) { + EFI_FFS_FILE_HEADER2 *NextFile; + UINTN FfsSize; + UINTN FvSize; + UINTN Offset; + + FfsSize =3D GetFfsFileLength((EFI_FFS_FILE_HEADER *)Ffs); + FfsSize +=3D (UINT8 *)ALIGN_POINTER(((UINT8 *)Ffs + FfsSize), 8) - ((UIN= T8 *)Ffs + FfsSize); + FvBufGetSize(Fv, &FvSize); + Offset =3D (UINT8 *)Ffs - (UINT8 *)Fv; + if (Offset + FfsSize < FvSize) { + NextFile =3D (EFI_FFS_FILE_HEADER2 *)((UINT8 *)Ffs + FfsSize); + if (NextFile->Type =3D=3D EFI_FV_FILETYPE_FFS_PAD) { + FfsSize +=3D GetFfsFileLength((EFI_FFS_FILE_HEADER *)NextFile); + } + } + return FfsSize; +} + +static +EFI_STATUS +ReadFfsAlignment( +IN EFI_FFS_FILE_HEADER *FfsFile, +IN OUT UINT32 *Alignment +) +{ + // + // Verify input parameters. + // + if (FfsFile =3D=3D NULL || Alignment =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + switch ((FfsFile->Attributes >> 3) & 0x07) { + + case 0: + // + // 1 byte alignment + // + *Alignment =3D 0; + break; + + case 1: + // + // 16 byte alignment + // + *Alignment =3D 4; + break; + + case 2: + // + // 128 byte alignment + // + *Alignment =3D 7; + break; + + case 3: + // + // 512 byte alignment + // + *Alignment =3D 9; + break; + + case 4: + // + // 1K byte alignment + // + *Alignment =3D 10; + break; + + case 5: + // + // 4K byte alignment + // + *Alignment =3D 12; + break; + + case 6: + // + // 32K byte alignment + // + *Alignment =3D 15; + break; + + case 7: + // + // 64K byte alignment + // + *Alignment =3D 16; + break; + + default: + break; + } + + return EFI_SUCCESS; +} + +static +BOOLEAN +ReplaceFfs(EFI_FIRMWARE_VOLUME_HEADER* Fv, EFI_FFS_FILE_HEADER2 *InputFfs,= EFI_FFS_FILE_HEADER2 *OldFfs) { + UINT32 FfsSize; + UINT32 NewFileSize; + UINT32 Offset; + UINT32 Align; + UINT32 HdrSize; + UINT32 PadSize; + EFI_FFS_FILE_HEADER2 *Pad; + + Align =3D 0; + PadSize =3D 0; + Pad =3D NULL; + ReadFfsAlignment((EFI_FFS_FILE_HEADER *)InputFfs, &Align); + Align =3D 1 << Align; + HdrSize =3D GetFfsHeaderLength((EFI_FFS_FILE_HEADER *)InputFfs); + + FfsSize =3D CalcuFfsSize(Fv, OldFfs); + // + // Align data + // + if ((((UINT8 *)OldFfs - (UINT8 *)Fv) + HdrSize) % Align !=3D 0) { + PadSize =3D ((UINT8 *)OldFfs - (UINT8 *)Fv) + sizeof (EFI_FFS_FILE_HEA= DER)+HdrSize; + while (PadSize % Align !=3D 0) { + PadSize++; + } + PadSize -=3D HdrSize; + PadSize -=3D ((UINT8 *)OldFfs - (UINT8 *)Fv); + if (FfsSize < PadSize) { + return FALSE; + } + FfsSize -=3D PadSize; + Pad =3D OldFfs; + OldFfs =3D (EFI_FFS_FILE_HEADER2 *)((UINT8 *)OldFfs + PadSize); + } + + NewFileSize =3D GetFfsFileLength((EFI_FFS_FILE_HEADER *)InputFfs); + Offset =3D (UINT8 *)ALIGN_POINTER(((UINT8 *)OldFfs + NewFileSize), 8) - = ((UINT8 *)OldFfs + NewFileSize); + if (FfsSize >=3D NewFileSize && FfsSize - NewFileSize <=3D 7) { + memcpy(OldFfs, (UINT8 *)InputFfs, NewFileSize); + if (Fv->Attributes & EFI_FVB2_ERASE_POLARITY) { + memset((UINT8 *)OldFfs + NewFileSize, -1, FfsSize - NewFileSize); + } + else { + memset((UINT8 *)OldFfs + NewFileSize, 0, FfsSize - NewFileSize); + } + } + else if (FfsSize >=3D NewFileSize + sizeof(EFI_FFS_FILE_HEADER) + Offset= ) { + memcpy(OldFfs, (UINT8 *)InputFfs, NewFileSize); + AddPadFile( + Fv, + (EFI_FFS_FILE_HEADER2 *)((UINT8 *)OldFfs + NewFileSize + Offset), + FfsSize - NewFileSize - Offset + ); + } + else { + return FALSE; + } + if (Fv->Attributes & EFI_FVB2_ERASE_POLARITY) { + OldFfs->State =3D (UINT8)~(InputFfs->State); + } + if (PadSize !=3D 0) { + AddPadFile(Fv, Pad, PadSize); + } + return TRUE; +} + +static + +EFI_STATUS +AddFfs(UINT8 *FdBuffer, UINT32 ImageAddress, EFI_FIRMWARE_VOLUME_HEADER* F= v, EFI_FFS_FILE_HEADER2 *InputFfs, UINT32 *OffsetAdded) { + UINTN FreeOffset; + UINTN Offset; + UINTN FfsSize; + EFI_STATUS Status; + EFI_FFS_FILE_HEADER2 *CurrentFile; + EFI_FFS_FILE_HEADER FreeHeader; + + if (Fv->Attributes & EFI_FVB2_ERASE_POLARITY) { + memset(&FreeHeader, -1, sizeof(EFI_FFS_FILE_HEADER)); + } + else { + memset(&FreeHeader, 0, sizeof(EFI_FFS_FILE_HEADER)); + } + + FfsSize =3D GetFfsFileLength((EFI_FFS_FILE_HEADER *)InputFfs); + + Offset =3D 0; + CurrentFile =3D NULL; + FreeOffset =3D 0; + do { + if (FreeOffset =3D=3D 0 && memcmp(FdBuffer + ImageAddress + (UINTN)ALI= GN_POINTER(Offset, 8), &FreeHeader, sizeof(EFI_FFS_FILE_HEADER)) =3D=3D 0) { + // + // Offset of free FV space found + // + FreeOffset =3D (UINTN)ALIGN_POINTER(Offset, 8); + } + Status =3D FvBufFindNextFile(FdBuffer + ImageAddress, &Offset, (VOID *= *)&CurrentFile); + if (Status =3D=3D EFI_NOT_FOUND) { + CurrentFile =3D NULL; + break; + } + else if (EFI_ERROR(Status)) { + return Status; + } + + if (CurrentFile !=3D NULL && CurrentFile->Type =3D=3D EFI_FV_FILETYPE_= FFS_PAD && + ReplaceFfs(Fv, InputFfs, CurrentFile)) { + *OffsetAdded =3D (UINT8 *)CurrentFile - (FdBuffer + ImageAddress); + return EFI_SUCCESS; + } + } while (CurrentFile !=3D NULL); + + if (FreeOffset !=3D 0) { + if (Fv->FvLength - FreeOffset < FfsSize) { + return EFI_ABORTED; + } + if (Fv->Attributes & EFI_FVB2_ERASE_POLARITY) { + InputFfs->State =3D (UINT8)~(InputFfs->State); + } + memcpy(FdBuffer + ImageAddress + FreeOffset, InputFfs, FfsSize); + *OffsetAdded =3D FreeOffset; + return EFI_SUCCESS; + } + + return EFI_NOT_FOUND; +} + +static +EFI_STATUS +FindPreviousFile(VOID *Fv, VOID *CurrentFile, VOID **PreFile) { + EFI_STATUS Status; + VOID *File =3D NULL; + UINTN Offset =3D 0; + + do { + *PreFile =3D File; + Status =3D FvBufFindNextFile(Fv, &Offset, &File); + if (Status =3D=3D EFI_NOT_FOUND) { + CurrentFile =3D NULL; + break; + } + else if (EFI_ERROR(Status)) { + return Status; + } + if (File =3D=3D CurrentFile) { + return EFI_SUCCESS; + } + } while (CurrentFile !=3D NULL); + *PreFile =3D NULL; + return Status; +} + +static +BOOLEAN +NeedNewPath(FV_INFORMATION *FvInFd, CHAR8 *FvId, UINT32 FileIndex, BOOLEAN= IsAdd) { + UINT32 Index; + + Index =3D 0; + + if (strcmp(FvId, FvInFd->FvName) !=3D 0) { + return FALSE; + } + if (IsAdd) { + return TRUE; + } + if (FvInFd->FfsAttuibutes[FileIndex].FvLevel !=3D 1) { + return FALSE; + } + + for (Index =3D 0; Index <=3D FvInFd->FfsNumbers; Index++) { + if (FvInFd->FfsAttuibutes[Index].FvLevel !=3D 1) { + continue; + } + switch (FvInFd->FfsHeader[Index].Type) { + case EFI_FV_FILETYPE_PEI_CORE: + case EFI_FV_FILETYPE_PEIM: + case EFI_FV_FILETYPE_SECURITY_CORE: + return TRUE; + } + } + return FALSE; +} + +static UINT32 FindFile(FV_INFORMATION *FvInFd, UINT8 FvLevel, CHAR8 *File,= UINT32 *MatchIndex) { + UINT32 Index =3D 0; + CHAR16 *UIName; + CHAR16 *FfsUIName; + UINT32 FileNumber =3D 0; + + UIName =3D (CHAR16 *)malloc(_MAX_PATH); + if (NULL =3D=3D UIName) { + return 0; + } + FfsUIName =3D (CHAR16 *)malloc(_MAX_PATH); + if (NULL =3D=3D FfsUIName) { + free(UIName); + return 0; + } + LibAscii2Unicode(File, UIName); + for (Index =3D 0; Index <=3D FvInFd->FfsNumbers; Index++) { + // + // Compare the New File Name with UI Name of FFS + // NOTE: The UI Name is Unicode, but the New File Name is Ascii. + // + memcpy(FfsUIName, (CHAR16 *)(FvInFd->FfsAttuibutes[Index].UiName), _MA= X_PATH); + + if (FvInFd->FfsAttuibutes[Index].UiNameSize > 0 && memcmp(UIName, FfsU= IName, FvInFd->FfsAttuibutes[Index].UiNameSize) =3D=3D 0) { + FileNumber +=3D 1; + *MatchIndex =3D Index; + if (FileNumber > 1) { + break; + } + } + + } + free(UIName); + free(FfsUIName); + + return FileNumber; +} + +/** + Search the config file from the path list. + + Split the path from env PATH, and then search the cofig + file from these paths. The priority is from left to + right of PATH string. When met the first Config file, it + will break and return the pointer to the full file name. + + @param PathList the pointer to the path list. + @param FileName the pointer to the file name. + + @retval The pointer to the file name. + @return NULL An error occurred. +**/ +CHAR8 * +SearchConfigFromPathList ( + IN CHAR8 *PathList, + IN CHAR8 *FileName +) +{ + CHAR8 *CurDir; + CHAR8 *FileNamePath; + + CurDir =3D NULL; + FileNamePath =3D NULL; + +#ifndef __GNUC__ + CurDir =3D strtok (PathList,";"); +#else + CurDir =3D strtok (PathList,":"); +#endif + while (CurDir !=3D NULL) { + FileNamePath =3D (char *)calloc( + strlen (CurDir) + strlen (OS_SEP_STR) +strlen (FileNa= me) + 1, + sizeof(char) + ); + if (FileNamePath =3D=3D NULL) { + return NULL; + } + sprintf(FileNamePath, "%s%c%s", CurDir, OS_SEP, FileName); + if (access (FileNamePath, 0) !=3D -1) { + return FileNamePath; + } +#ifndef __GNUC__ + CurDir =3D strtok(NULL, ";"); +#else + CurDir =3D strtok(NULL, ":"); +#endif + free (FileNamePath); + FileNamePath =3D NULL; + } + return NULL; +} + +UINT32 lenList(FILENode* head){ + FILENode *p =3D head; + UINT32 sum=3D0; + if(head=3D=3DNULL) return 0; + while(p!=3DNULL){ + sum+=3D1; + p=3Dp->Next; + } + return sum; +} + +void sortList(FILENode* head){ + UINT32 len =3D lenList(head); + FILENode *p =3D head; + UINT32 i; + UINT32 j; + if(len=3D=3D0) return; + for(i=3D1; iSubLevel < p->Next->SubLevel){ + CHAR8 *FileName =3D p->FileName; + UINT8 tmp =3D p->SubLevel; + p->SubLevel =3D p->Next->SubLevel; + p->Next->SubLevel =3D tmp; + p->FileName =3D p->Next->FileName; + p->Next->FileName =3D FileName; + } + p=3Dp->Next; + } + } +} + +BOOLEAN +ParseSection ( + IN EFI_FFS_FILE_HEADER2 *InputFfs +) +{ + BOOLEAN UISectionFlag; + UINT32 SectionLength; + UINT32 ParsedLength; + UINT32 FfsFileSize; + UINT8 *Ptr; + EFI_SECTION_TYPE Type; + + UISectionFlag =3D FALSE; + Ptr =3D NULL; + SectionLength =3D 0; + ParsedLength =3D GetFfsHeaderLength((EFI_FFS_FILE_HEADER *)InputF= fs); + FfsFileSize =3D GetFfsFileLength((EFI_FFS_FILE_HEADER *)InputFfs= ); + + while (ParsedLength < FfsFileSize) { + Ptr =3D (UINT8 *)InputFfs + ParsedLength; + SectionLength =3D GetLength (((EFI_COMMON_SECTION_HEADER *) Ptr)->Size= ); + Type =3D ((EFI_COMMON_SECTION_HEADER *) Ptr)->Type; + + // + // This is sort of an odd check, but is necessary because FFS files are + // padded to a QWORD boundary, meaning there is potentially a whole se= ction + // header worth of 0xFF bytes. + // + if ((SectionLength =3D=3D 0xffffff) && (Type =3D=3D 0xff)) { + ParsedLength +=3D 4; + continue; + } + if (Type =3D=3D EFI_SECTION_USER_INTERFACE) { + UISectionFlag =3D TRUE; + break; + } + ParsedLength +=3D SectionLength; + // + // We make then next section begin on a 4-byte boundary + // + ParsedLength =3D GetOccupiedSize (ParsedLength, 4); + } + return UISectionFlag; + +} + + +/** + + Show the FD image layout information. Only display the modules with UI n= ame. + + @param[in] FdInName Input FD binary/image file name; + @param[in] FvName The FV ID in the FD file; + @param[in] ViewFlag Is this call for view or other operate(add/del/= replace) + @param[in] FdData The Fd data structure store the FD information. + + @retval EFI_SUCCESS + @retval EFI_INVALID_PARAMETER + @retval EFI_ABORTED + +**/ +EFI_STATUS +FmmtImageView ( + IN CHAR8* FdInName, + IN CHAR8* FvName, + IN BOOLEAN ViewFlag, + IN FIRMWARE_DEVICE **FdData +) +{ + EFI_STATUS Status; + EFI_STATUS ErrorStatus; + FIRMWARE_DEVICE *LocalFdData; + FV_INFORMATION *CurrentFv; + FILE *InputFile; + UINT32 FvSize; + UINTN BytesRead; + EFI_FIRMWARE_VOLUME_HEADER *FvImage; + UINT32 FfsCount; + UINT8 FvCount; + CHAR8 *TemDir; + + LocalFdData =3D NULL; + CurrentFv =3D NULL; + FvImage =3D NULL; + TemDir =3D NULL; + FvSize =3D 0; + BytesRead =3D 0; + FfsCount =3D 0; + FvCount =3D 0; + ErrorStatus =3D EFI_SUCCESS; + + // + // Check the FD file name/path. + // + if (FdInName =3D=3D NULL) { + Error("FMMT", 0, 1001, "Invalid parameter! Please specify ", FdInName); + Usage(); + return EFI_INVALID_PARAMETER; + } + + // + // Open the file containing the FV + // + InputFile =3D fopen (FdInName, "rb"); + if (InputFile =3D=3D NULL) { + Error (NULL, 0, 0001, "Error opening the input file", FdInName); + return EFI_INVALID_PARAMETER; + } + + Status =3D LibFindFvInFd (InputFile, &LocalFdData); + + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 1001, "Error while search FV in FD", ""); + fclose (InputFile); + return EFI_ABORTED; + } + + CurrentFv =3D LocalFdData->Fv; + + + do { + + memset (CurrentFv->FvName, '\0', _MAX_PATH); + + if (FvCount =3D=3D 0) { + sprintf (CurrentFv->FvName, "FV%d", FvCount); + } else { + sprintf (CurrentFv->FvName, "FV%d", FvCount); + } + + // + // Determine size of FV + // + if (fseek (InputFile, CurrentFv->ImageAddress, SEEK_SET) !=3D 0) { + Error (NULL, 0, 0003, "error parsing FV image", "%s FD file is inval= id", InputFile); + fclose (InputFile); + ErrorStatus =3D EFI_ABORTED; + goto Done; + } + + Status =3D LibGetFvSize(InputFile, &FvSize); + if (EFI_ERROR (Status)) { + Error (NULL, 0, 0003, "error parsing FV image", "%s Header is invali= d", InputFile); + fclose (InputFile); + ErrorStatus =3D EFI_ABORTED; + goto Done; + } + + // + // Seek to the start of the image, then read the entire FV to the buff= er + // + fseek (InputFile, CurrentFv->ImageAddress, SEEK_SET); + + + FvImage =3D (EFI_FIRMWARE_VOLUME_HEADER *) malloc (FvSize); + + if (FvImage =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + fclose (InputFile); + ErrorStatus =3D EFI_ABORTED; + goto Done; + } + + BytesRead =3D fread (FvImage, 1, FvSize, InputFile); + if ((unsigned int) BytesRead !=3D FvSize) { + Error ("FMMT", 0, 0004, "error reading FvImage from", FdInName); + free (FvImage); + fclose (InputFile); + ErrorStatus =3D EFI_ABORTED; + goto Done; + } + + // + // Collect FV information each by each. + // + Status =3D LibGetFvInfo (FvImage, CurrentFv, FvName, 0, &CurrentFv->En= capData, &FfsCount, &FvCount, ViewFlag, FALSE); + if (FvImage !=3D NULL) { + free (FvImage); + FvImage =3D NULL; + } + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while get information from FV %s", Fv= Name); + ErrorStatus =3D Status; + // + // If the FV to be parsed error is the same with the input FV in add= , replace and delete + // operation, abort the program directly. + // + if ((FvName !=3D NULL) && ((CurrentFv->FvName) !=3D NULL) && !strcmp= (CurrentFv->FvName, FvName)) { + fclose (InputFile); + ErrorStatus =3D EFI_ABORTED; + goto Done; + } + } + + + FfsCount =3D 0; + + CurrentFv =3D CurrentFv->FvNext; + + } while (CurrentFv !=3D NULL); + + fclose (InputFile); + + if (ViewFlag) { + + TemDir =3D getcwd (NULL, _MAX_PATH); + if (strlen (TemDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _M= AX_PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + ErrorStatus =3D EFI_ABORTED; + goto Done; + } + strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen(TemDir) - 1); + strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen(TemDir) - 1); + + mkdir(TemDir, S_IRWXU | S_IRWXG | S_IRWXO); + + Status =3D LibRmDir (TemDir); + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "remove = directory failed!"); + ErrorStatus =3D Status; + } + } +Done: + if (!ViewFlag) { + *FdData =3D LocalFdData; + } else { + LibFmmtFreeFd( LocalFdData); + } + return ErrorStatus; +} + +/** + Add FFS file into a specify FV. + + @param[in] FdInName Input FD binary/image file name; + @param[in] FileList The FV ID and FFS file Data; + @param[in] count The length of FileList; + @param[in] FdOutName Name of output FD binary/image file. + + @retval EFI_SUCCESS + @retval EFI_INVALID_PARAMETER + @retval EFI_ABORTED + +**/ +EFI_STATUS +FmmtImageAdd( + IN CHAR8* FdInName, + IN Data *FileList, + IN int count, + IN CHAR8* FdOutName +) +{ + EFI_STATUS Status; + FIRMWARE_DEVICE *FdData; + FV_INFORMATION *FvInFd; + FILE* NewFdFile; + FILE* NewFvFile; + UINT64 NewFvLength; + VOID* Buffer; + CHAR8 *TemDir; + UINT8 FvNumInFd; + UINT8 FvNumInFdCounter; + UINT8 NewAddedFfsLevel; + FFS_INFORMATION *OutputFileName; + UINT32 Index; + UINT32 EndId; + UINT8 *FdBuffer; + EFI_FIRMWARE_VOLUME_HEADER *Fv; + UINT32 FdSize; + EFI_FFS_FILE_HEADER2 *InputFfs; + UINT32 NewFileSize; + UINT64 BaseAddr; + UINT32 OffsetAdded; + int i; + int j; + Data *tmp; + CHAR8* FvId; + CHAR8* NewFile; + FILENode *NewFileNode; + BOOLEAN HasUISection; + HasUISection =3D FALSE; + Index =3D 0; + EndId =3D 0; + NewFvLength =3D 0; + FvNumInFd =3D 0; + FvNumInFdCounter =3D 0; + NewAddedFfsLevel =3D 0; + FdData =3D NULL; + FvInFd =3D NULL; + NewFdFile =3D NULL; + NewFvFile =3D NULL; + Buffer =3D NULL; + TemDir =3D NULL; + OutputFileName =3D NULL; + FvId =3D NULL; + NewFile =3D NULL; + + FdBuffer =3D NULL; + InputFfs =3D NULL; + BaseAddr =3D 0; + OffsetAdded =3D 0; + FdSize =3D 0; + + for (i =3D 0; i < count; i ++){ + tmp =3D FileList + i; + FvId =3D tmp->FvId; + FdData =3D tmp->FdData; + if (FdData =3D=3D NULL) { + Status =3D FmmtImageView (FdInName, FvId, FALSE, &FdData); + if (EFI_ERROR (Status) && Status !=3D EFI_UNSUPPORTED) { + Error ("FMMT", 0, 0004, "error while parsing FD Image", "G= athering FD information failed!"); + return Status; + } + if (FdData =3D=3D NULL) { + Error ("FMMT", 0, 0004, "error while parsing FD Image", ""= ); + return EFI_ABORTED; + } + + Status =3D LibLocateFvViaFvId (FdData, FvId, &FvInFd); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0005, "error while locate FV in FD", ""); + return Status; + } + (FileList + i) -> FdData =3D FdData; + (FileList + i) -> FvInFd =3D FvInFd; + (FileList + i) -> FvLevel =3D FvInFd -> FvLevel; + } + } + + for (i =3D 0; i < count; i++) { + for (j =3D i + 1; j < count; j++){ + if (((FileList + i)->FvId =3D=3D NULL) || ((FileList + j)->FvId = =3D=3D NULL)) { + continue; + } + if (strcmp((FileList + j)->FvId, (FileList + i)->FvInFd->FvName) = =3D=3D 0){ + NewFileNode =3D (FileList + j)->NewFile; + while (NewFileNode ->Next !=3D NULL) { + NewFileNode =3D NewFileNode->Next; + } + NewFileNode->Next =3D (FileList + i)->NewFile; + (FileList + i)->FvId =3D NULL; + } + } + } + + for (i =3D 0; i < count; i ++){ + if ((FileList + i)->FvId =3D=3D NULL) { + continue; + } + sortList ((FileList + i)-> NewFile); + } + + TemDir =3D getcwd(NULL, _MAX_PATH); + if (strlen (TemDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _M= AX_PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return EFI_ABORTED; + } + strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen(TemDir) - 1); + strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen(TemDir) - 1); + + if (FdBuffer =3D=3D NULL) { + FdBuffer =3D ReadFileToBuffer(FdInName, &FdSize); + if (FdBuffer =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while adding file", "cannot read= input file."); + return EFI_ABORTED; + } + } + + for (i =3D 0; i < count; i ++){ + tmp =3D FileList + i; + FvId =3D tmp->FvId; + if (FvId =3D=3D NULL) { + continue; + } + FdData =3D tmp->FdData; + FvInFd =3D tmp->FvInFd; + NewFileNode =3Dtmp->NewFile; + + NewFile =3D NewFileNode->FileName; + InputFfs =3D (EFI_FFS_FILE_HEADER2 *)ReadFileToBuffer(NewFile, &Ne= wFileSize); + if (InputFfs =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while adding file", "cannot read= input file."); + Status =3D EFI_ABORTED; + goto FAILED; + } + HasUISection =3D FALSE; + HasUISection =3D ParseSection(InputFfs); + if (!HasUISection) { + printf ("WARNING: The newly add file must have a user interfac= e (UI) section, otherwise it cannot be deleted or replaced. \n"); + } + if (NeedNewPath(FvInFd, FvId, 0, TRUE)) { + do { + NewFile =3D NewFileNode->FileName; + // + // TODO: currently only root FV is handled + // + InputFfs =3D (EFI_FFS_FILE_HEADER2 *)ReadFileToBuffer(NewF= ile, &NewFileSize); + if (InputFfs =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while adding file", "can= not read input file."); + Status =3D EFI_ABORTED; + goto FAILED; + } + + Fv =3D (EFI_FIRMWARE_VOLUME_HEADER *)(FdBuffer + FvInFd->I= mageAddress); + + Status =3D AddFfs(FdBuffer, FvInFd->ImageAddress, Fv, Inpu= tFfs, &OffsetAdded); + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0003, "error while adding file", "Not= enough space to add FFS"); + goto FAILED; + } + // + // Calculate base address of Current FV + // + if (InputFfs->Type =3D=3D EFI_FV_FILETYPE_PEIM || InputFfs= ->Type =3D=3D EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) { + Status =3D GetBaseAddrFromFsp(FdData, FdBuffer, FvId, = &BaseAddr); + if (!EFI_ERROR(Status)) { + mFvHeader =3D FvInFd->FvHeader; + mFvLength =3D (UINT32)FvInFd->FvHeader->FvLength; + RebaseFfs(BaseAddr, NewFile, (EFI_FFS_FILE_HEADER = *)(FdBuffer + FvInFd->ImageAddress + OffsetAdded), OffsetAdded); + } + else { + Status =3D GetBaseAddrFromVtf(FdData, FvId, &BaseA= ddr); + if (!EFI_ERROR(Status)) { + mFvHeader =3D FvInFd->FvHeader; + mFvLength =3D (UINT32)FvInFd->FvHeader->FvLeng= th; + RebaseFfs(BaseAddr, NewFile, (EFI_FFS_FILE_HEA= DER *)(FdBuffer + FvInFd->ImageAddress + OffsetAdded), OffsetAdded); + } + } + } + NewFileNode =3D NewFileNode->Next; + free (InputFfs); + InputFfs =3D NULL; + } while (NewFileNode !=3D NULL); + } else { + do { + NewFile =3D NewFileNode->FileName; + if (strlen (NewFile) > _MAX_PATH - 1) { + Error ("FMMT", 0, 2000, "error while adding file", "New = file name is too long!"); + Status =3D EFI_ABORTED; + goto FAILED; + } + FvNumInFd =3D ((UINT8)atoi(FvId + 2) - (UINT8)atoi(FvInFd-= >FvName + 2)); + if (FvInFd->FfsNumbers =3D=3D 0) { + NewAddedFfsLevel =3D FvInFd->FfsAttuibutes[0].Level; + } + for (Index =3D 0; Index <=3D FvInFd->FfsNumbers; Index++) { + if (FvInFd->FfsAttuibutes[Index].IsFvStart =3D=3D 1) { + FvNumInFdCounter++; + } + if ( FvNumInFdCounter =3D=3D FvNumInFd && FvInFd->FfsA= ttuibutes[Index].IsFvEnd =3D=3D 1) { + NewAddedFfsLevel =3D FvInFd->FfsAttuibutes[Index].= Level; + EndId =3D Index+1; + break; + } + if (FvInFd->FfsAttuibutes[Index].IsFvEnd =3D=3D 1) { + FvNumInFdCounter--; + if (FvNumInFdCounter =3D=3D 0) { + FvNumInFd--; + } + } + } + + // + // Add the new file into FV. + // + FvInFd->FfsNumbers +=3D 1; + for (Index =3D FvInFd->FfsNumbers; Index > EndId; Index--)= { + FvInFd->FfsAttuibutes[Index] =3D FvInFd->FfsAttuibutes= [Index - 1]; + } + strncpy(FvInFd->FfsAttuibutes[EndId].FfsName, NewFile, _MA= X_PATH - 1); + FvInFd->FfsAttuibutes[EndId].FfsName[_MAX_PATH - 1] =3D 0; + FvInFd->FfsAttuibutes[EndId].Level =3D NewAddedFfsLevel; + memset (&FvInFd->FfsAttuibutes[EndId].GuidName, '\0', size= of(EFI_GUID)); + if (EndId > 0) { + FvInFd->FfsAttuibutes[EndId].FvLevel =3D FvInFd->FfsAt= tuibutes[EndId - 1].FvLevel; + FvInFd->FfsAttuibutes[EndId - 1].IsFvEnd =3D 0; + } + FvInFd->FfsAttuibutes[EndId].IsFvEnd =3D 1; + FvInFd->FfsAttuibutes[EndId].IsFvStart =3D 0; + NewFileNode =3D NewFileNode->Next; + } while (NewFileNode !=3D NULL); + + mkdir(TemDir, S_IRWXU | S_IRWXG | S_IRWXO); + + Status =3D LibEncapNewFvFile (FvInFd, TemDir, NULL, 0, &Output= FileName); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image"= , "Make new FV file failed!"); + goto FAILED; + } + + NewFvFile =3D fopen (OutputFileName->FFSName, "rb+"); + if (NewFvFile =3D=3D NULL) { + Error ("FMMT", 0, 0003, "error Open FV file", "cannot Crea= te a new FD file."); + Status =3D EFI_ABORTED; + goto FAILED; + } + + fseek(NewFvFile,0,SEEK_SET); + fseek(NewFvFile,0,SEEK_END); + + NewFvLength =3D ftell(NewFvFile); + fseek(NewFvFile,0,SEEK_SET); + Buffer =3D malloc ((size_t)NewFvLength); + if (Buffer =3D=3D NULL) { + Status =3D EFI_ABORTED; + fclose(NewFvFile); + goto FAILED; + } + + if (fread (Buffer, 1, (size_t) NewFvLength, NewFvFile) !=3D (s= ize_t) NewFvLength) { + Error ("FMMT", 0, 0003, "error reading FV file %s", Output= FileName->FFSName); + free (Buffer); + Status =3D EFI_ABORTED; + fclose(NewFvFile); + goto FAILED; + } + + if (NewFvLength <=3D FvInFd->FvHeader->FvLength) { + memcpy(FdBuffer+FvInFd->ImageAddress,Buffer,(size_t) NewFv= Length); + } else { + Error ("FMMT", 0, 0004, "error writing FD file", "The add = ffs file is too large."); + } + fclose(NewFvFile); + free(Buffer); + } + } + + Status =3D LibRmDir(TemDir); + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0004, "error while encapsulate FD Image", "remove= directory failed!"); + goto FAILED; + } + + NewFdFile =3D fopen(FdOutName, "wb"); + if (NewFdFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while encapsulate FD Image", "Cannot= open target FD file!"); + Status =3D EFI_ABORTED; + goto FAILED; + } + + fwrite(FdBuffer, 1, FdSize, NewFdFile); + fclose(NewFdFile); + free(FdBuffer); + free(InputFfs); + printf ("Create New FD file successfully. \n\nDone! \n"); + return EFI_SUCCESS; + + FAILED: + if (FdBuffer !=3D NULL) { + free(FdBuffer); + } + if (InputFfs !=3D NULL) { + free(InputFfs); + } + return Status; +} + +/** +Delete a root FV from FD. + +@param[in] FdInName Input FD binary/image file name; +@param[in] FvName FV name; +@param[in] FdOutName Name of output fd file. + +@retval EFI_SUCCESS +@retval EFI_INVALID_PARAMETER +@retval EFI_ABORTED + +**/ +EFI_STATUS +FmmtImageDeleteFv( + IN CHAR8* FdInName, + IN CHAR8* FvName, + IN CHAR8* FdOutName +) +{ + EFI_STATUS Status; + FV_INFORMATION *FvInFd; + FILE *NewFdFile; + CHAR8 *TemDir; + + UINT8 *FdBuffer =3D NULL; + UINT8 *FdBak =3D NULL; + UINT32 FdSize =3D 0; + + FIRMWARE_DEVICE *FdData =3D NULL; + + TemDir =3D getcwd(NULL, _MAX_PATH); + if (strlen (TemDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _MAX= _PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return EFI_ABORTED; + } + strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen(TemDir) - 1); + strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen(TemDir) - 1); + + Status =3D FmmtImageView(FdInName, NULL, FALSE, &FdData); + if (EFI_ERROR(Status) && Status !=3D EFI_UNSUPPORTED) { + Error("FMMT", 0, 0004, "error while parsing FD Image", "Gathering FD i= nformation failed!"); + goto END; + } + if (FdData =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while parsing FD Image", ""); + Status =3D EFI_ABORTED; + goto END; + } + + FvInFd =3D FdData->Fv; + while (FvInFd) { + if (FvInFd->FvUiName && strcmp(FvInFd->FvUiName, FvName) =3D=3D 0) { + break; + } + FvInFd =3D FvInFd->FvNext; + } + if (!FvInFd) { + Error("FMMT", 0, 0004, "error while deleting root FV", "Cannot find th= is FV!"); + Status =3D EFI_ABORTED; + goto END; + } + FdBuffer =3D ReadFileToBuffer(FdInName, &FdSize); + FdBak =3D FdBuffer; + if (FdBuffer =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while deleting root FV", "Cannot read FD= file!"); + Status =3D EFI_ABORTED; + goto END; + } + + if (FvInFd->ImageAddress =3D=3D 0) { + FdBuffer =3D FdBuffer + FvInFd->FvHeader->FvLength; + FdSize -=3D (UINT32)FvInFd->FvHeader->FvLength; + } else { + if (FvInFd->FvHeader->Attributes & EFI_FVB2_ERASE_POLARITY) { + memset(FdBuffer + FvInFd->ImageAddress, -1, (size_t)FvInFd->FvHeader= ->FvLength); + } + else { + memset(FdBuffer + FvInFd->ImageAddress, 0, (size_t)FvInFd->FvHeader-= >FvLength); + } + } + + NewFdFile =3D fopen(FdOutName, "wb"); + if (NewFdFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while deleting root FV", "Cannot open ta= rget FD file!"); + Status =3D EFI_ABORTED; + goto END; + } + fwrite(FdBuffer, 1, FdSize, NewFdFile); + fclose(NewFdFile); + + Status =3D LibRmDir(TemDir); + + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0004, "error while deleting root FV", "remove directo= ry failed!"); + goto END; + } + + printf("Create New FD file successfully. \n\nDone! \n"); +END: + LibFmmtFreeFd(FdData); + free(FdBak); + return Status; +} + +/** + Delete an FFS file from a specify FV. + + @param[in] FdInName Input FD binary/image file name; + @param[in] FileList The FV ID and FFS file Data; + @param[in] count The length of FileList; + @param[in] FdOutName Name of output fd file. + + @retval EFI_SUCCESS + @retval EFI_INVALID_PARAMETER + @retval EFI_ABORTED + +**/ +EFI_STATUS +FmmtImageDelete ( + IN CHAR8* FdInName, + IN Data *FileList, + IN int count, + IN CHAR8* FdOutName +) +{ + EFI_STATUS Status; + FIRMWARE_DEVICE *FdData; + FV_INFORMATION *FvInFd; + UINT32 Index; + UINT32 FfsFoundFlag; + FFS_INFORMATION *OutputFileName; + FILE* NewFdFile; + FILE* NewFvFile; + UINT64 NewFvLength; + VOID* Buffer; + CHAR8 *TemDir; + UINT8 FvNumInFd; + UINT32 Offset; + UINT8 *FdBuffer; + EFI_FFS_FILE_HEADER2 *CurrentFile; + EFI_FFS_FILE_HEADER2 *PreFile; + Data *tmp; + CHAR8* FvId; + CHAR8* DelFile; + FILENode *OldFileNode; + int i; + UINT32 FfsSize; + UINT32 FdSize; + int j; + + FdSize =3D 0; + Index =3D 0; + NewFvLength =3D 0; + FfsFoundFlag =3D 0; + FdData =3D NULL; + FvInFd =3D NULL; + OutputFileName =3D NULL; + NewFdFile =3D NULL; + NewFvFile =3D NULL; + Buffer =3D NULL; + TemDir =3D NULL; + FvNumInFd =3D 0; + Offset =3D 0; + FdBuffer =3D NULL; + + for (i =3D 0; i < count; i ++){ + tmp =3D FileList + i; + FvId =3D tmp->FvId; + FdData =3D tmp->FdData; + if (FdData =3D=3D NULL) { + Status =3D FmmtImageView (FdInName, FvId, FALSE, &FdData); + if (EFI_ERROR (Status) && Status !=3D EFI_UNSUPPORTED) { + Error ("FMMT", 0, 0004, "error while parsing FD Image", "G= athering FD information failed!"); + return Status; + } + if (FdData =3D=3D NULL) { + Error ("FMMT", 0, 0004, "error while parsing FD Image", ""= ); + return EFI_ABORTED; + } + + Status =3D LibLocateFvViaFvId (FdData, FvId, &FvInFd); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0005, "error while locate FV in FD", ""); + return Status; + } + (FileList + i) -> FdData =3D FdData; + (FileList + i) -> FvInFd =3D FvInFd; + (FileList + i) -> FvLevel =3D FvInFd -> FvLevel; + } + FvNumInFd =3D ((UINT8)atoi(FvId + 2) - (UINT8)atoi(FvInFd->FvName = + 2)) + 1; + OldFileNode =3D tmp-> OldFile; + do { + DelFile =3D OldFileNode->FileName; + if (FvInFd =3D=3D NULL) { + break; + } + FfsFoundFlag =3D FindFile(FvInFd, FvNumInFd, DelFile, &Index); + if (FfsFoundFlag) { + if (FfsFoundFlag > 1) { + printf("Duplicated file found in this FV, file name: %= s\n", DelFile); + return EFI_ABORTED; + } + } else { + printf ("Could not found the FFS file from FD!, file name:= %s\n", DelFile); + return EFI_ABORTED; + } + OldFileNode -> SubLevel =3D FvInFd -> FfsAttuibutes[Index].Lev= el; + OldFileNode =3D OldFileNode->Next; + } while (OldFileNode !=3D NULL); + } + + for (i =3D 0; i < count; i++) { + for (j =3D i + 1; j < count; j++) + { + if (((FileList + i)->FvId =3D=3D NULL) || ((FileList + j)->FvI= d =3D=3D NULL)) { + continue; + } + if (strcmp((FileList + j)->FvId, (FileList + i)->FvInFd->FvNam= e) =3D=3D 0){ + OldFileNode =3D (FileList + j)->OldFile; + while (OldFileNode ->Next !=3D NULL) { + OldFileNode =3D OldFileNode->Next; + } + OldFileNode->Next =3D (FileList + i)->OldFile; + (FileList + i)->FvId =3D NULL; + } + } + } + + for (i =3D 0; i < count; i ++){ + if ((FileList + i)->FvId =3D=3D NULL) { + continue; + } + sortList ((FileList + i)-> OldFile); + } + + TemDir =3D getcwd(NULL, _MAX_PATH); + if (strlen (TemDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _M= AX_PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return EFI_ABORTED; + } + strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen(TemDir) - 1); + strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen(TemDir) - 1); + + if (FdBuffer =3D=3D NULL) { + FdBuffer =3D ReadFileToBuffer(FdInName, &FdSize); + if (FdBuffer =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while deleting file", "cannot re= ad input file."); + return EFI_ABORTED; + } + } + + for (i =3D 0; i < count; i ++){ + tmp =3D FileList + i; + FvId =3D tmp->FvId; + if (FvId =3D=3D NULL) { + continue; + } + FdData =3D tmp->FdData; + FvInFd =3D tmp->FvInFd; + FvNumInFd =3D ((UINT8)atoi(FvId + 2) - (UINT8)atoi(FvInFd->FvName = + 2)) + 1; + OldFileNode =3D tmp->OldFile; + DelFile =3D OldFileNode -> FileName; + FfsFoundFlag =3D FindFile(FvInFd, FvNumInFd, DelFile, &Index); + if (FfsFoundFlag && NeedNewPath(FvInFd, FvId, Index, FALSE)) { + do { + DelFile =3D OldFileNode -> FileName; + FfsFoundFlag =3D FindFile(FvInFd, FvNumInFd, DelFile, &Ind= ex); + // + // TODO: currently only root FV is handled + // + Offset =3D FvInFd->ImageAddress + FvInFd->FfsAttuibutes[In= dex].Offset; + if (FdBuffer !=3D NULL) { + CurrentFile =3D (EFI_FFS_FILE_HEADER2 *)(FdBuffer + Offs= et); + + FfsSize =3D CalcuFfsSize((EFI_FIRMWARE_VOLUME_HEADER *)(= FdBuffer + FvInFd->ImageAddress), CurrentFile); + + FindPreviousFile((EFI_FIRMWARE_VOLUME_HEADER *)(FdBuffer= + FvInFd->ImageAddress), CurrentFile, (VOID **) &PreFile); + if (PreFile !=3D NULL && PreFile->Type =3D=3D EFI_FV_FIL= ETYPE_FFS_PAD) { + FfsSize +=3D (UINT8 *)CurrentFile - (UINT8 *)PreFile; + CurrentFile =3D PreFile; + } + AddPadFile((EFI_FIRMWARE_VOLUME_HEADER *)(FdBuffer + FvI= nFd->ImageAddress), CurrentFile, FfsSize); + } + OldFileNode =3D OldFileNode -> Next; + } while (OldFileNode !=3D NULL); + } else { + do { + DelFile =3D OldFileNode -> FileName; + FfsFoundFlag =3D FindFile(FvInFd, FvNumInFd, DelFile, &Ind= ex); + + if (FfsFoundFlag) { + // + // Delete this FFS file from Current FV structure. + // + Status =3D LibFmmtDeleteFile (FvInFd->FfsAttuibutes[In= dex].FfsName); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate F= D Image", "Delete the specified file failed!"); + Error ("FMMT", 0, 0004, "Cannot find the file need= to delete", "Please check the name of the file you want to delete!"); + goto FAILED; + } + + memset(FvInFd->FfsAttuibutes[Index].FfsName, '\0', _MA= X_PATH); + FvInFd->FfsAttuibutes[Index].Level =3D 0xFF; + + // + // Since we can avoid to add NULL ffs file, at this ti= me we don't need to decrease the FFS number. + // If decrease operation executed, we should adjust th= e ffs list. It will bring in more complex. + // + //FvInFd->FfsNumbers -=3D 1; + memset(FvInFd->FfsAttuibutes[Index].UiName, '\0', _MAX= _PATH); + if (FvInFd->FfsAttuibutes[Index].FvLevel > 1) { + for (j =3D Index - 1; j >=3D 0; j--) { + if (FvInFd->FfsAttuibutes[j].FvLevel =3D=3D FvI= nFd->FfsAttuibutes[Index].FvLevel - 1) { + break; + } + } + if (Index+1 <=3D FvInFd->FfsNumbers) { + if (FvInFd->FfsAttuibutes[Index+1].FvLevel =3D= =3D FvInFd->FfsAttuibutes[Index].FvLevel + 1) { + for (j =3D Index+1; j <=3D (signed)FvInFd->Ff= sNumbers; j++) { + if (FvInFd->FfsAttuibutes[j].FvLevel > FvI= nFd->FfsAttuibutes[Index].FvLevel) { + Status =3D LibFmmtDeleteFile(FvInFd->Ff= sAttuibutes[j].FfsName); + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0004, "error while= encapsulate FD Image", "Delete the specified file failed!"); + return Status; + } + memset(FvInFd->FfsAttuibutes[j].FfsName= , '\0', _MAX_PATH); + FvInFd->FfsAttuibutes[j].Level =3D 0xFF; + } + } + } + } + } + } else { + printf ("Could not found the FFS file from FD!, file n= ame: %s\n", DelFile); + Status =3D EFI_ABORTED; + goto FAILED; + } + OldFileNode =3D OldFileNode -> Next; + + }while (OldFileNode !=3D NULL); + + mkdir(TemDir, S_IRWXU | S_IRWXG | S_IRWXO); + + Status =3D LibEncapNewFvFile (FvInFd, TemDir, NULL, 0, &Output= FileName); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image"= , "Make new FV file failed!"); + goto FAILED; + } + + NewFvFile =3D fopen (OutputFileName->FFSName, "rb+"); + if (NewFvFile =3D=3D NULL) { + Error ("FMMT", 0, 0003, "error Open FV file", "cannot Crea= te a new FD file."); + Status =3D EFI_ABORTED; + goto FAILED; + } + + fseek(NewFvFile,0,SEEK_SET); + fseek(NewFvFile,0,SEEK_END); + + NewFvLength =3D ftell(NewFvFile); + fseek(NewFvFile,0,SEEK_SET); + Buffer =3D malloc ((size_t)NewFvLength); + if (Buffer =3D=3D NULL) { + fclose(NewFvFile); + Status =3D EFI_ABORTED; + goto FAILED; + } + + if (fread (Buffer, 1, (size_t) NewFvLength, NewFvFile) !=3D (s= ize_t) NewFvLength) { + Error ("FMMT", 0, 0003, "error reading FV file %s", Output= FileName->FFSName); + fclose(NewFvFile); + free(Buffer); + Status =3D EFI_ABORTED; + goto FAILED; + } + memcpy(FdBuffer+FvInFd->ImageAddress,Buffer,(size_t) NewFvLeng= th); + free(Buffer); + fclose(NewFvFile); + } + } + + Status =3D LibRmDir(TemDir); + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0004, "error while encapsulate FD Image", "remove= directory failed!"); + goto FAILED; + } + + NewFdFile =3D fopen(FdOutName, "wb"); + if (NewFdFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while encapsulate FD Image", "Cannot o= pen target FD file!"); + Status =3D EFI_ABORTED; + goto FAILED; + } + + fwrite(FdBuffer, 1, FdSize, NewFdFile); + fclose(NewFdFile); + free(FdBuffer); + printf("Create New FD file successfully. \n\nDone! \n"); + return EFI_SUCCESS; + + FAILED: + free(FdBuffer); + return Status; +} + +/** + Replace the exist FFS file with new one from a specify FV. + + @param[in] FdInName Input FD binary/image file name; + @param[in] FileList The FV ID and FFS file Data; + @param[in] count The length of FileList; + @param[in] FdOutName Name of output fd file. + + @retval EFI_SUCCESS + @retval EFI_INVALID_PARAMETER + @retval EFI_ABORTED + +**/ +EFI_STATUS +FmmtImageReplace ( + IN CHAR8* FdInName, + IN Data *FileList, + IN int count, + IN CHAR8* FdOutName +) +{ + EFI_STATUS Status; + FIRMWARE_DEVICE *FdData; + FV_INFORMATION *FvInFd; + UINT32 Index; + UINT32 FfsFoundFlag; + FFS_INFORMATION *OutputFileName; + FILE* NewFdFile; + FILE* NewFvFile; + UINT64 NewFvLength; + VOID* Buffer; + CHAR8 *TemDir; + UINT32 Offset; + UINT8 *FdBuffer; + UINT8 FvNumInFd; + EFI_FFS_FILE_HEADER2 *CurrentFile; + EFI_FIRMWARE_VOLUME_HEADER *Fv; + UINT32 FdSize; + EFI_FFS_FILE_HEADER2 *InputFfs; + UINT32 NewFileSize; + UINT32 PadFileSize; + UINT64 BaseAddr; + UINT32 OffsetAdded; + Data *tmp; + CHAR8* FvId; + CHAR8* OldFile; + CHAR8* NewFile; + int i; + int j; + FILENode *OldFileNode; + FILENode *NewFileNode; + BOOLEAN HasUISection; + HasUISection =3D FALSE; + Index =3D 0; + NewFvLength =3D 0; + FfsFoundFlag =3D 0; + FdData =3D NULL; + FvInFd =3D NULL; + OutputFileName =3D NULL; + NewFdFile =3D NULL; + NewFvFile =3D NULL; + Buffer =3D NULL; + TemDir =3D NULL; + Offset =3D 0; + FdBuffer =3D NULL; + InputFfs =3D NULL; + BaseAddr =3D 0; + OffsetAdded =3D 0; + FdSize =3D 0; + + for (i =3D 0; i < count; i ++){ + tmp =3D FileList + i; + FvId =3D tmp->FvId; + FdData =3D tmp->FdData; + if (FdData =3D=3D NULL){ + Status =3D FmmtImageView(FdInName, FvId, FALSE, &FdData); + if (EFI_ERROR(Status) && Status !=3D EFI_UNSUPPORTED) { + Error("FMMT", 0, 0004, "error while parsing FD Image", "Ga= thering information failed!"); + return Status; + } + + if (FdData =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while parsing FD Image", ""); + return EFI_ABORTED; + } + + Status =3D LibLocateFvViaFvId(FdData, FvId, &FvInFd); + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0005, "error while locate FV in FD", ""); + return Status; + } + (FileList + i) -> FdData =3D FdData; + (FileList + i) -> FvInFd =3D FvInFd; + (FileList + i) -> FvLevel =3D FvInFd -> FvLevel; + } + FvNumInFd =3D ((UINT8)atoi(FvId + 2) - (UINT8)atoi(FvInFd->FvName = + 2)) + 1; + OldFileNode =3D tmp-> OldFile; + NewFileNode =3D tmp-> NewFile; + do { + OldFile =3D OldFileNode -> FileName; + NewFile =3D NewFileNode -> FileName; + if (FvInFd =3D=3D NULL) { + break; + } + FfsFoundFlag =3D FindFile(FvInFd, FvNumInFd, OldFile, &Index); + + if (FfsFoundFlag) { + if (FfsFoundFlag > 1) { + printf("Duplicated file found in this FV, file name: %= s\n", OldFile); + return EFI_ABORTED; + } + // + // Replace this FFS file with the new one. + // strcpy (FvInFd->FfsAttuibutes[Index].FfsName, NewFile); + } else { + printf ("Could not found the FFS file need to be replaced = from FD! file name: %s\n", OldFile); + return EFI_ABORTED; + } + OldFileNode -> SubLevel =3D FvInFd -> FfsAttuibutes[Index].Lev= el; + NewFileNode -> SubLevel =3D FvInFd -> FfsAttuibutes[Index].Lev= el; + OldFileNode =3D OldFileNode->Next; + NewFileNode =3D NewFileNode->Next; + } while (OldFileNode !=3D NULL && NewFileNode !=3D NULL); + } + + for (i =3D 0; i < count; i++) { + for (j =3D i + 1; j < count; j++) + { + if (((FileList + i)->FvId =3D=3D NULL) || ((FileList + j)->FvI= d =3D=3D NULL)) { + continue; + } + if (strcmp((FileList + j)->FvId, (FileList + i)->FvInFd->FvNam= e) =3D=3D 0){ + OldFileNode =3D (FileList + j)->OldFile; + NewFileNode =3D (FileList + j)->NewFile; + while (OldFileNode->Next !=3D NULL && NewFileNode->Next != =3D NULL) { + OldFileNode =3D OldFileNode->Next; + NewFileNode =3D NewFileNode->Next; + } + OldFileNode->Next =3D (FileList + i)->OldFile; + NewFileNode->Next =3D (FileList + i)->NewFile; + (FileList + i)->FvId =3D NULL; + } + } + } + + for (i =3D 0; i < count; i ++){ + if ((FileList + i)->FvId =3D=3D NULL) { + continue; + } + sortList ((FileList + i)-> OldFile); + sortList ((FileList + i)-> NewFile); + } + TemDir =3D getcwd (NULL, _MAX_PATH); + if (strlen (TemDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _M= AX_PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return EFI_ABORTED; + } + strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen(TemDir) - 1); + strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen(TemDir) - 1); + mkdir(TemDir, S_IRWXU | S_IRWXG | S_IRWXO); + if (FdBuffer =3D=3D NULL) { + FdBuffer =3D ReadFileToBuffer(FdInName, &FdSize); + if (FdBuffer =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while replacing file", "cannot rea= d input file."); + return EFI_ABORTED; + } + } + + for (i =3D 0; i < count; i ++){ + tmp =3D FileList + i; + FvId =3D tmp->FvId; + if (FvId =3D=3D NULL) { + continue; + } + FdData =3D tmp->FdData; + FvInFd =3D tmp->FvInFd; + FvNumInFd =3D ((UINT8)atoi(FvId + 2) - (UINT8)atoi(FvInFd->FvName = + 2)) + 1; + OldFileNode =3D tmp-> OldFile; + OldFile =3D OldFileNode -> FileName; + NewFileNode =3D tmp-> NewFile; + FfsFoundFlag =3D FindFile(FvInFd, FvNumInFd, OldFile, &Index); + + NewFile =3D NewFileNode->FileName; + InputFfs =3D (EFI_FFS_FILE_HEADER2 *)ReadFileToBuffer(NewFile, &Ne= wFileSize); + if (InputFfs =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while replacing file", "cannot r= ead input file."); + free (FdBuffer); + return EFI_ABORTED; + } + HasUISection =3D FALSE; + HasUISection =3D ParseSection(InputFfs); + if (!HasUISection) { + printf ("WARNING: The newly replace file must have a user inte= rface (UI) section, otherwise it cannot be deleted or replaced. \n"); + } + if (FfsFoundFlag && NeedNewPath(FvInFd, FvId, Index, FALSE)) { + do { + OldFile =3D OldFileNode -> FileName; + NewFile =3D NewFileNode -> FileName; + FfsFoundFlag =3D FindFile(FvInFd, FvNumInFd, OldFile, &Ind= ex); + // + // TODO: currently only root FV is handled + // + InputFfs =3D (EFI_FFS_FILE_HEADER2 *)ReadFileToBuffer(NewF= ile, &NewFileSize); + if (InputFfs =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while replacing file", "= cannot read input file."); + free (FdBuffer); + return EFI_ABORTED; + } + + Offset =3D FvInFd->ImageAddress + FvInFd->FfsAttuibutes[In= dex].Offset; + Fv =3D (EFI_FIRMWARE_VOLUME_HEADER *)(FdBuffer + FvInFd->I= mageAddress); + OffsetAdded =3D FvInFd->FfsAttuibutes[Index].Offset; + + if (!ReplaceFfs(Fv, InputFfs, (EFI_FFS_FILE_HEADER2 *)(FdB= uffer + Offset))) { + Status =3D AddFfs(FdBuffer, FvInFd->ImageAddress, Fv, In= putFfs, &OffsetAdded); + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0003, "error while replacing file", "= cannot add ffs"); + goto END; + } + // + // Set original FFS to PAD file + // + CurrentFile =3D (EFI_FFS_FILE_HEADER2 *)(FdBuffer + FvIn= Fd->ImageAddress + FvInFd->FfsAttuibutes[Index].Offset); + PadFileSize =3D CalcuFfsSize(Fv, CurrentFile); + AddPadFile(Fv, CurrentFile, PadFileSize); + } + + // + // Calculate base address of Current FV + // + if (InputFfs->Type =3D=3D EFI_FV_FILETYPE_PEIM || InputFfs= ->Type =3D=3D EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) { + Status =3D GetBaseAddrFromFsp(FdData, FdBuffer, FvId, &B= aseAddr); + if (!EFI_ERROR(Status)) { + mFvHeader =3D FvInFd->FvHeader; + mFvLength =3D (UINT32)FvInFd->FvHeader->FvLength; + RebaseFfs(BaseAddr, NewFile, (EFI_FFS_FILE_HEADER *)(F= dBuffer + FvInFd->ImageAddress + OffsetAdded), OffsetAdded); + } + else { + Status =3D GetBaseAddrFromVtf(FdData, FvId, &BaseAddr); + if (!EFI_ERROR(Status)) { + mFvHeader =3D FvInFd->FvHeader; + mFvLength =3D (UINT32)FvInFd->FvHeader->FvLength; + RebaseFfs(BaseAddr, NewFile, (EFI_FFS_FILE_HEADER *)= (FdBuffer + FvInFd->ImageAddress + OffsetAdded), OffsetAdded); + } + } + } + OldFileNode =3D OldFileNode -> Next; + NewFileNode =3D NewFileNode -> Next; + free (InputFfs); + InputFfs =3D NULL; + } while (OldFileNode !=3D NULL && NewFileNode!=3D NULL); + } else { + do { + OldFile =3D OldFileNode->FileName; + NewFile =3D NewFileNode->FileName; + FfsFoundFlag =3D FindFile(FvInFd, FvNumInFd, OldFile, &Ind= ex); + // + // Replace this FFS file with the new one. + // + if (strlen (NewFile) > _MAX_PATH - 1) { + Error ("FMMT", 0, 2000, "error while replacing file", "N= ew file name is too long!"); + free (FdBuffer); + return EFI_ABORTED; + } + strncpy(FvInFd->FfsAttuibutes[Index].FfsName, NewFile, _MA= X_PATH - 1); + FvInFd->FfsAttuibutes[Index].FfsName[_MAX_PATH - 1] =3D 0; + OldFileNode =3D OldFileNode->Next; + NewFileNode =3D NewFileNode->Next; + } while (OldFileNode !=3D NULL && NewFileNode !=3D NULL); + Status =3D LibEncapNewFvFile (FvInFd, TemDir, NULL, 0, &Output= FileName); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image"= , "Make new FV file failed!"); + free (FdBuffer); + return Status; + } + + NewFvFile =3D fopen (OutputFileName->FFSName, "rb+"); + if (NewFvFile =3D=3D NULL) { + Error ("FMMT", 0, 0003, "error Open FV file", "cannot Crea= te a new FD file."); + free (FdBuffer); + return EFI_ABORTED; + } + + fseek(NewFvFile,0,SEEK_SET); + fseek(NewFvFile,0,SEEK_END); + + NewFvLength =3D ftell(NewFvFile); + fseek(NewFvFile,0,SEEK_SET); + Buffer =3D malloc ((size_t)NewFvLength); + if (Buffer =3D=3D NULL) { + fclose(NewFvFile); + free (FdBuffer); + return EFI_ABORTED; + } + + if (fread (Buffer, 1, (size_t) NewFvLength, NewFvFile) !=3D (s= ize_t) NewFvLength) { + Error ("FMMT", 0, 0003, "error reading FV file %s", Output= FileName->FFSName); + free(Buffer); + free (FdBuffer); + fclose(NewFvFile); + return EFI_ABORTED; + } + if (NewFvLength <=3D FvInFd->FvHeader->FvLength) { + memcpy(FdBuffer+FvInFd->ImageAddress,Buffer,(size_t) NewFv= Length); + }else { + Error ("FMMT", 0, 0004, "error writing FD file", "The repl= ace ffs file is too large."); + } + free(Buffer); + fclose(NewFvFile); + } + } + + Status =3D LibRmDir(TemDir); + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0004, "error while encapsulate FD Image", "remove d= irectory failed!"); + } + + NewFdFile =3D fopen(FdOutName, "wb"); + if (NewFdFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "error while replacing file", "Cannot open ta= rget FD file!"); + Status =3D EFI_ABORTED; + goto END; + } + fwrite(FdBuffer, 1, FdSize, NewFdFile); + fclose(NewFdFile); + free(FdBuffer); + printf("Create New FD file successfully. \n\nDone! \n"); + return EFI_SUCCESS; + + END: + if (FdBuffer !=3D NULL) { + free(FdBuffer); + } + if (InputFfs !=3D NULL) { + free(InputFfs); + } + return EFI_ABORTED; +} + +/** + +The main entry of FMMT. + +@param argc The number of input parameters. +@param *argv[] The array pointer to the parameters. + +@retval 0 The application exited normally. +@retval 1 An error occurred. + +**/ +int main( + int Argc, + char *Argv[] +) +{ + EFI_STATUS Status; + CHAR8 *TemDir; + FILE *CheckFileExist; + CHAR8 *InFilePath; + CHAR8 FullGuidToolDefinition[_MAX_PATH]; + CHAR8 *FileName; + UINTN FileNameIndex; + CHAR8 *PathList; + UINTN EnvLen; + CHAR8 *NewPathList; + Data *FileData; + int index; + int count; + int exist; + int j; + FILENode *p; + FILENode *q; + + p =3D NULL; + q =3D NULL; + TemDir =3D NULL; + CheckFileExist =3D NULL; + PathList =3D NULL; + NewPathList =3D NULL; + EnvLen =3D 0; + count =3D 0; + exist =3D -1; + + TemDir =3D getcwd (NULL, _MAX_PATH); + if (strlen (TemDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _MAX= _PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return 1; + } + strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen(TemDir) - 1); + strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen(TemDir) - 1); + + // + // Print utility header + // + printf ("Intel(R) %s. Version %d.%d, %s. %s.\n", + UTILITY_NAME, + UTILITY_MAJOR_VERSION, + UTILITY_MINOR_VERSION, + __DATE__, + __BUILD_VERSION + ); + + // + // Should have more than 1 arguments. + // + if (Argc <=3D 1) { + Usage(); + return 1; + } + + // + // Workaroud: the first call to this function + // returns a file name ends with dot + // +#ifndef __GNUC__ + tmpnam (NULL); +#else + CHAR8 tmp[] =3D "/tmp/fileXXXXXX"; + UINTN Fdtmp; + Fdtmp =3D mkstemp(tmp); + close(Fdtmp); +#endif + + // + // Save, skip filename arg + // + FileName =3D Argv[0]; + Argc--; + Argv++; + + // + // Get the same path with the application itself + // + if (strlen (FileName) > _MAX_PATH - 1) { + Error ("FMMT", 0, 2000, "Parameter: The input filename is too long", N= ULL); + return 1; + } + strncpy (FullGuidToolDefinition, FileName, _MAX_PATH - 1); + FullGuidToolDefinition[_MAX_PATH - 1] =3D 0; + FileNameIndex =3D strlen (FullGuidToolDefinition); + while (FileNameIndex !=3D 0) { + FileNameIndex --; + if (FullGuidToolDefinition[FileNameIndex] =3D=3D OS_SEP) { + FullGuidToolDefinition[FileNameIndex] =3D 0; + break; + } + } + // + // Build the path list for Config file scan. The priority is below. + // 1. Scan the current path + // 2. Scan the same path with the application itself + // 3. Scan the current %PATH% of OS environment + // 4. Use the build-in default configuration + // + PathList =3D getenv("PATH"); + if (PathList =3D=3D NULL) { + Error (NULL, 0, 1001, "Option: Environment variable 'PATH' does not ex= ist", NULL); + return 1; + } + EnvLen =3D strlen(PathList); + NewPathList =3D (char *)calloc( + strlen (".") + + strlen (";") + + strlen (FullGuidToolDefinition) + + strlen (";") + + EnvLen + + 1, + sizeof(char) + ); + if (NewPathList =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + PathList =3D NULL; + free (PathList); + return 1; + } +#ifndef __GNUC__ + sprintf (NewPathList, "%s;%s;%s", ".", FullGuidToolDefinition, PathList); +#else + sprintf (NewPathList, "%s:%s:%s", ".", FullGuidToolDefinition, PathList); +#endif + PathList =3D NULL; + free (PathList); + + // + // Load Guid Tools definition + // + InFilePath =3D SearchConfigFromPathList(NewPathList, mGuidToolDefinition= ); + free (NewPathList); + if (InFilePath !=3D NULL) { + printf ("\nThe Guid Tool Definition comes from the '%s'. \n", InFilePa= th); + mParsedGuidedSectionTools =3D ParseGuidedSectionToolsFile (InFilePath); + free (InFilePath); + } else { + // + // Use the pre-defined standard guided tools. + // + printf ("\nThe Guid Tool Definition comes from the build-in default conf= iguration. \n"); + mParsedGuidedSectionTools =3D LibPreDefinedGuidedTools (); + } + + if ((strcmp(Argv[0], "-v") =3D=3D 0) || (strcmp(Argv[0], "-V") =3D=3D 0)= ) { + // + // View the FD binary image information. + // + if (Argc <=3D 1) { + Error("FMMT", 0, 1001, "Invalid parameter, Please make sure the para= meter is correct.", ""); + Usage (); + return 1; + } + + // + // Open the file containing the FV to check whether it exist or not + // + CheckFileExist =3D fopen (Argv[1], "rb"); + if (CheckFileExist =3D=3D NULL) { + Error ("FMMT", 0, 0001, "Error opening the input binary file, Please= make sure the exist!", Argv[1]); + return 1; + } + fclose(CheckFileExist); + + Status =3D FmmtImageView(Argv[1], NULL, TRUE, NULL); + + if (EFI_ERROR (Status)) { + Error("FMMT", 0, 1001, "Error while view the FD image file.", ""); + LibRmDir (TemDir); + return 1; + } + + } else if ((strcmp(Argv[0], "-d") =3D=3D 0) || (strcmp(Argv[0], "-D") = =3D=3D 0)) { + // + // Delete some named FFS file from FD binary image. + // + if (!((Argc =3D=3D 4) || ((Argc - 3) % 2 =3D=3D 0))) { + Error("FMMT", 0, 1001, "Invalid parameter, Please make sure the par= ameter is correct.", ""); + Usage (); + return 1; + } + + // + // Open the file containing the FV to check whether it exist or not + // + CheckFileExist =3D fopen (Argv[1], "rb"); + if (CheckFileExist =3D=3D NULL) { + Error ("FMMT", 0, 0001, "Error opening the input binary file, Please= make sure the exist!", Argv[1]); + return 1; + } + fclose(CheckFileExist); + + if ((Argc - 3) % 2 =3D=3D 0) { + FileData =3D malloc(sizeof (Data) * (Argc - 3)/2); + if (FileData =3D=3D NULL) { + Error ("FMMT", 0, 4001, "Resource: Memory can't be allocated", N= ULL); + return 1; + } + for(index =3D 0; index < (Argc - 3)/2; index ++) { + p =3D malloc(sizeof (FILENode)); + if (p =3D=3D NULL) { + Error ("FMMT", 0, 4001, "Resource: Memory can't be allocated= ", NULL); + free (FileData); + return 1; + } + p -> FileName =3D Argv[3 + index * 2]; + p -> SubLevel =3D 0; + exist =3D -1; + for (j =3D 0; j < count; j ++) { + if ((strcmp(Argv[2 + index * 2], (FileData + j) -> FvId) = =3D=3D 0)) { + exist =3D j; + break; + } + } + if (exist >=3D 0) { + p -> Next =3D (FileData + j) -> OldFile; + (FileData + j) -> OldFile =3D p; + } else { + (FileData + count) -> NewFile =3D NULL; + (FileData + count) -> FdData =3D NULL; + (FileData + count) -> FvLevel =3D 0; + (FileData + count) -> FvInFd =3D NULL; + (FileData + count) -> FvId =3D Argv[2 + index * 2];; + (FileData + count) -> OldFile =3D p; + p -> Next =3D NULL; + count ++; + } + } + + if (count <=3D 0) { + Error("FMMT", 0, 0004, "error while parsing FD Image", "Gather= ing information failed!"); + } + for (index =3D 0; index < count; index ++) { + for (j =3D index + 1; j < count; j ++) { + if ((strcmp((FileData + index)->FvId, (FileData + j)->FvId= ) < 0)) { + CHAR8 *tmp =3D (FileData + index)->FvId; + FILENode *t =3D (FileData + index)->OldFile; + (FileData + index)->FvId =3D (FileData + j)->FvId; + (FileData + index)-> OldFile =3D (FileData + j)->OldFi= le; + (FileData + j)-> OldFile =3D t; + (FileData + j)-> FvId =3D tmp; + } + } + } + + // + // Delete some FFS file + // + Status =3D FmmtImageDelete(Argv[1], FileData, count, Argv[Argc-1]); + for (index =3D 0; index < count; index ++) { + if ((FileData + index) ->NewFile !=3D NULL) { + free ((FileData + index)->NewFile); + (FileData + index)->NewFile =3D NULL; + } + if ((FileData + index)->OldFile !=3D NULL) { + free ((FileData + index)->OldFile); + (FileData + index)->OldFile =3D NULL; + } + } + for (index =3D 0; index < count; index ++) { + if ((FileData + index)->FdData !=3D NULL) { + LibFmmtFreeFd ((FileData + index)->FdData); + } + } + free (FileData); + if (EFI_ERROR (Status)) { + Error("FMMT", 0, 1001, "Error while delete some named ffs fil= e from the FD image file.", ""); + LibRmDir (TemDir); + return 1; + } + } else { + // + // Delete FV + // + Status =3D FmmtImageDeleteFv(Argv[1], Argv[2], Argv[3]); + if (EFI_ERROR (Status)) { + Error("FMMT", 0, 1001, "Error while delete the entire FV from= the FD image file.", ""); + LibRmDir (TemDir); + return 1; + } + } + + } else if ((strcmp(Argv[0], "-a") =3D=3D 0) || (strcmp(Argv[0], "-A") = =3D=3D 0)) { + // + // Add some named FFS file into FD binary image. + // + if ((Argc - 3 ) % 2 !=3D 0) { + Error("FMMT", 0, 1001, "Invalid parameter, Please make sure the par= ameter is correct.", ""); + Usage (); + return 1; + } + + // + // Open the file containing the FV to check whether it exist or not + // + CheckFileExist =3D fopen (Argv[1], "rb"); + if (CheckFileExist =3D=3D NULL) { + Error ("FMMT", 0, 0001, "Error opening the input binary file, Please= make sure the exist!", Argv[1]); + return 1; + } + fclose(CheckFileExist); + + // + // Check whether the new added file exist or not. + // + for (index =3D 1; index < (Argc - 1) / 2; index ++) { + CheckFileExist =3D fopen(Argv[2 * index + 1], "rb"); + if (CheckFileExist =3D=3D NULL) { + Error("FMMT", 0, 0001, "Could not open the new FFS file, Pleas= e make sure the new FFS file exist.", Argv[2 * index + 1]); + return 1; + } + fclose(CheckFileExist); + } + + FileData =3D malloc(sizeof (Data) * (Argc - 3)/2); + if (FileData =3D=3D NULL) { + Error ("FMMT", 0, 4001, "Resource: Memory can't be allocated", NULL); + return 1; + } + for(index =3D 0; index < (Argc - 3)/2; index ++) { + p =3D malloc(sizeof (FILENode)); + if (p =3D=3D NULL) { + Error ("FMMT", 0, 4001, "Resource: Memory can't be allocated", N= ULL); + free (FileData); + return 1; + } + p -> FileName =3D Argv[3 + index * 2]; + p -> SubLevel =3D 0; + exist =3D -1; + for (j =3D 0; j < count; j ++) { + if ((strcmp(Argv[2 + index * 2], (FileData + j) -> FvId) =3D= =3D 0)) { + exist =3D j; + break; + } + } + if (exist >=3D 0) { + p -> Next =3D (FileData + j) -> NewFile; + (FileData + j) -> NewFile =3D p; + } else { + (FileData + count) -> OldFile =3D NULL; + (FileData + count) -> FdData =3D NULL; + (FileData + count) -> FvLevel =3D 0; + (FileData + count) -> FvInFd =3D NULL; + (FileData + count) -> FvId =3D Argv[2 + index * 2]; + (FileData + count) -> NewFile =3D p; + p -> Next =3D NULL; + count ++; + } + } + + if (count <=3D 0) { + Error("FMMT", 0, 0004, "error while parsing FD Image", "Gathering = information failed!"); + } + + for (index =3D 0; index < count; index ++) { + for (j =3D index + 1; j < count; j ++) { + if ((strcmp((FileData + index)->FvId, (FileData + j)->FvId) < 0)) { + CHAR8 *tmp =3D (FileData + index)->FvId; + FILENode *temp =3D (FileData + index)->NewFile; + (FileData + index)->FvId =3D (FileData + j)->FvId; + (FileData + index)-> NewFile =3D (FileData + j)->NewFile; + (FileData + j)-> NewFile =3D temp; + (FileData + j)-> FvId =3D tmp; + } + } + } + + Status =3D FmmtImageAdd(Argv[1], FileData, count, Argv[Argc-1]); + for (index =3D 0; index < count; index ++) { + if ((FileData + index)->NewFile !=3D NULL) { + free ((FileData + index)->NewFile); + (FileData + index)->NewFile =3D NULL; + } + if ((FileData + index)->OldFile !=3D NULL) { + free ((FileData + index)->OldFile); + (FileData + index)->OldFile =3D NULL; + } + } + for (index =3D 0; index < count; index ++) { + if ((FileData + index)->FdData !=3D NULL) { + LibFmmtFreeFd ((FileData + index)->FdData); + } + } + free (FileData); + + if (EFI_ERROR (Status)) { + Error("FMMT", 0, 1001, "Error while add some named ffs file into th= e FD image file.", ""); + LibRmDir (TemDir); + return 1; + } + + } else if ((strcmp(Argv[0], "-r") =3D=3D 0) || (strcmp(Argv[0], "-R") = =3D=3D 0)) { + // + // Replace some named FFS file in the FD binary. + // + if ((Argc - 3) % 3 !=3D 0) { + Error("FMMT", 0, 1001, "Invalid parameter, Please make sure the par= ameter is correct.", ""); + Usage(); + return 1; + } + + // + // Open the file containing the FV to check whether it exist or not + // + CheckFileExist =3D fopen (Argv[1], "rb"); + if (CheckFileExist =3D=3D NULL) { + Error ("FMMT", 0, 0001, "Error opening the input binary file, Please= make sure the exist!", Argv[1]); + return 1; + } + fclose(CheckFileExist); + + // + // Check whether the new FFS file exist or not. + // + for (index =3D 1; index < Argc/3; index ++) { + CheckFileExist =3D fopen(Argv[3 * index + 1], "rb"); + if (CheckFileExist =3D=3D NULL) { + Error ("FMMT", 0, 0001, "Could not open the new FFS file, Plea= se make sure the new FFS file exist.", Argv[3 * index + 1]); + return 1; + } + fclose(CheckFileExist); + } + + FileData =3D malloc(sizeof (Data) * (Argc - 3)/3); + if (FileData =3D=3D NULL) { + Error ("FMMT", 0, 4001, "Resource: Memory can't be allocated", NULL); + return 1; + } + for(index =3D 0; index < (Argc - 3)/3; index ++) { + p =3D malloc(sizeof (FILENode)); //p for old file + if (p =3D=3D NULL) { + Error ("FMMT", 0, 4001, "Resource: Memory can't be allocated", N= ULL); + free (FileData); + return 1; + } + q =3D malloc(sizeof (FILENode)); //q for new file + if (q =3D=3D NULL) { + Error ("FMMT", 0, 4001, "Resource: Memory can't be allocated", N= ULL); + free (FileData); + free (p); + return 1; + } + p -> FileName =3D Argv[3 + index * 3]; + q -> FileName =3D Argv[4 + index * 3]; + p -> SubLevel =3D 0; + q -> SubLevel =3D 0; + exist =3D -1; + for (j =3D 0; j < count; j ++) { + if ((strcmp(Argv[2 + index * 3], (FileData + j) -> FvId) =3D= =3D 0)) { + exist =3D j; + break; + } + } + if (exist >=3D 0) { + p -> Next =3D (FileData + j) -> OldFile; + (FileData + j) -> OldFile =3D p; + q -> Next =3D (FileData + j) -> NewFile; + (FileData + j) -> NewFile =3D q; + } else { + (FileData + count) -> FdData =3D NULL; + (FileData + count) -> FvLevel =3D 0; + (FileData + count) -> FvInFd =3D NULL; + (FileData + count) -> FvId =3D Argv[2 + index * 3];; + (FileData + count) -> OldFile =3D p; + (FileData + count) -> NewFile =3D q; + p -> Next =3D NULL; + q -> Next =3D NULL; + count ++; + } + } + + if (count <=3D 0) { + Error("FMMT", 0, 0004, "error while parsing FD Image", "Gathering = information failed!"); + } + for (index =3D 0; index < count; index ++) { + for (j =3D index + 1; j < count; j ++) { + if ((strcmp((FileData + index)->FvId, (FileData + j)->FvId) < = 0)) { + CHAR8 *tmp =3D (FileData + index)->FvId; + FILENode *Old =3D (FileData + index)->OldFile; + FILENode *New =3D (FileData + index)->NewFile; + (FileData + index)->FvId =3D (FileData + j)->FvId; + (FileData + index)->OldFile =3D (FileData + j)->OldFile; + (FileData + index)->NewFile =3D (FileData + j)->NewFile; + (FileData + j)->OldFile =3D Old; + (FileData + j)->NewFile =3D New; + (FileData + j)->FvId =3D tmp; + } + } + } + + Status =3D FmmtImageReplace(Argv[1], FileData, count, Argv[Argc-1]); + for (index =3D 0; index < count; index ++) { + if ((FileData + index)->NewFile !=3D NULL) { + free ((FileData + index)->NewFile); + (FileData + index)->NewFile =3D NULL; + } + if ((FileData + index)->OldFile !=3D NULL) { + free ((FileData + index)->OldFile); + (FileData + index)->OldFile =3D NULL; + } + } + for (index =3D 0; index < count; index ++) { + if ((FileData + index)->FdData !=3D NULL) { + LibFmmtFreeFd ((FileData + index)->FdData); + } + } + free (FileData); + if (EFI_ERROR (Status)) { + Error("FMMT", 0, 1001, "Error while replace the named ffs file in t= he FD image file with the new ffs file.", ""); + LibRmDir (TemDir); + return 1; + } + + } else if ((strcmp(Argv[0], "-h") =3D=3D 0) || (strcmp(Argv[0], "--help"= ) =3D=3D 0) || + (strcmp(Argv[0], "-?") =3D=3D 0) || (strcmp(Argv[0], "/?") = =3D=3D 0)) { + // + // print help information to user. + // + Usage(); + + } else { + // + // Invalid parameter. + // + printf("\n"); + Error("FMMT", 0, 1001, "Invalid parameter", Argv[0]); + Usage(); + return 1; + } + + return 0; +} + diff --git a/Platform/Intel/Tools/FMMT/FirmwareModuleManagement.h b/Platfor= m/Intel/Tools/FMMT/FirmwareModuleManagement.h new file mode 100644 index 0000000000..ec8e3eaba0 --- /dev/null +++ b/Platform/Intel/Tools/FMMT/FirmwareModuleManagement.h @@ -0,0 +1,479 @@ +/** @file + + Structures and functions declaration. + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _BIN_FILE_MANAGER_ +#define _BIN_FILE_MANAGER_ + +#include +#include +#include +#ifdef __GNUC__ +#include +#else +#include +#include +#endif +#include +#include +#include +#include +#include + +#include "CommonLib.h" +#include "EfiUtilityMsgs.h" +#include "ParseInf.h" +#include "ParseGuidedSectionTools.h" +#include "StringFuncs.h" +#include "Compress.h" +#include "Decompress.h" + +#ifndef _MAX_PATH +#define _MAX_PATH 500 +#endif + +#if defined(_MSC_VER) && _MSC_VER < 1900 +#define snprintf _snprintf +#endif + +#ifdef __GNUC__ +#define OS_SEP '/' +#define OS_SEP_STR "/" +#define COPY_STR "cp \"%s\" \"%s\" > /dev/null" +#define RMDIR_STR "rm -r \"%s\" > /dev/null" +#define DEL_STR "rm \"%s\" > /dev/null" +#else +#define OS_SEP '\\' +#define OS_SEP_STR "\\" +#define COPY_STR "copy \"%s\" \"%s\" > NUL" +#define RMDIR_STR "rmdir /S /Q \"%s\" > NUL" +#define DEL_STR "del \"%s\" > NUL" +#endif + +#define UTILITY_NAME "Firmware Module Management Tool(FMMT)" +#define UTILITY_SHORT_NAME "FMMT" +#define UTILITY_MAJOR_VERSION 0 +#define UTILITY_MINOR_VERSION 23 +#define MAX_BASENAME_LEN 60 // not good to HardCode, but let's = be reasonable +#define EFI_SECTION_ERROR EFIERR (100) +// +// 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 sections in an FFS file. +// +#define MAX_NUMBER_OF_SECTION_IN_FFS 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 + + + +/// +/// If present, this must be the first and only opcode, +/// EFI_DEP_BEFORE is only used by DXE driver. +/// +#define EFI_DEP_BEFORE 0x00 + +/// +/// If present, this must be the first and only opcode, +/// EFI_DEP_AFTER is only used by DXE driver. +/// +#define EFI_DEP_AFTER 0x01 + +#define EFI_DEP_PUSH 0x02 +#define EFI_DEP_AND 0x03 +#define EFI_DEP_OR 0x04 +#define EFI_DEP_NOT 0x05 +#define EFI_DEP_TRUE 0x06 +#define EFI_DEP_FALSE 0x07 +#define EFI_DEP_END 0x08 + + +/// +/// If present, this must be the first opcode, +/// EFI_DEP_SOR is only used by DXE driver. +/// +#define EFI_DEP_SOR 0x09 + +// +// INF file strings +// +#define OPTIONS_SECTION_STRING "[options]" +#define ATTRIBUTES_SECTION_STRING "[attributes]" +#define FILES_SECTION_STRING "[files]" +#define FV_BASE_ADDRESS_STRING "[FV_BASE_ADDRESS]" + +// +// 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_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" + + +typedef UINT32 FMMT_ENCAP_TYPE; + +#define MAX_LEVEL_IN_FV_FILE 32 + +// +// Types of FMMT_ENCAP_TREENODE_TYPE +// +#define FMMT_ENCAP_TREE_FV 0x1 +#define FMMT_ENCAP_TREE_FFS 0x2 +#define FMMT_ENCAP_TREE_GUIDED_SECTION 0x3 +#define FMMT_ENCAP_TREE_COMPRESS_SECTION 0x4 +#define FMMT_ENCAP_TREE_FV_SECTION 0x5 + +extern EFI_HANDLE mParsedGuidedSectionTools; + + +#define TEMP_DIR_NAME "FmmtTemp" + +// +// Structure to keep a list of GUID-To-BaseNames +// +typedef struct _GUID_TO_BASENAME { + struct _GUID_TO_BASENAME *Next; + INT8 Guid[PRINTED_GUID_BUFFER_SIZE]; + INT8 BaseName[MAX_BASENAME_LEN]; +} GUID_TO_BASENAME; + + +typedef struct _GUID_SEC_TOOL_ENTRY { + EFI_GUID Guid; + CHAR8* Name; + CHAR8* Path; + struct _GUID_SEC_TOOL_ENTRY *Next; +} GUID_SEC_TOOL_ENTRY; + + +// +// Private data types +// +// +// Component information +// +typedef struct { + UINTN Size; + CHAR8 ComponentName[_MAX_PATH]; +} COMPONENT_INFO; + +typedef struct { + CHAR8 FfsName[_MAX_PATH]; + + // + // UI Name for this FFS file, if has. + // + CHAR16 UiName[_MAX_PATH]; + UINT32 UiNameSize; + // + // Total section number in this FFS. + // + UINT32 TotalSectionNum; + + // + // Describe the position of the FFS file. + // + UINT8 Level; + // + // If this FFS has no encapsulate section, this flag will set to True. + // + BOOLEAN IsLeaf; + // + // Section type for each section in FFS. + // + EFI_SECTION_TYPE SectionType[MAX_NUMBER_OF_SECTION_IN_FFS]; + // + // Offset relative to current FV + // + UINT32 Offset; + UINT8 FvLevel; + EFI_GUID GuidName; + UINT8 *Depex; + UINT32 DepexLen; + BOOLEAN IsHandle; + BOOLEAN IsFvStart; + BOOLEAN IsFvEnd; +}FFS_ATTRIBUTES; + + +typedef struct __ENCAP_INFO_DATA{ + // + // Now Level + // + UINT8 Level; + + // + // Encapsulate type. + // + FMMT_ENCAP_TYPE Type; + + // + // Data, if it's FV, should be FV header. + // + VOID *Data; + + // + //FvId, match FvId with FvGuidName. + // + UINT8 FvId; + + // + // if FV ExtHeaderOffset not to zero, should also have FvExtHeader infor= mation + // + EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader; + + CHAR16 UiName[_MAX_PATH]; + UINT32 UiNameSize; + UINT8 *Depex; + UINT32 DepexLen; + + // + // Next node. + // + struct __ENCAP_INFO_DATA *NextNode; + + // + // Right node. + // + struct __ENCAP_INFO_DATA *RightNode; +} ENCAP_INFO_DATA; + +typedef struct _FFS_INFOMATION{ + CHAR8 *FFSName; + UINT32 InFvId; + UINT8 ParentLevel; + BOOLEAN IsFFS; + CHAR16 UiName[_MAX_PATH]; + UINT32 UiNameSize; + UINT8 *Depex; + UINT32 DepexLen; + BOOLEAN FfsFoundFlag; + struct _FFS_INFOMATION *Next; +} FFS_INFORMATION; + +// +// FV and capsule information holder +// +typedef struct _FV_INFOMATION{ + EFI_FIRMWARE_VOLUME_HEADER *FvHeader; + EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader; + UINT32 ImageAddress; + UINT32 FfsNumbers; + CHAR8 FvName[_MAX_PATH]; + EFI_FV_BLOCK_MAP_ENTRY FvBlocks[MAX_NUMBER_OF_FV_BLOCKS]; + FFS_ATTRIBUTES FfsAttuibutes[MAX_NUMBER_OF_FILES_IN_FV]; + EFI_FFS_FILE_HEADER2 FfsHeader[MAX_NUMBER_OF_FILES_IN_FV]; + struct _FV_INFOMATION *FvNext; + ENCAP_INFO_DATA *EncapData; + UINT8 FvLevel; + CHAR8 *FvUiName; + UINT8 MulFvLevel; + CHAR8 AlignmentStr[16]; + FFS_INFORMATION *ChildFvFFS; +} FV_INFORMATION; + +typedef struct _FIRMWARE_DEVICE { + /// + /// Size of FD file + /// + UINT32 Size; + FV_INFORMATION *Fv; +} FIRMWARE_DEVICE; + +typedef struct _FILENode { + CHAR8 *FileName; + UINT8 SubLevel; + struct _FILENode *Next; +} FILENode; + +typedef struct { + CHAR8 *FvId; + FILENode *NewFile; + FILENode *OldFile; + FIRMWARE_DEVICE *FdData; + UINT8 FvLevel; + FV_INFORMATION *FvInFd; +} Data; + +EFI_STATUS +LibFindFvInFd ( + IN FILE *InputFile, + IN OUT FIRMWARE_DEVICE **FdData +); + +/** + + TODO: Add function description + + @param[in] Fv - Firmware Volume to get information from + + @return EFI_STATUS + +**/ +EFI_STATUS +LibGetFvInfo ( + IN VOID *Fv, + IN OUT FV_INFORMATION *CurrentFv, + IN CHAR8 *FvName, + IN UINT8 Level, + IN ENCAP_INFO_DATA **CurrentFvEncapData, + IN UINT32 *FfsCount, + IN OUT UINT8 *FvCount, + IN BOOLEAN ViewFlag, + IN BOOLEAN IsChildFv + ); + +/* + Get size info from FV file. + + @param[in] + @param[out] + + @retval + +*/ +EFI_STATUS +LibGetFvSize ( + IN FILE *InputFile, + OUT UINT32 *FvSize + ); + + /** + + This function returns the next larger size that meets the alignment + requirement specified. + + @param[in] ActualSize The size. + @param[in] Alignment The desired alignment. + + @retval EFI_SUCCESS Function completed successfully. + @retval EFI_ABORTED The function encountered an error. + +**/ +UINT32 +GetOccupiedSize ( + IN UINT32 ActualSize, + IN UINT32 Alignment + ); + +/** + Converts ASCII characters to Unicode. + Assumes that the Unicode characters are only these defined in the ASCII = set. + + String - Pointer to string that is written to FILE. + UniString - Pointer to unicode string + + The address to the ASCII string - same as AsciiStr. + +**/ +VOID +LibAscii2Unicode ( + IN CHAR8 *String, + OUT CHAR16 *UniString + ); + +/** + Delete a directory and files in it. + + @param[in] DirName Name of the directory need to be deleted. + + @return EFI_INVALID_PARAMETER + @return EFI_SUCCESS +**/ +EFI_STATUS +LibRmDir ( + IN CHAR8* DirName + ); + +/** + Delete a file. + + @param[in] FileName Name of the file need to be deleted. + + @return EFI_INVALID_PARAMETER + @return EFI_SUCCESS +**/ +EFI_STATUS +LibFmmtDeleteFile( + IN CHAR8 *FileName +); + + +/** + + Free the whole Fd data structure. + + @param[in] Fd The pointer point to the Fd data structure. + +**/ +VOID +LibFmmtFreeFd ( + FIRMWARE_DEVICE *Fd +); + + +EFI_STATUS +LibEncapNewFvFile( + IN FV_INFORMATION *FvInFd, + IN CHAR8 *TemDir, + IN ENCAP_INFO_DATA *CurrentEncapData, + IN UINT32 Level_Break, + OUT FFS_INFORMATION **OutputFile +); + + +EFI_STATUS +LibLocateFvViaFvId ( + IN FIRMWARE_DEVICE *FdData, + IN CHAR8 *FvId, + IN OUT FV_INFORMATION **FvInFd +); + +EFI_HANDLE +LibPreDefinedGuidedTools ( + VOID +); + +EFI_STATUS +FvBufGetSize( +IN VOID *Fv, +OUT UINTN *Size +); + +EFI_STATUS +FvBufFindNextFile( +IN VOID *Fv, +IN OUT UINTN *Key, +OUT VOID **File +); +#endif diff --git a/Platform/Intel/Tools/FMMT/FmmtConf.ini b/Platform/Intel/Tools/= FMMT/FmmtConf.ini new file mode 100644 index 0000000000..36135116b3 --- /dev/null +++ b/Platform/Intel/Tools/FMMT/FmmtConf.ini @@ -0,0 +1,6 @@ +a31280ad-481e-41b6-95e8-127f4c984779 TIANO TianoCompress +ee4e5898-3914-4259-9d6e-dc7bd79403cf LZMA LzmaCompress +fc1bcdb0-7d31-49aa-936a-a4600d9dd083 CRC32 GenCrc32 +d42ae6bd-1352-4bfb-909a-ca72a6eae889 LZMAF86 LzmaF86Compress +3d532050-5cda-4fd0-879e-0f7f630d5afb BROTLI BrotliCompress + diff --git a/Platform/Intel/Tools/FMMT/FmmtLib.c b/Platform/Intel/Tools/FMM= T/FmmtLib.c new file mode 100644 index 0000000000..f87042114b --- /dev/null +++ b/Platform/Intel/Tools/FMMT/FmmtLib.c @@ -0,0 +1,5051 @@ +/** @file + + Library to parse and generate FV image. + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "FirmwareModuleManagement.h" + +#define EFI_TEST_FFS_ATTRIBUTES_BIT(FvbAttributes, TestAttributes, Bit) \ + ( \ + (BOOLEAN) ( \ + (FvbAttributes & EFI_FVB2_ERASE_POLARITY) ? (((~TestAttributes) = & Bit) =3D=3D Bit) : ((TestAttributes & Bit) =3D=3D Bit) \ + ) \ + ) + +CHAR8 mFirmwareFileSystem2Guid[16] =3D {0x78, 0xE5, 0x8C, 0x8C, 0x3D,= 0x8A, 0x1C, 0x4F, 0x99, 0x35, 0x89, 0x61, 0x85, 0xC3, 0x2D, 0xD3}; + +CHAR8 mFirmwareFileSystem3Guid[16] =3D {0x7A, 0xC0, 0x73, 0x54, 0xCB,= 0x3D, 0xCA, 0x4D, 0xBD, 0x6F, 0x1E, 0x96, 0x89, 0xE7, 0x34, 0x9A }; + +EFI_GUID mEfiCrc32GuidedSectionExtractionProtocolGuid =3D EFI_CRC32_GUID= ED_SECTION_EXTRACTION_PROTOCOL_GUID; +extern CHAR8* mGuidToolDefinition; + +static CHAR8 *mSectionTypeName[] =3D { + NULL, // 0x00 - reserved + "EFI_SECTION_COMPRESSION", // 0x01 + "EFI_SECTION_GUID_DEFINED", // 0x02 + NULL, // 0x03 - reserved + NULL, // 0x04 - reserved + NULL, // 0x05 - reserved + NULL, // 0x06 - reserved + NULL, // 0x07 - reserved + NULL, // 0x08 - reserved + NULL, // 0x09 - reserved + NULL, // 0x0A - reserved + NULL, // 0x0B - reserved + NULL, // 0x0C - reserved + NULL, // 0x0D - reserved + NULL, // 0x0E - reserved + NULL, // 0x0F - reserved + "EFI_SECTION_PE32", // 0x10 + "EFI_SECTION_PIC", // 0x11 + "EFI_SECTION_TE", // 0x12 + "EFI_SECTION_DXE_DEPEX", // 0x13 + "EFI_SECTION_VERSION", // 0x14 + "EFI_SECTION_USER_INTERFACE", // 0x15 + "EFI_SECTION_COMPATIBILITY16", // 0x16 + "EFI_SECTION_FIRMWARE_VOLUME_IMAGE", // 0x17 + "EFI_SECTION_FREEFORM_SUBTYPE_GUID", // 0x18 + "EFI_SECTION_RAW", // 0x19 + NULL, // 0x1A + "EFI_SECTION_PEI_DEPEX", // 0x1B + "EFI_SECTION_SMM_DEPEX" // 0x1C +}; + + +static CHAR8 *mFfsFileType[] =3D { + 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 *mGuidSectionAttr[] =3D { + "NONE", // 0x00 + "PROCESSING_REQUIRED", // 0x01 + "AUTH_STATUS_VALID" // 0x02 +}; + +static EFI_GUID mFvUiGuid =3D { + 0xA67DF1FA, 0x8DE8, 0x4E98, { + 0xAF, 0x09, 0x4B, 0xDF, 0x2E, 0xFF, 0xBC, 0x7C + } +}; + + +/** + Generate the unique template filename. +**/ +CHAR8 * +GenTempFile ( + VOID + ) +{ + CHAR8 *TemString; + TemString =3D NULL; +#ifndef __GNUC__ + TemString =3D CloneString (tmpnam (NULL)); +#else + CHAR8 tmp[] =3D "/tmp/fileXXXXXX"; + UINTN Fdtmp; + Fdtmp =3D mkstemp(tmp); + TemString =3D CloneString(tmp); + close(Fdtmp); +#endif + return TemString; +} + +static +EFI_STATUS +LibExtractFvUiName(CONST EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader, CHAR= 8 **FvUiName) +{ + UINT8 *ExtEnd; + UINT32 ExtDataSize; + EFI_FIRMWARE_VOLUME_EXT_ENTRY *ExtEntry; + EFI_FIRMWARE_VOLUME_EXT_ENTRY_GUID_TYPE *GuidEntry; + + + ExtEnd =3D (UINT8 *)FvExtHeader + FvExtHeader->ExtHeaderSize; + ExtEntry =3D (EFI_FIRMWARE_VOLUME_EXT_ENTRY *)(FvExtHeader + 1); + while ((UINT8 *)ExtEntry < ExtEnd) { + // + // GUID type EXT + // + if (ExtEntry->ExtEntryType =3D=3D 0x0002) { + GuidEntry =3D (EFI_FIRMWARE_VOLUME_EXT_ENTRY_GUID_TYPE *)ExtEntry; + if (memcmp(&GuidEntry->FormatType, &mFvUiGuid, sizeof(EFI_GUID)) =3D= =3D 0) { + ExtDataSize =3D ExtEntry->ExtEntrySize - (sizeof(EFI_GUID)+sizeof(= *ExtEntry)); + *FvUiName =3D malloc(ExtDataSize + 1); + if (*FvUiName !=3D NULL) { + memcpy(*FvUiName, (UINT8 *)GuidEntry + sizeof(EFI_GUID)+sizeof(*= ExtEntry), ExtDataSize); + (*FvUiName)[ExtDataSize] =3D '\0'; + return EFI_SUCCESS; + } + } + } + + ExtEntry =3D (EFI_FIRMWARE_VOLUME_EXT_ENTRY *)((UINT8 *)ExtEntry + Ext= Entry->ExtEntrySize); + } + return EFI_NOT_FOUND; +} + +FV_INFORMATION * +LibInitializeFvStruct ( + FV_INFORMATION *Fv +) +{ + UINT32 Index; + + if (Fv =3D=3D NULL) { + return NULL; + } + + for (Index =3D 0; Index < MAX_NUMBER_OF_FILES_IN_FV; Index ++) { + memset (Fv->FfsAttuibutes[Index].FfsName, '\0', _MAX_PATH); + memset (Fv->FfsAttuibutes[Index].UiName, '\0', _MAX_PATH); + memset (&Fv->FfsAttuibutes[Index].GuidName, '\0', sizeof(EFI_GUID)); + Fv->FfsAttuibutes[Index].UiNameSize =3D 0; + Fv->FfsAttuibutes[Index].IsLeaf =3D TRUE; + Fv->FfsAttuibutes[Index].Level =3D 0xFF; + Fv->FfsAttuibutes[Index].TotalSectionNum =3D 0; + Fv->FfsAttuibutes[Index].Depex =3D NULL; + Fv->FfsAttuibutes[Index].DepexLen =3D 0; + Fv->FfsAttuibutes[Index].IsHandle =3D FALSE; + Fv->FfsAttuibutes[Index].IsFvStart =3D FALSE; + Fv->FfsAttuibutes[Index].IsFvEnd =3D FALSE; + } + + Fv->EncapData =3D NULL; + Fv->FvNext =3D NULL; + Fv->ChildFvFFS =3D NULL; + Fv->FvLevel =3D 0; + Fv->MulFvLevel =3D 1; + strcpy(Fv->AlignmentStr,"8"); + return Fv; +} + + +EFI_STATUS +LibFindFvInFd ( + IN FILE *InputFile, + IN OUT FIRMWARE_DEVICE **FdData +) +{ + FIRMWARE_DEVICE *LocalFdData; + UINT16 Index; + CHAR8 Ffs2Guid[16]; + CHAR8 SignatureCheck[5] =3D ""; + CHAR8 Signature[5] =3D "_FVH"; + FV_INFORMATION *CurrentFv; + FV_INFORMATION *NewFoundFv; + BOOLEAN FirstMatch; + UINT32 FdSize; + UINT16 FvCount; + UINT8 *FdBuffer; + UINT8 *FdBufferEnd; + UINT8 *FdBufferOri; + EFI_FIRMWARE_VOLUME_HEADER *FvHeader; + + CurrentFv =3D NULL; + NewFoundFv =3D NULL; + FdBuffer =3D NULL; + FdBufferOri =3D NULL; + FirstMatch =3D TRUE; + Index =3D 0; + FdSize =3D 0; + FvCount =3D 0; + LocalFdData =3D NULL; + + if (InputFile =3D=3D NULL) { + Error ("FMMT", 0, 0001, "Error opening the input file", ""); + return EFI_ABORTED; + } + + // + // Find each FVs in the FD + // + + fseek(InputFile,0,SEEK_SET); + fseek(InputFile,0,SEEK_END); + + FdSize =3D ftell(InputFile); + + fseek(InputFile,0,SEEK_SET); + // + // Create an FD structure to store useful information. + // + LocalFdData =3D (FIRMWARE_DEVICE *) malloc (sizeof (FIRMWARE_DEVICE)= ); + if (LocalFdData =3D=3D NULL) { + Error ("FMMT", 0, 0002, "Error searching FVs in the input fd", "Alloca= te memory error"); + return EFI_OUT_OF_RESOURCES; + } + LocalFdData->Fv =3D (FV_INFORMATION *) malloc (sizeof (FV_INFORMATION)); + if (LocalFdData->Fv =3D=3D NULL) { + Error ("FMMT", 0, 0002, "Error searching FVs in the input fd", "Alloca= te memory error"); + free (LocalFdData); + return EFI_OUT_OF_RESOURCES; + } + + LibInitializeFvStruct (LocalFdData->Fv); + + // + // Readout the FD file data to buffer. + // + FdBuffer =3D malloc (FdSize); + + if (FdBuffer =3D=3D NULL) { + Error ("FMMT", 0, 0002, "Error searching FVs in the input fd", "Alloca= te memory error"); + free (LocalFdData->Fv); + free (LocalFdData); + return EFI_OUT_OF_RESOURCES; + } + + if (fread (FdBuffer, 1, FdSize, InputFile) !=3D FdSize) { + Error ("FMMT", 0, 0002, "Error searching FVs in the input fd", "Read F= D file error!"); + free (LocalFdData->Fv); + free (LocalFdData); + free (FdBuffer); + return EFI_ABORTED; + } + + FdBufferOri =3D FdBuffer; + FdBufferEnd =3D FdBuffer + FdSize; + + while (FdBuffer <=3D FdBufferEnd - sizeof (EFI_FIRMWARE_VOLUME_HEADER)) { + FvHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *) FdBuffer; + // + // Copy 4 bytes of fd data to check the _FVH signature + // + memcpy (SignatureCheck, &FvHeader->Signature, 4); + + if (strncmp(SignatureCheck, Signature, 4) =3D=3D 0){ + // + // Still need to determine the FileSystemGuid in EFI_FIRMWARE_VOLUME= _HEADER equal to + // EFI_FIRMWARE_FILE_SYSTEM2_GUID or EFI_FIRMWARE_FILE_SYSTEM3_GUID. + // Turn back 28 bytes to find the GUID. + // + memcpy (Ffs2Guid, &FvHeader->FileSystemGuid, 16); + + // + // Compare GUID. + // + for (Index =3D 0; Index < 16; Index ++) { + if (Ffs2Guid[Index] !=3D mFirmwareFileSystem2Guid[Index]) { + break; + } + } + if (Index !=3D 16) { + for (Index =3D 0; Index < 16; Index ++) { + if (Ffs2Guid[Index] !=3D mFirmwareFileSystem3Guid[Index]) { + break; + } + } + } + + // + // Here we found an FV. + // + if ((Index =3D=3D 16) && ((FdBuffer + FvHeader->FvLength) <=3D FdBuf= ferEnd)) { + if (FirstMatch) { + LocalFdData->Fv->ImageAddress =3D (UINTN)((UINT8 *)FdBuffer - (U= INT8 *)FdBufferOri); + CurrentFv =3D LocalFdData->Fv; + CurrentFv->FvNext =3D NULL; + // + // Store the FV name by found sequence + // + sprintf(CurrentFv->FvName, "FV%d", FvCount); + + FirstMatch =3D FALSE; + } else { + NewFoundFv =3D (FV_INFORMATION *) malloc (sizeof (FV_INFORMATI= ON)); + if (NewFoundFv =3D=3D NULL) { + Error ("FMMT", 0, 0002, "Error searching FVs in the input fd= ", "Allocate memory error"); + free (LocalFdData->Fv); + free (LocalFdData); + free (FdBuffer); + return EFI_OUT_OF_RESOURCES; + } + + LibInitializeFvStruct (NewFoundFv); + + // + // Need to turn back 0x2c bytes + // + NewFoundFv->ImageAddress =3D (UINTN)((UINT8 *)FdBuffer - (UINT= 8 *)FdBufferOri); + + // + // Store the FV name by found sequence + // + sprintf(NewFoundFv->FvName, "FV%d", FvCount); + + // + // Value it to NULL for found FV usage. + // + NewFoundFv->FvNext =3D NULL; + CurrentFv->FvNext =3D NewFoundFv; + + // + // Make the CurrentFv point to next FV. + // + CurrentFv =3D CurrentFv->FvNext; + } + + FvCount ++; + FdBuffer =3D FdBuffer + FvHeader->FvLength; + } else { + FdBuffer ++; + } + + } else { + FdBuffer ++; + } + } + + LocalFdData->Size =3D FdSize; + + *FdData =3D LocalFdData; + + free (FdBufferOri); + + return EFI_SUCCESS; +} + +UINTN +GetFreeOffset ( + IN VOID *InputFv +) +{ + UINTN FreeOffset; + UINTN Offset; + EFI_STATUS Status; + EFI_FFS_FILE_HEADER2 *CurrentFile; + + Offset =3D 0; + CurrentFile =3D NULL; + FreeOffset =3D 0; + do { + FreeOffset =3D (UINTN)ALIGN_POINTER(Offset, 8); + Status =3D FvBufFindNextFile(InputFv, &Offset, (VOID **)&CurrentFile); + if (Status =3D=3D EFI_NOT_FOUND) { + CurrentFile =3D NULL; + break; + } + else if (EFI_ERROR(Status)) { + return Status; + } + } while (CurrentFile !=3D NULL); + + return FreeOffset; +} + +/* + Construct a set of blank chars based on the number. + + @param[in] Count The number of blank chars. + + @return A string contained the blank chars. + +*/ +CHAR8 * +LibConstructBlankChar ( + IN UINT8 Count +) +{ + CHAR8 *RetStr; + UINT8 Index; + + Index =3D 0; + RetStr =3D NULL; + + RetStr =3D (CHAR8 *) malloc (Count +1); + + if (RetStr =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return NULL; + } + + memset (RetStr , '\0', Count + 1); + + for (Index=3D0; Index <=3D Count -1; Index ++) { + RetStr[Index] =3D ' '; + } + + return RetStr; + +} + +/** + + This function determines the size of the FV and the erase polarity. The + erase polarity is the FALSE value for file state. + + + @param[in ] InputFile The file that contains the FV image. + @param[out] FvSize The size of the FV. + @param[out] ErasePolarity The FV erase polarity. + + @return EFI_SUCCESS Function completed successfully. + @return EFI_INVALID_PARAMETER A required parameter was NULL or is out = of range. + @return EFI_ABORTED The function encountered an error. + +**/ +EFI_STATUS +LibReadFvHeader ( + IN VOID *InputFv, + IN BOOLEAN ViewFlag, + IN UINT8 FvLevel, + IN UINT8 FvCount, + IN CHAR8 *FvName + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *VolumeHeader; + CHAR8 *BlankSpace; + CHAR8 *FvUiName; + EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader; + + BlankSpace =3D NULL; + FvUiName =3D NULL; + + // + // Check input parameters + // + if (InputFv =3D=3D NULL) { + Error (__FILE__, __LINE__, 0, "FMMT application error", "invalid param= eter to function"); + return EFI_INVALID_PARAMETER; + } + + // + // Read the header + // + VolumeHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *) InputFv; + + + BlankSpace =3D LibConstructBlankChar((FvLevel)*2); + + if (BlankSpace =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_OUT_OF_RESOURCES; + } + + + if (ViewFlag) { + if ((FvLevel -1) =3D=3D 0) { + printf ("\n%s :\n", FvName); + } else { + printf ("%sChild FV named FV%d of %s\n", BlankSpace, FvCount, FvName= ); + } + } + + // + // Print FV header information + // + if (ViewFlag) { + printf ("\n%sAttributes: %X\n", BlankSpace, (unsigned) Volu= meHeader->Attributes); + printf ("%sTotal Volume Size: 0x%08X\n", BlankSpace, (unsigned) Vo= lumeHeader->FvLength); + printf ("%sFree Volume Size: 0x%08X\n", BlankSpace, (unsigned) (V= olumeHeader->FvLength - GetFreeOffset(InputFv))); + } + + if (ViewFlag && VolumeHeader->ExtHeaderOffset !=3D 0) { + FvExtHeader =3D (EFI_FIRMWARE_VOLUME_EXT_HEADER *)((UINT8 *)VolumeHead= er + VolumeHeader->ExtHeaderOffset); + printf("%sFvNameGuid: %08X-%04X-%04X-%02X%02X-%02X%02X%02X%= 02X%02X%02X\n", + BlankSpace, + FvExtHeader->FvName.Data1, + FvExtHeader->FvName.Data2, + FvExtHeader->FvName.Data3, + FvExtHeader->FvName.Data4[0], + FvExtHeader->FvName.Data4[1], + FvExtHeader->FvName.Data4[2], + FvExtHeader->FvName.Data4[3], + FvExtHeader->FvName.Data4[4], + FvExtHeader->FvName.Data4[5], + FvExtHeader->FvName.Data4[6], + FvExtHeader->FvName.Data4[7]); + LibExtractFvUiName(FvExtHeader, &FvUiName); + if (FvUiName !=3D NULL && FvLevel =3D=3D 1) { + printf("%sFV UI Name: %s\n\n", BlankSpace, FvUiName); + } + free(FvUiName); + } + free (BlankSpace); + return EFI_SUCCESS; +} + +/* + Get size info from FV file. + + @param[in] + @param[out] + + @retval + +*/ +EFI_STATUS +LibGetFvSize ( + IN FILE *InputFile, + OUT UINT32 *FvSize + ) +{ + + UINTN BytesRead; + UINT32 Size; + EFI_FV_BLOCK_MAP_ENTRY BlockMap; + + BytesRead =3D 0; + Size =3D 0; + + if (InputFile =3D=3D NULL || FvSize =3D=3D NULL) { + Error (__FILE__, __LINE__, 0, "FMMT application error", "invalid param= eter to function"); + return EFI_INVALID_PARAMETER; + } + + fseek (InputFile, sizeof (EFI_FIRMWARE_VOLUME_HEADER) - sizeof (EFI_FV_B= LOCK_MAP_ENTRY), SEEK_CUR); + do { + fread (&BlockMap, sizeof (EFI_FV_BLOCK_MAP_ENTRY), 1, InputFile); + BytesRead +=3D sizeof (EFI_FV_BLOCK_MAP_ENTRY); + + if (BlockMap.NumBlocks !=3D 0) { + Size +=3D BlockMap.NumBlocks * BlockMap.Length; + } + } while (!(BlockMap.NumBlocks =3D=3D 0 && BlockMap.Length =3D=3D 0)); + + + *FvSize =3D Size; + + return EFI_SUCCESS; +} + +/** + + Clears out all files from the Fv buffer in memory + + @param[in] Fv - Address of the Fv in memory + + @return EFI_STATUS + +**/ +EFI_STATUS +FvBufGetSize ( + IN VOID *Fv, + OUT UINTN *Size + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *hdr; + EFI_FV_BLOCK_MAP_ENTRY *blk; + + *Size =3D 0; + hdr =3D (EFI_FIRMWARE_VOLUME_HEADER*)Fv; + blk =3D hdr->BlockMap; + + while (blk->Length !=3D 0 || blk->NumBlocks !=3D 0) { + *Size =3D *Size + (blk->Length * blk->NumBlocks); + if (*Size >=3D 0x40000000) { + // + // If size is greater than 1GB, then assume it is corrupted + // + return EFI_VOLUME_CORRUPTED; + } + blk++; + } + + if (*Size =3D=3D 0) { + // + // If size is 0, then assume the volume is corrupted + // + return EFI_VOLUME_CORRUPTED; + } + + return EFI_SUCCESS; +} + +/* + Generate the leaf FFS files. + +*/ +EFI_STATUS +LibGenFfsFile ( + EFI_FFS_FILE_HEADER2 *CurrentFile, + FV_INFORMATION *CurrentFv, + CHAR8 *FvName, + UINT8 Level, + UINT32 *FfsCount, + BOOLEAN ErasePolarity +) +{ + UINT32 FfsFileSize; + CHAR8 *FfsFileName; + FILE *FfsFile; + CHAR8 *TempDir; + + + FfsFileSize =3D 0; + FfsFileName =3D NULL; + FfsFile =3D NULL; + TempDir =3D NULL; + + TempDir =3D getcwd (NULL, _MAX_PATH); + if (strlen (TempDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _MA= X_PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return EFI_ABORTED; + } + strncat (TempDir, OS_SEP_STR, _MAX_PATH - strlen(TempDir) - 1); + strncat (TempDir, TEMP_DIR_NAME, _MAX_PATH - strlen(TempDir) - 1); + + mkdir(TempDir, S_IRWXU | S_IRWXG | S_IRWXO); + + FfsFileName =3D (CHAR8 *) malloc (_MAX_PATH); + if (FfsFileName =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + memset (FfsFileName, '\0', _MAX_PATH); + FfsFileSize =3D GetFfsFileLength ((EFI_FFS_FILE_HEADER *) CurrentFile); + sprintf ( + (CHAR8 *)FfsFileName, + "%s%cNum%d-%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X-Level%d", + TempDir, + OS_SEP, + *FfsCount, + (unsigned) CurrentFile->Name.Data1, + CurrentFile->Name.Data2, + CurrentFile->Name.Data3, + CurrentFile->Name.Data4[0], + CurrentFile->Name.Data4[1], + CurrentFile->Name.Data4[2], + CurrentFile->Name.Data4[3], + CurrentFile->Name.Data4[4], + CurrentFile->Name.Data4[5], + CurrentFile->Name.Data4[6], + CurrentFile->Name.Data4[7], + Level + ); + + memcpy (CurrentFv->FfsAttuibutes[*FfsCount].FfsName, FfsFileName, strlen= (FfsFileName)); + memcpy (&CurrentFv->FfsAttuibutes[*FfsCount].GuidName, &CurrentFile->Nam= e, sizeof(EFI_GUID)); + // + // Update current FFS files file state. + // + if (ErasePolarity) { + CurrentFile->State =3D (UINT8)~(CurrentFile->State); + } + + FfsFile =3D fopen (FfsFileName, "wb+"); + if (FfsFile =3D=3D NULL) { + Error ("FMMT", 0, 0003, "error writing FFS file", "cannot Create a new= ffs file."); + free(FfsFileName); + return EFI_ABORTED; + } + + if (fwrite (CurrentFile, 1, FfsFileSize, FfsFile) !=3D FfsFileSize) { + Error ("FMMT", 0, 0004, "error writing FFS file", "cannot Create a ne= w ffs file."); + fclose(FfsFile); + free(FfsFileName); + return EFI_ABORTED; + } + + fclose(FfsFile); + free(FfsFileName); + FfsFileName =3D NULL; + + CurrentFv->FfsNumbers =3D *FfsCount; + + *FfsCount +=3D 1; + + if (ErasePolarity) { + CurrentFile->State =3D (UINT8)~(CurrentFile->State); + } + + return EFI_SUCCESS; +} + +VOID +Unicode2AsciiString ( + IN CHAR16 *Source, + OUT CHAR8 *Destination + ) + /*++ + + Routine Description: + + Convert a null-terminated unicode string to a null-terminated ascii stri= ng. + + Arguments: + + Source - The pointer to the null-terminated input unicode string. + Destination - The pointer to the null-terminated output ascii string. + + Returns: + + N/A + + --*/ +{ + while (*Source !=3D '\0') { + *(Destination++) =3D (CHAR8) *(Source++); + } + // + // End the ascii with a NULL. + // + *Destination =3D '\0'; +} + + +/** + + Parses EFI Sections, if the view flag turn on, then will collect FFS sec= tion information + and extract FFS files. + + @param[in] SectionBuffer - Buffer containing the section to parse. + @param[in] BufferLength - Length of SectionBuffer + @param[in, out] CurrentFv + @param[in] FvName + @param[in] CurrentFile + @param[in] Level + @param[in, out] FfsCount + @param[in] ViewFlag + @param[in] ErasePolarity + + @retval EFI_SECTION_ERROR - Problem with section parsing. + (a) compression errors + (b) unrecognized section + @retval EFI_UNSUPPORTED - Do not know how to parse the section. + @retval EFI_SUCCESS - Section successfully parsed. + @retval EFI_OUT_OF_RESOURCES - Memory allocation failed. + +--*/ +EFI_STATUS +LibParseSection ( + UINT8 *SectionBuffer, + UINT32 BufferLength, + FV_INFORMATION *CurrentFv, + CHAR8 *FvName, + EFI_FFS_FILE_HEADER2 *CurrentFile, + UINT8 Level, + ENCAP_INFO_DATA **CurrentFvEncapData, + UINT8 FfsLevel, + UINT32 *FfsCount, + UINT8 *FvCount, + BOOLEAN ViewFlag, + BOOLEAN ErasePolarity, + BOOLEAN *IsFfsGenerated + ) +{ + UINT32 ParsedLength; + UINT8 *Ptr; + UINT32 SectionLength; + UINT32 UiSectionLength; + EFI_SECTION_TYPE Type; + EFI_STATUS Status; + CHAR8 *ExtractionTool; + CHAR8 *ToolInputFile; + CHAR8 *ToolOutputFile; + CHAR8 *SystemCommandFormatString; + CHAR8 *SystemCommand; + UINT8 *ToolOutputBuffer; + UINT32 ToolOutputLength; + CHAR16 *UIName; + UINT32 UINameSize; + BOOLEAN HasDepexSection; + UINT32 NumberOfSections; + ENCAP_INFO_DATA *LocalEncapData; + ENCAP_INFO_DATA *LocalEncapDataTemp; + CHAR8 *BlankChar; + UINT8 *UncompressedBuffer; + UINT32 UncompressedLength; + UINT8 *CompressedBuffer; + UINT32 CompressedLength; + UINT8 CompressionType; + DECOMPRESS_FUNCTION DecompressFunction; + GETINFO_FUNCTION GetInfoFunction; + UINT32 DstSize; + UINT32 ScratchSize; + UINT8 *ScratchBuffer; + BOOLEAN EncapDataNeedUpdata; + CHAR8 *TempDir; + CHAR8 *ToolInputFileFullName; + CHAR8 *ToolOutputFileFullName; + UINT8 LargeHeaderOffset; + UINT16 GuidAttr; + UINT16 DataOffset; + CHAR8 *UIFileName; + CHAR8 *ToolInputFileName; + CHAR8 *ToolOutputFileName; + + DataOffset =3D 0; + GuidAttr =3D 0; + ParsedLength =3D 0; + ToolOutputLength =3D 0; + UINameSize =3D 0; + NumberOfSections =3D 0; + UncompressedLength =3D 0; + CompressedLength =3D 0; + CompressionType =3D 0; + DstSize =3D 0; + ScratchSize =3D 0; + Ptr =3D NULL; + ExtractionTool =3D NULL; + ToolInputFile =3D NULL; + ToolOutputFile =3D NULL; + SystemCommand =3D NULL; + SystemCommandFormatString =3D NULL; + ToolOutputBuffer =3D NULL; + UIName =3D NULL; + LocalEncapData =3D NULL; + LocalEncapDataTemp =3D NULL; + BlankChar =3D NULL; + UncompressedBuffer =3D NULL; + CompressedBuffer =3D NULL; + ScratchBuffer =3D NULL; + TempDir =3D NULL; + ToolInputFileFullName =3D NULL; + ToolOutputFileFullName =3D NULL; + ToolInputFileName =3D NULL; + ToolOutputFileFullName =3D NULL; + HasDepexSection =3D FALSE; + EncapDataNeedUpdata =3D TRUE; + LargeHeaderOffset =3D 0; + + + while (ParsedLength < BufferLength) { + Ptr =3D SectionBuffer + ParsedLength; + + SectionLength =3D GetLength (((EFI_COMMON_SECTION_HEADER *) Ptr)->Size= ); + Type =3D ((EFI_COMMON_SECTION_HEADER *) Ptr)->Type; + + // + // This is sort of an odd check, but is necessary because FFS files are + // padded to a QWORD boundary, meaning there is potentially a whole se= ction + // header worth of 0xFF bytes. + // + if (SectionLength =3D=3D 0xffffff && Type =3D=3D 0xff) { + ParsedLength +=3D 4; + continue; + } + // + //If Size is 0xFFFFFF then ExtendedSize contains the size of the section. + // + if (SectionLength =3D=3D 0xffffff) { + SectionLength =3D ((EFI_COMMON_SECTION_HEADER2 *) Ptr)->ExtendedSi= ze; + LargeHeaderOffset =3D sizeof (EFI_COMMON_SECTION_HEADER2) - sizeof (EF= I_COMMON_SECTION_HEADER); + } + + switch (Type) { + + case EFI_SECTION_FIRMWARE_VOLUME_IMAGE: + + EncapDataNeedUpdata =3D TRUE; + + Level ++; + NumberOfSections ++; + + CurrentFv->FfsAttuibutes[*FfsCount].IsLeaf =3D FALSE; + CurrentFv->FfsAttuibutes[*FfsCount].IsFvStart =3D TRUE; + // + // Put in encapsulate data information. + // + LocalEncapData =3D *CurrentFvEncapData; + if (LocalEncapData->NextNode !=3D NULL) { + LocalEncapData =3D LocalEncapData->NextNode; + while (LocalEncapData->RightNode !=3D NULL) { + LocalEncapData =3D LocalEncapData->RightNode; + } + } + + if (EncapDataNeedUpdata) { + // + // Put in this is an FFS with FV section + // + + // + // Construct the new ENCAP_DATA + // + LocalEncapData->NextNode =3D (ENCAP_INFO_DATA *) malloc (sizeof (E= NCAP_INFO_DATA)); + + if (LocalEncapData->NextNode =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + + LocalEncapData =3D LocalEncapData->NextNode; + + LocalEncapData->Level =3D Level; + LocalEncapData->Type =3D FMMT_ENCAP_TREE_FV_SECTION; + + // + // We don't need additional data for encapsulate this FFS but type. + // + LocalEncapData->Data =3D NULL; + LocalEncapData->FvExtHeader =3D NULL; + LocalEncapData->NextNode =3D NULL; + LocalEncapData->RightNode =3D NULL; + LocalEncapData->Depex =3D NULL; + LocalEncapData->DepexLen =3D 0; + LocalEncapData->UiNameSize =3D 0; + LocalEncapData->FvId =3D *FvCount; + } + + // + //save parent level FFS file's GUID name + // + LocalEncapDataTemp =3D CurrentFv->EncapData; + while (LocalEncapDataTemp->NextNode !=3D NULL) { + if (LocalEncapDataTemp->Level =3D=3D FfsLevel) { + while (LocalEncapDataTemp->RightNode !=3D NULL) { + LocalEncapDataTemp =3D LocalEncapDataTemp->RightNode; + } + if (LocalEncapDataTemp !=3D NULL && LocalEncapDataTemp->FvExt= Header =3D=3D NULL) { + LocalEncapDataTemp->FvExtHeader =3D (EFI_FIRMWARE_VOLUME_= EXT_HEADER *)malloc(sizeof(EFI_FIRMWARE_VOLUME_EXT_HEADER)); + if (LocalEncapDataTemp->FvExtHeader =3D=3D NULL) { + Error(NULL, 0, 4001, "Resource: Memory can't be alloc= ated", NULL); + return EFI_ABORTED; + } + + if (*FfsCount >=3D 1) { + if ((memcmp(&CurrentFv->FfsAttuibutes[*FfsCount - 1].G= uidName, &(LocalEncapDataTemp->FvExtHeader->FvName), sizeof(EFI_GUID)) =3D= =3D 0)) { + memcpy(LocalEncapDataTemp->UiName, CurrentFv->FfsA= ttuibutes[*FfsCount - 1].UiName, _MAX_PATH); + LocalEncapDataTemp->UiNameSize =3D CurrentFv->FfsA= ttuibutes[*FfsCount - 1].UiNameSize; + LocalEncapDataTemp->DepexLen =3D CurrentFv->FfsAtt= uibutes[*FfsCount - 1].DepexLen; + LocalEncapDataTemp->Depex =3D malloc (LocalEncapDa= taTemp->DepexLen); + if (LocalEncapDataTemp->Depex =3D=3D NULL) { + Error(NULL, 0, 4001, "Resource: Memory can't b= e allocated", NULL); + return EFI_ABORTED; + } + memcpy(LocalEncapDataTemp->Depex, CurrentFv->FfsAt= tuibutes[*FfsCount - 1].Depex, LocalEncapDataTemp->DepexLen); + } + } + } + break; + } + LocalEncapDataTemp =3D LocalEncapDataTemp->NextNode; + } + + Status =3D LibGetFvInfo ((UINT8*)((EFI_FIRMWARE_VOLUME_IMAGE_SECTION= *)Ptr + 1) + LargeHeaderOffset, CurrentFv, FvName, Level, &LocalEncapData, = FfsCount, FvCount, ViewFlag, TRUE); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0003, "printing of FV section contents failed", = NULL); + return EFI_SECTION_ERROR; + } + if (*FfsCount >=3D 1) { + CurrentFv->FfsAttuibutes[*FfsCount -1].IsFvEnd =3D TRUE; + } + break; + + case EFI_SECTION_COMPRESSION: + Level ++; + NumberOfSections ++; + + EncapDataNeedUpdata =3D TRUE; + // + // Put in encapsulate data information. + // + LocalEncapData =3D *CurrentFvEncapData; + if (LocalEncapData->NextNode !=3D NULL) { + EncapDataNeedUpdata =3D FALSE; + while (LocalEncapData->RightNode !=3D NULL) { + LocalEncapData =3D LocalEncapData->RightNode; + } + } + + if (EncapDataNeedUpdata) { + // + // Put in this is an FFS with FV section + // + + // + // Construct the new ENCAP_DATA + // + LocalEncapData->NextNode =3D (ENCAP_INFO_DATA *) malloc (sizeof (E= NCAP_INFO_DATA)); + + if (LocalEncapData->NextNode =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + + LocalEncapData =3D LocalEncapData->NextNode; + + LocalEncapData->Level =3D Level; + LocalEncapData->Type =3D FMMT_ENCAP_TREE_COMPRESS_SECTION; + + // + // Store the compress type + // + LocalEncapData->Data =3D malloc (sizeof (UINT8)); + + if (LocalEncapData->Data =3D=3D NULL) { + Error ("FMMT", 0, 0003, "Allocate memory failed", NULL); + return EFI_OUT_OF_RESOURCES; + } + + *(UINT8 *)LocalEncapData->Data =3D ((EFI_COMPRESSION_SECTION *= ) (Ptr + LargeHeaderOffset))->CompressionType; + LocalEncapData->FvExtHeader =3D NULL; + LocalEncapData->NextNode =3D NULL; + LocalEncapData->RightNode =3D NULL; + } else { + LocalEncapData->RightNode =3D (ENCAP_INFO_DATA *) malloc (sizeof (= ENCAP_INFO_DATA)); + if (LocalEncapData->RightNode =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + LocalEncapData =3D LocalEncapData->RightNode; + + LocalEncapData->Level =3D Level; + LocalEncapData->Type =3D FMMT_ENCAP_TREE_COMPRESS_SECTION; + + // + // Store the compress type + // + LocalEncapData->Data =3D malloc (sizeof (UINT8)); + + if (LocalEncapData->Data =3D=3D NULL) { + Error ("FMMT", 0, 0003, "Allocate memory failed", NULL); + return EFI_OUT_OF_RESOURCES; + } + + *(UINT8 *)LocalEncapData->Data =3D ((EFI_COMPRESSION_SECTION *= ) (Ptr + LargeHeaderOffset))->CompressionType; + LocalEncapData->FvExtHeader =3D NULL; + LocalEncapData->NextNode =3D NULL; + LocalEncapData->RightNode =3D NULL; + + } + + // + // Process compressed section + // + CurrentFv->FfsAttuibutes[*FfsCount].IsLeaf =3D FALSE; + + UncompressedBuffer =3D NULL; + CompressedLength =3D SectionLength - sizeof (EFI_COMPRESSION_SECT= ION) - LargeHeaderOffset; + UncompressedLength =3D ((EFI_COMPRESSION_SECTION *) (Ptr + LargeHea= derOffset))->UncompressedLength; + CompressionType =3D ((EFI_COMPRESSION_SECTION *) (Ptr + LargeHea= derOffset))->CompressionType; + + if (CompressionType =3D=3D EFI_NOT_COMPRESSED) { + //printf (" Compression Type: EFI_NOT_COMPRESSED\n"); + if (CompressedLength !=3D UncompressedLength) { + Error ("FMMT", 0, 0, "file is not compressed, but the compressed= length does not match the uncompressed length", NULL); + return EFI_SECTION_ERROR; + } + + UncompressedBuffer =3D Ptr + sizeof (EFI_COMPRESSION_SECTION) + La= rgeHeaderOffset; + } else if (CompressionType =3D=3D EFI_STANDARD_COMPRESSION) { + GetInfoFunction =3D EfiGetInfo; + DecompressFunction =3D EfiDecompress; + + CompressedBuffer =3D Ptr + sizeof (EFI_COMPRESSION_SECTION) + Lar= geHeaderOffset; + + Status =3D GetInfoFunction (CompressedBuffer, Compresse= dLength, &DstSize, &ScratchSize); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0003, "error getting compression info from com= pression section", NULL); + return EFI_SECTION_ERROR; + } + + if (DstSize !=3D UncompressedLength) { + Error ("FMMT", 0, 0003, "compression error in the compression se= ction", NULL); + return EFI_SECTION_ERROR; + } + + ScratchBuffer =3D malloc (ScratchSize); + if (ScratchBuffer =3D=3D NULL) { + Error ("FMMT", 0, 0003, "Allocate memory failed", NULL); + return EFI_OUT_OF_RESOURCES; + } + UncompressedBuffer =3D malloc (UncompressedLength); + if (UncompressedBuffer =3D=3D NULL) { + Error ("FMMT", 0, 0003, "Allocate memory failed", NULL); + free (ScratchBuffer); + return EFI_OUT_OF_RESOURCES; + } + // + // Decompress the section. + // + Status =3D DecompressFunction ( + CompressedBuffer, + CompressedLength, + UncompressedBuffer, + UncompressedLength, + ScratchBuffer, + ScratchSize + ); + free (ScratchBuffer); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0003, "decompress failed", NULL); + free (UncompressedBuffer); + return EFI_SECTION_ERROR; + } + } else { + Error ("FMMT", 0, 0003, "unrecognized compression type", "type 0x%= X", CompressionType); + return EFI_SECTION_ERROR; + } + + Status =3D LibParseSection ( UncompressedBuffer, + UncompressedLength, + CurrentFv, + FvName, + CurrentFile, + Level, + &LocalEncapData, + FfsLevel, + FfsCount, + FvCount, + ViewFlag, + ErasePolarity, + IsFfsGenerated); + + if (CompressionType =3D=3D EFI_STANDARD_COMPRESSION) { + // + // We need to deallocate Buffer + // + free (UncompressedBuffer); + } + + if (EFI_ERROR (Status)) { + Error (NULL, 0, 0003, "failed to parse section", NULL); + return EFI_SECTION_ERROR; + } + + break; + + case EFI_SECTION_GUID_DEFINED: + // + // Process GUID defined + // looks up the appropriate tool to use for extracting + // a GUID defined FV section. + // + Level ++; + NumberOfSections++; + EncapDataNeedUpdata =3D TRUE; + // + // Put in encapsulate data information. + // + LocalEncapData =3D *CurrentFvEncapData; + if (LocalEncapData->NextNode !=3D NULL) { + EncapDataNeedUpdata =3D FALSE; + while (LocalEncapData->RightNode !=3D NULL) { + LocalEncapData =3D LocalEncapData->RightNode; + } + } + GuidAttr =3D ((EFI_GUID_DEFINED_SECTION *)(Ptr + LargeHeaderOffset))= ->Attributes; + DataOffset =3D ((EFI_GUID_DEFINED_SECTION *)(Ptr + LargeHeaderOffset= ))->DataOffset; + + if ((ViewFlag) && ((GuidAttr & EFI_GUIDED_SECTION_PROCESSING_REQUIRE= D) =3D=3D 0)) { + ToolOutputBuffer =3D Ptr + DataOffset; + ToolOutputLength =3D SectionLength - DataOffset; + Status =3D LibParseSection( + ToolOutputBuffer, + ToolOutputLength, + CurrentFv, + FvName, + CurrentFile, + Level, + &LocalEncapData, + FfsLevel, + FfsCount, + FvCount, + ViewFlag, + ErasePolarity, + IsFfsGenerated + ); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 0003, "parse of decoded GUIDED section failed", N= ULL); + return EFI_SECTION_ERROR; + } + break; + } + + if (EncapDataNeedUpdata) { + + // + // Put in this is an FFS with FV section + // + + // + // Construct the new ENCAP_DATA + // + LocalEncapData->NextNode =3D (ENCAP_INFO_DATA *) malloc (sizeof (E= NCAP_INFO_DATA)); + + if (LocalEncapData->NextNode =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + + LocalEncapData =3D LocalEncapData->NextNode; + + LocalEncapData->Level =3D Level; + LocalEncapData->Type =3D FMMT_ENCAP_TREE_GUIDED_SECTION; + LocalEncapData->Depex =3D NULL; + LocalEncapData->DepexLen =3D 0; + LocalEncapData->UiNameSize =3D 0; + // + // We don't need additional data for encapsulate this FFS but type. + // include DataOffset + Attributes + // + + LocalEncapData->Data =3D (EFI_GUID *) malloc (sizeof (EFI_GUID= ) + 4); + + if (LocalEncapData->Data =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + + // + // include guid attribute and dataoffset + // + memcpy (LocalEncapData->Data, Ptr + LargeHeaderOffset + OFFSET_OF = (EFI_GUID_DEFINED_SECTION, SectionDefinitionGuid), sizeof (EFI_GUID) + 4); + + LocalEncapData->FvExtHeader =3D NULL; + LocalEncapData->NextNode =3D NULL; + LocalEncapData->RightNode =3D NULL; + } else { + LocalEncapData->RightNode =3D (ENCAP_INFO_DATA *) malloc (sizeof (= ENCAP_INFO_DATA)); + if (LocalEncapData->RightNode =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + LocalEncapData =3D LocalEncapData->RightNode; + LocalEncapData->Level =3D Level; + LocalEncapData->Type =3D FMMT_ENCAP_TREE_GUIDED_SECTION; + LocalEncapData->Depex =3D NULL; + LocalEncapData->DepexLen =3D 0; + LocalEncapData->UiNameSize =3D 0; + // + // We don't need additional data for encapsulate this FFS but type. + // include DataOffset + Attributes + // + + LocalEncapData->Data =3D (EFI_GUID *) malloc (sizeof (EFI_GUID= ) + 4); + + if (LocalEncapData->Data =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + + // + // include guid attribute and dataoffset + // + memcpy (LocalEncapData->Data, Ptr + LargeHeaderOffset + OFFSET_OF = (EFI_GUID_DEFINED_SECTION, SectionDefinitionGuid), sizeof (EFI_GUID) + 4); + + LocalEncapData->FvExtHeader =3D NULL; + LocalEncapData->NextNode =3D NULL; + LocalEncapData->RightNode =3D NULL; + } + + CurrentFv->FfsAttuibutes[*FfsCount].IsLeaf =3D FALSE; + + ExtractionTool =3D + LookupGuidedSectionToolPath ( + mParsedGuidedSectionTools, + &((EFI_GUID_DEFINED_SECTION *) (Ptr + LargeHeaderOffset))->Secti= onDefinitionGuid + ); + + if (ExtractionTool !=3D NULL && ((GuidAttr & EFI_GUIDED_SECTION_PROC= ESSING_REQUIRED) !=3D 0)) { + + TempDir =3D getcwd (NULL, _MAX_PATH); + if (strlen (TempDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME)= > _MAX_PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + free (ExtractionTool); + return EFI_SECTION_ERROR; + } + strncat (TempDir, OS_SEP_STR, _MAX_PATH - strlen(TempDir) - 1); + strncat (TempDir, TEMP_DIR_NAME, _MAX_PATH - strlen(TempDir) - 1); + mkdir(TempDir, S_IRWXU | S_IRWXG | S_IRWXO); + ToolInputFile =3D GenTempFile (); + if (ToolInputFile =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + free (ExtractionTool); + return EFI_OUT_OF_RESOURCES; + } + ToolOutputFile =3D GenTempFile (); + if (ToolOutputFile =3D=3D NULL) { + free (ToolInputFile); + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + free (ExtractionTool); + return EFI_OUT_OF_RESOURCES; + } + ToolInputFileName =3D strrchr(ToolInputFile, OS_SEP); + if (ToolInputFileName =3D=3D NULL) { + free (ToolInputFile); + free (ToolOutputFile); + free (ExtractionTool); + return EFI_ABORTED; + } + ToolOutputFileName =3D strrchr(ToolOutputFile, OS_SEP); + if (ToolOutputFileName =3D=3D NULL) { + free (ToolInputFile); + free (ToolOutputFile); + free (ExtractionTool); + return EFI_ABORTED; + } + + ToolInputFileFullName =3D malloc (strlen("%s%s") + strlen(TempDi= r) + strlen(ToolInputFileName) + 1); + if (ToolInputFileFullName =3D=3D NULL) { + free (ToolInputFile); + free (ToolOutputFile); + free (ExtractionTool); + Error ("FMMT", 0, 0003, "Allocate memory failed", NULL); + return EFI_OUT_OF_RESOURCES; + } + ToolOutputFileFullName =3D malloc (strlen("%s%s") + strlen(TempDi= r) + strlen(ToolOutputFileName) + 1); + + if (ToolOutputFileFullName =3D=3D NULL) { + free (ToolInputFile); + free (ToolOutputFile); + free (ToolInputFileFullName); + free (ExtractionTool); + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_OUT_OF_RESOURCES; + } + + sprintf (ToolInputFileFullName, "%s%s", TempDir, ToolInputFileName= ); + sprintf (ToolOutputFileFullName, "%s%s", TempDir, ToolOutputFileNa= me); + + // + // Construction 'system' command string + // + SystemCommandFormatString =3D "%s -d -o \"%s\" \"%s\""; + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (ExtractionTool) + + strlen (ToolInputFileFullName) + + strlen (ToolOutputFileFullName) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + free (ToolInputFile); + free (ToolOutputFile); + free (ToolInputFileFullName); + free (ToolOutputFileFullName); + free (ExtractionTool); + return EFI_ABORTED; + } + sprintf ( + SystemCommand, + "%s -d -o \"%s\" \"%s\"", + ExtractionTool, + ToolOutputFileFullName, + ToolInputFileFullName + ); + free (ExtractionTool); + ExtractionTool =3D NULL; + + Status =3D PutFileImage ( + ToolInputFileFullName, + (CHAR8*) Ptr + ((EFI_GUID_DEFINED_SECTION *) (Ptr + LargeHeaderOff= set))->DataOffset, + SectionLength - ((EFI_GUID_DEFINED_SECTION *) (Ptr + LargeHeaderOf= fset))->DataOffset + ); + + if (HasDepexSection) { + HasDepexSection =3D FALSE; + } + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "unable to decoded GUIDED section", NULL= ); + free (SystemCommand); + free (ToolInputFile); + free (ToolOutputFile); + free (ToolOutputFileFullName); + remove (ToolInputFileFullName); + free (ToolInputFileFullName); + return EFI_SECTION_ERROR; + } + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + printf("Command failed: %s\n", SystemCommand); + free (SystemCommand); + free (ToolInputFile); + free (ToolOutputFile); + free (ToolOutputFileFullName); + remove (ToolInputFileFullName); + free (ToolInputFileFullName); + return EFI_ABORTED; + } + free (SystemCommand); + remove (ToolInputFileFullName); + free (ToolInputFile); + free (ToolInputFileFullName); + ToolInputFile =3D NULL; + ToolInputFileFullName =3D NULL; + + + Status =3D GetFileImage ( + ToolOutputFileFullName, + (CHAR8 **)&ToolOutputBuffer, + &ToolOutputLength + ); + remove (ToolOutputFileFullName); + free (ToolOutputFile); + free (ToolOutputFileFullName); + ToolOutputFile =3D NULL; + ToolOutputFileFullName =3D NULL; + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "unable to read decoded GUIDED section",= NULL); + return EFI_SECTION_ERROR; + } + + Status =3D LibParseSection ( + ToolOutputBuffer, + ToolOutputLength, + CurrentFv, + FvName, + CurrentFile, + Level, + &LocalEncapData, + FfsLevel, + FfsCount, + FvCount, + ViewFlag, + ErasePolarity, + IsFfsGenerated + ); + if (EFI_ERROR (Status)) { + Error (NULL, 0, 0003, "parse of decoded GUIDED section failed", = NULL); + return EFI_SECTION_ERROR; + } + } else if ((GuidAttr & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) =3D= =3D 0){ + Status =3D LibParseSection ( + Ptr + ((EFI_GUID_DEFINED_SECTION *) (Ptr + LargeHeaderOffset))= ->DataOffset, + SectionLength - ((EFI_GUID_DEFINED_SECTION *) (Ptr + LargeHead= erOffset))->DataOffset, + CurrentFv, + FvName, + CurrentFile, + Level, + &LocalEncapData, + FfsLevel, + FfsCount, + FvCount, + ViewFlag, + ErasePolarity, + IsFfsGenerated + ); + if (ExtractionTool !=3D NULL) { + free (ExtractionTool); + ExtractionTool =3D NULL; + } + if (EFI_ERROR (Status)) { + Error (NULL, 0, 0003, "parse of decoded GUIDED section failed"= , NULL); + return EFI_SECTION_ERROR; + } + }else { + // + // We don't know how to parse it now. + // + if (ExtractionTool !=3D NULL) { + free (ExtractionTool); + ExtractionTool =3D NULL; + } + Error ("FMMT", 0, 0003, "Error parsing section", \ + "EFI_SECTION_GUID_DEFINED cannot be parsed a= t this time. Tool to decode this section should have been defined in %s fil= e.", mGuidToolDefinition); + printf(" Its GUID is: "); + PrintGuid(&(((EFI_GUID_DEFINED_SECTION *)(Ptr + LargeHeaderOffset)= )->SectionDefinitionGuid)); + return EFI_UNSUPPORTED; + } + break; + + // + //Leaf sections + // + case EFI_SECTION_RAW: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + if (!ViewFlag) { + if (!*IsFfsGenerated) { + LibGenFfsFile(CurrentFile, CurrentFv, FvName, Level, FfsCount, E= rasePolarity); + *IsFfsGenerated =3D TRUE; + } + } + + break; + case EFI_SECTION_PE32: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + if (!ViewFlag) { + if (!*IsFfsGenerated) { + LibGenFfsFile(CurrentFile, CurrentFv, FvName, Level, FfsCount, E= rasePolarity); + *IsFfsGenerated =3D TRUE; + } + } + + break; + case EFI_SECTION_PIC: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + if (!ViewFlag) { + if (!*IsFfsGenerated) { + LibGenFfsFile(CurrentFile, CurrentFv, FvName, Level, FfsCount, E= rasePolarity); + *IsFfsGenerated =3D TRUE; + } + } + + break; + case EFI_SECTION_TE: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + if (!ViewFlag) { + if (!*IsFfsGenerated) { + LibGenFfsFile(CurrentFile, CurrentFv, FvName, Level, FfsCount, E= rasePolarity); + *IsFfsGenerated =3D TRUE; + } + } + break; + + case EFI_SECTION_COMPATIBILITY16: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + if (!ViewFlag) { + if (!*IsFfsGenerated) { + LibGenFfsFile(CurrentFile, CurrentFv, FvName, Level, FfsCount, E= rasePolarity); + *IsFfsGenerated =3D TRUE; + } + } + break; + + case EFI_SECTION_FREEFORM_SUBTYPE_GUID: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + if (!ViewFlag) { + if (!*IsFfsGenerated) { + LibGenFfsFile(CurrentFile, CurrentFv, FvName, Level, FfsCount, E= rasePolarity); + *IsFfsGenerated =3D TRUE; + } + } + break; + + case EFI_SECTION_VERSION: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + break; + case EFI_SECTION_PEI_DEPEX: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + HasDepexSection =3D TRUE; + CurrentFv->FfsAttuibutes[*FfsCount].Depex =3D malloc (SectionLength); + memcpy(CurrentFv->FfsAttuibutes[*FfsCount].Depex, Ptr, SectionLength= ); + CurrentFv->FfsAttuibutes[*FfsCount].DepexLen =3D SectionLength; + break; + case EFI_SECTION_DXE_DEPEX: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + HasDepexSection =3D TRUE; + CurrentFv->FfsAttuibutes[*FfsCount].Depex =3D malloc (SectionLength); + memcpy(CurrentFv->FfsAttuibutes[*FfsCount].Depex, Ptr, SectionLength= ); + CurrentFv->FfsAttuibutes[*FfsCount].DepexLen =3D SectionLength; + break; + case EFI_SECTION_SMM_DEPEX: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + HasDepexSection =3D TRUE; + CurrentFv->FfsAttuibutes[*FfsCount].Depex =3D malloc (SectionLength); + memcpy(CurrentFv->FfsAttuibutes[*FfsCount].Depex, Ptr, SectionLength= ); + CurrentFv->FfsAttuibutes[*FfsCount].DepexLen =3D SectionLength; + break; + + case EFI_SECTION_USER_INTERFACE: + NumberOfSections ++; + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + + UiSectionLength =3D GetLength (((EFI_USER_INTERFACE_SECTION *) Ptr)-= >CommonHeader.Size); + if (UiSectionLength =3D=3D 0xffffff) { + UiSectionLength =3D ((EFI_USER_INTERFACE_SECTION2 *) Ptr)->CommonH= eader.ExtendedSize; + UINameSize =3D UiSectionLength - sizeof(EFI_COMMON_SECTION_HEAD= ER2); + } else { + UINameSize =3D UiSectionLength - sizeof(EFI_COMMON_SECTION_HEADER); + } + + UIName =3D (CHAR16 *) malloc (UINameSize + 2); + if (UIName !=3D NULL) { + memset (UIName, '\0', UINameSize + 2); + if (UiSectionLength >=3D 0xffffff) { + memcpy(UIName, ((EFI_USER_INTERFACE_SECTION2 *) Ptr)->FileNameSt= ring, UINameSize); + } else { + memcpy(UIName, ((EFI_USER_INTERFACE_SECTION *) Ptr)->FileNameStr= ing, UINameSize); + } + } else { + Error ("FMMT", 0, 0001, "Memory allocate error!", NULL); + return EFI_OUT_OF_RESOURCES; + } + + BlankChar =3D LibConstructBlankChar( CurrentFv->FvLevel * 2); + if (BlankChar =3D=3D NULL) { + free(UIName); + return EFI_OUT_OF_RESOURCES; + } + + if (ViewFlag) { + UIFileName =3D malloc (UINameSize + 2); + if (UIFileName =3D=3D NULL) { + Error ("FMMT", 0, 4001, "Memory allocation fail!", NULL); + free (UIName); + free (BlankChar); + return EFI_OUT_OF_RESOURCES; + } + Unicode2AsciiString (UIName, UIFileName); + fprintf(stdout, "%sFile \"%s\"\n", BlankChar, UIFileName); + free(UIFileName); + } + free (BlankChar); + + // + // If Ffs file has been generated, then the FfsCount should decrease= 1. + // + if (*IsFfsGenerated) { + memcpy (CurrentFv->FfsAttuibutes[*FfsCount -1].UiName, UIName, UIN= ameSize); + CurrentFv->FfsAttuibutes[*FfsCount -1].UiNameSize =3D UINameSize; + } else { + memcpy (CurrentFv->FfsAttuibutes[*FfsCount].UiName, UIName, UIName= Size); + CurrentFv->FfsAttuibutes[*FfsCount].UiNameSize =3D UINameSize; + } + + HasDepexSection =3D FALSE; + free(UIName); + UINameSize =3D 0; + + break; + default: + break; + } + + ParsedLength +=3D SectionLength; + // + // We make then next section begin on a 4-byte boundary + // + ParsedLength =3D GetOccupiedSize (ParsedLength, 4); + } + + if (ParsedLength < BufferLength) { + Error ("FMMT", 0, 0003, "sections do not completely fill the sectioned= buffer being parsed", NULL); + return EFI_SECTION_ERROR; + } + + + return EFI_SUCCESS; +} + +/** + + Iterates through the files contained within the firmware volume + + @param[in] Fv - Address of the Fv in memory + @param[in] Key - Should be 0 to get the first file. After that, it s= hould be + passed back in without modifying it's contents to re= trieve + subsequent files. + @param[in] File- Output file pointer + File =3D=3D NULL - invalid parameter + otherwise - *File will be update to the location of = the file + + @return EFI_STATUS + EFI_NOT_FOUND + EFI_VOLUME_CORRUPTED + +**/ +EFI_STATUS +FvBufFindNextFile ( + IN VOID *Fv, + IN OUT UINTN *Key, + OUT VOID **File + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *hdr; + EFI_FFS_FILE_HEADER *fhdr; + EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExtHeader; + EFI_FVB_ATTRIBUTES_2 FvbAttributes; + UINTN fsize; + EFI_STATUS Status; + UINTN fvSize; + + hdr =3D (EFI_FIRMWARE_VOLUME_HEADER*)Fv; + fhdr =3D NULL; + + if (Fv =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + Status =3D FvBufGetSize (Fv, &fvSize); + if (EFI_ERROR (Status)) { + return Status; + } + + if (*Key =3D=3D 0) { + if (hdr->ExtHeaderOffset !=3D 0) { + // + // Searching for files starts on an 8 byte aligned boundary after th= e end of the Extended Header if it exists. + // + FwVolExtHeader =3D (EFI_FIRMWARE_VOLUME_EXT_HEADER *)((UINT8 *)hdr += hdr->ExtHeaderOffset); + *Key =3D (UINTN)hdr->ExtHeaderOffset + FwVolExtHeader->ExtHeaderSize; + *Key =3D (UINTN)ALIGN_POINTER(*Key, 8); + } else { + *Key =3D hdr->HeaderLength; + } + } + + FvbAttributes =3D hdr->Attributes; + + for( + *Key =3D (UINTN)ALIGN_POINTER (*Key, 8); + (*Key + sizeof (*fhdr)) < fvSize; + *Key =3D (UINTN)ALIGN_POINTER (*Key, 8) + ) { + fhdr =3D (EFI_FFS_FILE_HEADER*) ((UINT8*)hdr + *Key); + fsize =3D GetFfsFileLength (fhdr); + if (!EFI_TEST_FFS_ATTRIBUTES_BIT( + FvbAttributes, + fhdr->State, + EFI_FILE_HEADER_VALID + ) || + EFI_TEST_FFS_ATTRIBUTES_BIT( + FvbAttributes, + fhdr->State, + EFI_FILE_HEADER_INVALID + ) + ) { + *Key =3D *Key + 1; + continue; + } else if( + EFI_TEST_FFS_ATTRIBUTES_BIT( + FvbAttributes, + fhdr->State, + EFI_FILE_MARKED_FOR_UPDATE + ) || + EFI_TEST_FFS_ATTRIBUTES_BIT( + FvbAttributes, + fhdr->State, + EFI_FILE_DELETED + ) + ) { + *Key =3D *Key + fsize; + continue; + } else if (EFI_TEST_FFS_ATTRIBUTES_BIT( + FvbAttributes, + fhdr->State, + EFI_FILE_DATA_VALID + ) + ) { + *File =3D (UINT8*)hdr + *Key; + *Key =3D *Key + fsize; + return EFI_SUCCESS; + } + + *Key =3D *Key + 1; + } + + return EFI_NOT_FOUND; +} + +/** + + TODO: Add function description + + FvImage - TODO: add argument description + FileHeader - TODO: add argument description + ErasePolarity - TODO: add argument description + + EFI_SUCCESS - TODO: Add description for return value + EFI_ABORTED - TODO: Add description for return value + +**/ +EFI_STATUS +LibGetFileInfo ( + EFI_FIRMWARE_VOLUME_HEADER *FvImage, + EFI_FFS_FILE_HEADER2 *CurrentFile, + BOOLEAN ErasePolarity, + FV_INFORMATION *CurrentFv, + CHAR8 *FvName, + UINT8 Level, + ENCAP_INFO_DATA **CurrentFvEncapData, + UINT32 *FfsCount, + UINT8 *FvCount, + BOOLEAN ViewFlag + ) +{ + UINT32 FileLength; + UINT8 FileState; + UINT8 Checksum; + EFI_FFS_FILE_HEADER2 BlankHeader; + EFI_STATUS Status; + UINT8 GuidBuffer[PRINTED_GUID_BUFFER_SIZE]; + ENCAP_INFO_DATA *LocalEncapData; + BOOLEAN EncapDataNeedUpdateFlag; + BOOLEAN IsGeneratedFfs; + UINT32 FfsFileHeaderSize; + + Status =3D EFI_SUCCESS; + + LocalEncapData =3D NULL; + EncapDataNeedUpdateFlag =3D TRUE; + IsGeneratedFfs =3D FALSE; + + FfsFileHeaderSize =3D GetFfsHeaderLength ((EFI_FFS_FILE_HEADER *) Curre= ntFile); + FileLength =3D GetFfsFileLength ((EFI_FFS_FILE_HEADER *) CurrentF= ile); + + // + // Check if we have free space + // + if (ErasePolarity) { + memset (&BlankHeader, -1, FfsFileHeaderSize); + } else { + memset (&BlankHeader, 0, FfsFileHeaderSize); + } + + // + // Is this FV blank? + // + if (memcmp (&BlankHeader, CurrentFile, FfsFileHeaderSize) =3D=3D 0) { + return EFI_SUCCESS; + } + + // + // Print file information. + // + FileState =3D GetFileState (ErasePolarity, (EFI_FFS_FILE_HEADER *)Curren= tFile); + PrintGuidToBuffer (&(CurrentFile->Name), GuidBuffer, PRINTED_GUID_BUFFER= _SIZE, FALSE); + if (FileState =3D=3D EFI_FILE_DATA_VALID) { + // + // Calculate header checksum + // + Checksum =3D CalculateSum8 ((UINT8 *) CurrentFile, FfsFileHeaderSize); + Checksum =3D (UINT8) (Checksum - CurrentFile->IntegrityCheck.Checksum= .File); + Checksum =3D (UINT8) (Checksum - CurrentFile->State); + if (Checksum !=3D 0) { + Error ("FMMT", 0, 0003, "error parsing FFS file", "FFS file with Gui= d %s has invalid header checksum", GuidBuffer); + return EFI_ABORTED; + } + + if (CurrentFile->Attributes & FFS_ATTRIB_CHECKSUM) { + // + // Calculate file checksum + // + Checksum =3D CalculateSum8 ((UINT8 *) ((UINTN)CurrentFile + FfsFile= HeaderSize), FileLength - FfsFileHeaderSize); + Checksum =3D Checksum + CurrentFile->IntegrityCheck.Checksum.File; + if (Checksum !=3D 0) { + Error ("FMMT", 0, 0003, "error parsing FFS file", "FFS file with G= uid %s has invalid file checksum", GuidBuffer); + return EFI_ABORTED; + } + } else { + if (CurrentFile->IntegrityCheck.Checksum.File !=3D FFS_FIXED_CHECKSU= M) { + Error ("FMMT", 0, 0003, "error parsing FFS file", "FFS file with G= uid %s has invalid header checksum -- not set to fixed value of 0xAA", Guid= Buffer); + return EFI_ABORTED; + } + } + } else { + Error ("FMMT", 0, 0003, "error parsing FFS file", "FFS file with Guid = %s has the invalid/unrecognized file state bits", GuidBuffer); + return EFI_ABORTED; + } + + Level +=3D 1; + + if ((CurrentFile->Type !=3D EFI_FV_FILETYPE_ALL) && (CurrentFile->Type != =3D EFI_FV_FILETYPE_FFS_PAD)) { + + // + // Put in encapsulate data information. + // + LocalEncapData =3D *CurrentFvEncapData; + if (LocalEncapData->NextNode !=3D NULL) { + LocalEncapData =3D LocalEncapData->NextNode; + EncapDataNeedUpdateFlag =3D FALSE; + while (LocalEncapData->RightNode !=3D NULL) { + LocalEncapData =3D LocalEncapData->RightNode; + } + } + + if (EncapDataNeedUpdateFlag) { + // + // Construct the new ENCAP_DATA + // + LocalEncapData->NextNode =3D (ENCAP_INFO_DATA *) malloc (sizeof (ENC= AP_INFO_DATA)); + + if (LocalEncapData->NextNode =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + LocalEncapData =3D LocalEncapData->NextNode; + + LocalEncapData->Level =3D Level; + LocalEncapData->Type =3D FMMT_ENCAP_TREE_FFS; + LocalEncapData->FvExtHeader =3D NULL; + LocalEncapData->Depex =3D NULL; + LocalEncapData->DepexLen =3D 0; + LocalEncapData->UiNameSize =3D 0; + // + // Store the header of FFS file. + // + LocalEncapData->Data =3D malloc (FfsFileHeaderSize); + if (LocalEncapData->Data =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + memcpy (LocalEncapData->Data, CurrentFile, FfsFileHeaderSize); + LocalEncapData->FvExtHeader =3D (EFI_FIRMWARE_VOLUME_EXT_HEADER *)ma= lloc(sizeof(EFI_FIRMWARE_VOLUME_EXT_HEADER)); + if (LocalEncapData->FvExtHeader =3D=3D NULL) { + Error(NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + LocalEncapData->FvExtHeader->FvName.Data1 =3D CurrentFile->Name.Data= 1; + LocalEncapData->FvExtHeader->FvName.Data2 =3D CurrentFile->Name.Data= 2; + LocalEncapData->FvExtHeader->FvName.Data3 =3D CurrentFile->Name.Data= 3; + LocalEncapData->FvExtHeader->FvName.Data4[0] =3D CurrentFile->Name.D= ata4[0]; + LocalEncapData->FvExtHeader->FvName.Data4[1] =3D CurrentFile->Name.D= ata4[1]; + LocalEncapData->FvExtHeader->FvName.Data4[2] =3D CurrentFile->Name.D= ata4[2]; + LocalEncapData->FvExtHeader->FvName.Data4[3] =3D CurrentFile->Name.D= ata4[3]; + LocalEncapData->FvExtHeader->FvName.Data4[4] =3D CurrentFile->Name.D= ata4[4]; + LocalEncapData->FvExtHeader->FvName.Data4[5] =3D CurrentFile->Name.D= ata4[5]; + LocalEncapData->FvExtHeader->FvName.Data4[6] =3D CurrentFile->Name.D= ata4[6]; + LocalEncapData->FvExtHeader->FvName.Data4[7] =3D CurrentFile->Name.D= ata4[7]; + LocalEncapData->NextNode =3D NULL; + LocalEncapData->RightNode =3D NULL; + }else{ + // + // Construct the new ENCAP_DATA + // + LocalEncapData->RightNode =3D (ENCAP_INFO_DATA *) malloc (sizeof (EN= CAP_INFO_DATA)); + + if (LocalEncapData->RightNode =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + LocalEncapData =3D LocalEncapData->RightNode; + + LocalEncapData->Level =3D Level; + LocalEncapData->Type =3D FMMT_ENCAP_TREE_FFS; + LocalEncapData->FvExtHeader =3D NULL; + LocalEncapData->Depex =3D NULL; + LocalEncapData->DepexLen =3D 0; + LocalEncapData->UiNameSize =3D 0; + // + // Store the header of FFS file. + // + LocalEncapData->Data =3D malloc (FfsFileHeaderSize); + if (LocalEncapData->Data =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + memcpy (LocalEncapData->Data, CurrentFile, FfsFileHeaderSize); + LocalEncapData->FvExtHeader =3D (EFI_FIRMWARE_VOLUME_EXT_HEADER *)ma= lloc(sizeof(EFI_FIRMWARE_VOLUME_EXT_HEADER)); + if (LocalEncapData->FvExtHeader =3D=3D NULL) { + Error(NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + LocalEncapData->FvExtHeader->FvName.Data1 =3D CurrentFile->Name.Data= 1; + LocalEncapData->FvExtHeader->FvName.Data2 =3D CurrentFile->Name.Data= 2; + LocalEncapData->FvExtHeader->FvName.Data3 =3D CurrentFile->Name.Data= 3; + LocalEncapData->FvExtHeader->FvName.Data4[0] =3D CurrentFile->Name.D= ata4[0]; + LocalEncapData->FvExtHeader->FvName.Data4[1] =3D CurrentFile->Name.D= ata4[1]; + LocalEncapData->FvExtHeader->FvName.Data4[2] =3D CurrentFile->Name.D= ata4[2]; + LocalEncapData->FvExtHeader->FvName.Data4[3] =3D CurrentFile->Name.D= ata4[3]; + LocalEncapData->FvExtHeader->FvName.Data4[4] =3D CurrentFile->Name.D= ata4[4]; + LocalEncapData->FvExtHeader->FvName.Data4[5] =3D CurrentFile->Name.D= ata4[5]; + LocalEncapData->FvExtHeader->FvName.Data4[6] =3D CurrentFile->Name.D= ata4[6]; + LocalEncapData->FvExtHeader->FvName.Data4[7] =3D CurrentFile->Name.D= ata4[7]; + LocalEncapData->RightNode =3D NULL; + LocalEncapData->NextNode =3D NULL; + } + + if ( CurrentFile->Type =3D=3D EFI_FV_FILETYPE_RAW){ + CurrentFv->FfsAttuibutes[*FfsCount].Level =3D Level; + if (!ViewFlag){ + LibGenFfsFile(CurrentFile, CurrentFv, FvName, Level, FfsCount, Era= sePolarity); + } + } else if( CurrentFile->Type =3D=3D EFI_FV_FILETYPE_FFS_PAD){ + //EFI_FV_FILETYPE_FFS_PAD + } else { + // + // All other files have sections + // + Status =3D LibParseSection ( + (UINT8 *) ((UINTN) CurrentFile + FfsFileHeaderSize), + FileLength - FfsFileHeaderSize, + CurrentFv, + FvName, + CurrentFile, + Level, + &LocalEncapData, + Level, + FfsCount, + FvCount, + ViewFlag, + ErasePolarity, + &IsGeneratedFfs + ); + } + if (EFI_ERROR (Status)) { + printf ("ERROR: Parsing the FFS file.\n"); + return Status; + } + } + + + return EFI_SUCCESS; +} + +/** + + Get firmware information. Including the FV headers, + + @param[in] Fv - Firmware Volume to get information from + + @return EFI_STATUS + +**/ +EFI_STATUS +LibGetFvInfo ( + IN VOID *Fv, + IN OUT FV_INFORMATION *CurrentFv, + IN CHAR8 *FvName, + IN UINT8 Level, + IN ENCAP_INFO_DATA **CurrentFvEncapData, + IN UINT32 *FfsCount, + IN OUT UINT8 *FvCount, + IN BOOLEAN ViewFlag, + IN BOOLEAN IsChildFv + ) +{ + EFI_STATUS Status; + UINTN NumberOfFiles; + BOOLEAN ErasePolarity; + UINTN FvSize; + EFI_FFS_FILE_HEADER2 *CurrentFile; + UINTN Key; + ENCAP_INFO_DATA *LocalEncapData; + EFI_FIRMWARE_VOLUME_EXT_HEADER *ExtHdrPtr; + EFI_FIRMWARE_VOLUME_HEADER *FvHdr; + + NumberOfFiles =3D 0; + Key =3D 0; + LocalEncapData =3D NULL; + CurrentFile =3D NULL; + FvHdr =3D (EFI_FIRMWARE_VOLUME_HEADER *)Fv; + + + Level +=3D 1; + *FvCount +=3D 1; + CurrentFv->FvLevel +=3D 1; + + Status =3D FvBufGetSize (Fv, &FvSize); + + ErasePolarity =3D (((EFI_FIRMWARE_VOLUME_HEADER*)Fv)->Attributes & EFI_F= VB2_ERASE_POLARITY) ? TRUE : FALSE; + + Status =3D LibReadFvHeader (Fv, ViewFlag, CurrentFv->FvLevel, *FvCount -= 1, CurrentFv->FvName); + if (EFI_ERROR (Status)) { + Error (NULL, 0, 0003, "error parsing FV image", "Header is invalid"); + return EFI_ABORTED; + } + + if (!IsChildFv) { + // + // Write FV header information into CurrentFv struct. + // + CurrentFv->FvHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *) malloc (FvHdr->= HeaderLength); + + if (CurrentFv->FvHeader =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + // + // Get the FV Header information + // + memcpy(CurrentFv->FvHeader, Fv, FvHdr->HeaderLength); + CurrentFv->FvExtHeader =3D NULL; + CurrentFv->FvUiName =3D NULL; + + // + // Exist Extend FV header. + // + if (CurrentFv->FvHeader->ExtHeaderOffset !=3D 0){ + ExtHdrPtr =3D (VOID *)((UINTN)Fv + CurrentFv->FvHeader->ExtHeaderOff= set); + CurrentFv->FvExtHeader =3D (EFI_FIRMWARE_VOLUME_EXT_HEADER *) malloc= (ExtHdrPtr->ExtHeaderSize); + + if (CurrentFv->FvExtHeader =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + // + // Get the FV extended Header information + // + memcpy (CurrentFv->FvExtHeader, (VOID *)((UINTN)Fv + CurrentFv->FvHe= ader->ExtHeaderOffset), ExtHdrPtr->ExtHeaderSize); + LibExtractFvUiName(CurrentFv->FvExtHeader, &CurrentFv->FvUiName); + } + } + + // + // Put encapsulate information into structure. + // + LocalEncapData =3D *CurrentFvEncapData; + if (LocalEncapData =3D=3D NULL && !IsChildFv) { + // + // First time in, the root FV + // + LocalEncapData =3D (ENCAP_INFO_DATA *) malloc (sizeof (ENCAP_INFO_DATA= )); + CurrentFv->EncapData =3D LocalEncapData; + if (CurrentFv->EncapData =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + CurrentFv->EncapData->FvExtHeader =3D NULL; + CurrentFv->EncapData->Depex =3D NULL; + CurrentFv->EncapData->DepexLen =3D 0; + CurrentFv->EncapData->UiNameSize =3D 0; + CurrentFv->EncapData->Level =3D Level; + CurrentFv->EncapData->Type =3D FMMT_ENCAP_TREE_FV; + CurrentFv->EncapData->Data =3D (EFI_FIRMWARE_VOLUME_HEADER *) malloc = (sizeof (EFI_FIRMWARE_VOLUME_HEADER)); + CurrentFv->EncapData->FvId =3D *FvCount; + + if (CurrentFv->EncapData->Data =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + memcpy (CurrentFv->EncapData->Data, Fv, sizeof (EFI_FIRMWARE_VOLUME_HE= ADER)); + + if (((EFI_FIRMWARE_VOLUME_HEADER *)(CurrentFv->EncapData->Data))->ExtH= eaderOffset !=3D 0) { + ExtHdrPtr =3D (VOID *)((UINTN)Fv + ((EFI_FIRMWARE_VOLUME_HEADER *)(C= urrentFv->EncapData->Data))->ExtHeaderOffset); + CurrentFv->EncapData->FvExtHeader =3D (EFI_FIRMWARE_VOLUME_EXT_HEADE= R *) malloc (ExtHdrPtr->ExtHeaderSize); + + if (CurrentFv->EncapData->FvExtHeader =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + // + // Get the FV extended Header information + // + memcpy(CurrentFv->EncapData->FvExtHeader, (VOID *)((UINTN)Fv + ((EFI= _FIRMWARE_VOLUME_HEADER *)(CurrentFv->EncapData->Data))->ExtHeaderOffset), = ExtHdrPtr->ExtHeaderSize); + } + + CurrentFv->EncapData->NextNode =3D NULL; + CurrentFv->EncapData->RightNode =3D NULL; + } else if (LocalEncapData =3D=3D NULL) { + return EFI_ABORTED; + } else if (IsChildFv) { + + LocalEncapData =3D *CurrentFvEncapData; + while (LocalEncapData->NextNode !=3D NULL) { + LocalEncapData =3D LocalEncapData->NextNode; + } + + // + // Construct the new ENCAP_DATA + // + LocalEncapData->NextNode =3D (ENCAP_INFO_DATA *) malloc (sizeof (ENC= AP_INFO_DATA)); + + if (LocalEncapData->NextNode =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + LocalEncapData =3D LocalEncapData->NextNode; + + LocalEncapData->Level =3D Level; + LocalEncapData->Type =3D FMMT_ENCAP_TREE_FV; + LocalEncapData->Data =3D (EFI_FIRMWARE_VOLUME_HEADER *) malloc (siz= eof (EFI_FIRMWARE_VOLUME_HEADER)); + LocalEncapData->FvExtHeader =3D NULL; + LocalEncapData->Depex =3D NULL; + LocalEncapData->DepexLen =3D 0; + LocalEncapData->UiNameSize =3D 0; + LocalEncapData->FvId =3D *FvCount; + if (LocalEncapData->Data =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + memcpy (LocalEncapData->Data, Fv, sizeof (EFI_FIRMWARE_VOLUME_HEADER= )); + + if (((EFI_FIRMWARE_VOLUME_HEADER *)(LocalEncapData->Data))->ExtHeade= rOffset !=3D 0) { + ExtHdrPtr =3D (VOID *)((UINTN)Fv + ((EFI_FIRMWARE_VOLUME_HEADER *)= (LocalEncapData->Data))->ExtHeaderOffset); + LocalEncapData->FvExtHeader =3D (EFI_FIRMWARE_VOLUME_EXT_HEADER *)= malloc(ExtHdrPtr->ExtHeaderSize); + + if (LocalEncapData->FvExtHeader =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + + // + // Get the FV extended Header information + // + memcpy(LocalEncapData->FvExtHeader, (VOID *)((UINTN)Fv + ((EFI_FIR= MWARE_VOLUME_HEADER *)(LocalEncapData->Data))->ExtHeaderOffset), ExtHdrPtr-= >ExtHeaderSize); + } + + LocalEncapData->NextNode =3D NULL; + LocalEncapData->RightNode =3D NULL; + + } + + + // + // Get the first file + // + Status =3D FvBufFindNextFile (Fv, &Key, (VOID **) &CurrentFile); + if (Status =3D=3D EFI_NOT_FOUND) { + CurrentFile =3D NULL; + } else if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0003, "error parsing FV image", "cannot find the fir= st file in the FV image"); + return Status; + } + + while (CurrentFile !=3D NULL) { + + // + // Increment the number of files counter + // + NumberOfFiles++; + + // + // Store FFS file Header information + // + CurrentFv->FfsHeader[*FfsCount].Attributes =3D CurrentFile->Attr= ibutes; + CurrentFv->FfsHeader[*FfsCount].IntegrityCheck =3D CurrentFile->Inte= grityCheck; + CurrentFv->FfsHeader[*FfsCount].Name =3D CurrentFile->Name; + CurrentFv->FfsHeader[*FfsCount].Size[0] =3D CurrentFile->Size= [0]; + CurrentFv->FfsHeader[*FfsCount].Size[1] =3D CurrentFile->Size= [1]; + CurrentFv->FfsHeader[*FfsCount].Size[2] =3D CurrentFile->Size= [2]; + CurrentFv->FfsHeader[*FfsCount].State =3D CurrentFile->Stat= e; + CurrentFv->FfsHeader[*FfsCount].Type =3D CurrentFile->Type; + CurrentFv->FfsHeader[*FfsCount].ExtendedSize =3D CurrentFile->Exte= ndedSize; + CurrentFv->FfsAttuibutes[*FfsCount].Offset =3D Key - GetFfsFileLength = ((EFI_FFS_FILE_HEADER *) CurrentFile); + + CurrentFv->FfsAttuibutes[*FfsCount].FvLevel =3D CurrentFv->FvLevel; + if (CurrentFv->FvLevel > CurrentFv->MulFvLevel) { + CurrentFv->MulFvLevel =3D CurrentFv->FvLevel; + } + // + // Display info about this file + // + Status =3D LibGetFileInfo (Fv, CurrentFile, ErasePolarity, CurrentFv, = FvName, Level, &LocalEncapData, FfsCount, FvCount, ViewFlag); + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0003, "error parsing FV image", "failed to parse a= file in the FV"); + return Status; + } + + // + // Get the next file + // + Status =3D FvBufFindNextFile (Fv, &Key, (VOID **) &CurrentFile); + if (Status =3D=3D EFI_NOT_FOUND) { + CurrentFile =3D NULL; + } else if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0003, "error parsing FV image", "cannot find the n= ext file in the FV image"); + return Status; + } + } + + if (IsChildFv) { + if (CurrentFv->FvLevel > 1) { + CurrentFv->FvLevel -=3D 1; + } + } + return EFI_SUCCESS; +} + +/** + + This function returns the next larger size that meets the alignment + requirement specified. + + @param[in] ActualSize The size. + @param[in] Alignment The desired alignment. + + @retval EFI_SUCCESS Function completed successfully. + @retval EFI_ABORTED The function encountered an error. + +**/ +UINT32 +GetOccupiedSize ( + IN UINT32 ActualSize, + IN UINT32 Alignment + ) +{ + UINT32 OccupiedSize; + + OccupiedSize =3D ActualSize; + while ((OccupiedSize & (Alignment - 1)) !=3D 0) { + OccupiedSize++; + } + + return OccupiedSize; +} + + + +EFI_STATUS +LibDeleteAndRenameFfs( + IN CHAR8* DeleteFile, + IN CHAR8* NewFile +) +{ + CHAR8* SystemCommand; + CHAR8* TemDir; + SystemCommand =3D NULL; + + if (DeleteFile =3D=3D NULL || + NewFile =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Delete the file of the specified extract FFS file. + // + SystemCommand =3D malloc ( + strlen (DEL_STR) + + strlen (DeleteFile) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + sprintf ( + SystemCommand, + DEL_STR, + DeleteFile + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + + TemDir =3D getcwd (NULL, _MAX_PATH); + if (strlen (TemDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _MAX= _PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return EFI_ABORTED; + } + strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen(TemDir) - 1); + strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen(TemDir) - 1); + + mkdir(TemDir, S_IRWXU | S_IRWXG | S_IRWXO); + // + // Create a copy the new file. + // + + SystemCommand =3D malloc ( + strlen (COPY_STR) + + strlen (NewFile) + + strlen (DeleteFile) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + sprintf ( + SystemCommand, + COPY_STR, + NewFile, + DeleteFile + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + + return EFI_SUCCESS; + +} + +/** + Converts ASCII characters to Unicode. + Assumes that the Unicode characters are only these defined in the ASCII = set. + + String - Pointer to string that is written to FILE. + UniString - Pointer to unicode string + + The address to the ASCII string - same as AsciiStr. + +**/ +VOID +LibAscii2Unicode ( + IN CHAR8 *String, + OUT CHAR16 *UniString + ) +{ + while (*String !=3D '\0') { + *(UniString++) =3D (CHAR16) *(String++); + } + // + // End the UniString with a NULL. + // + *UniString =3D '\0'; +} + + +EFI_STATUS +LibCreateGuidedSectionOriginalData( + IN CHAR8* FileIn, + IN CHAR8* ToolName, + IN CHAR8* FileOut +) +{ + CHAR8* SystemCommandFormatString; + CHAR8* SystemCommand; + + SystemCommandFormatString =3D NULL; + SystemCommand =3D NULL; + + if (FileIn =3D=3D NULL || + ToolName =3D=3D NULL || + FileOut =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Delete the file of the specified extract FFS file. + // + SystemCommandFormatString =3D "%s -e \"%s\" -o \"%s\""; + + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (FileIn) + + strlen (ToolName) + + strlen (FileOut) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + sprintf ( + SystemCommand, + "%s -e \"%s\" -o \"%s\"", + ToolName, + FileIn, + FileOut + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + printf("Command failed: %s\n", SystemCommand); + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + + return EFI_SUCCESS; +} + +/** + + This function convert the FV header's attribute to a string. The conver= ted string + will be put into an INF file as the input of GenFV. + + @param[in] Attr FV header's attribute. + @param[out] InfFile InfFile contain FV header attribute informat= ion. + + @retval EFI_SUCCESS. + @retval EFI_INVLID_PARAMETER + @retval EFI_OUT_OF_RESOURCES + +**/ +EFI_STATUS +LibFvHeaderAttributeToStr ( + IN EFI_FVB_ATTRIBUTES_2 Attr, + IN FILE* InfFile +) +{ + CHAR8 *LocalStr; + + LocalStr =3D NULL; + + LocalStr =3D (CHAR8 *) malloc (1024 * 4); + + if (LocalStr =3D=3D NULL) { + printf ("Memory allocate error!\n"); + return EFI_OUT_OF_RESOURCES; + } + + memset (LocalStr, '\0', 1024 * 4); + + if (Attr =3D=3D 0 || InfFile =3D=3D NULL) { + free (LocalStr); + return EFI_INVALID_PARAMETER; + } + + strncat (LocalStr, "[attributes] \n", sizeof("[attributes] \n")); + + if (Attr & EFI_FVB2_READ_DISABLED_CAP) { + strncat (LocalStr, "EFI_READ_DISABLED_CAP =3D TRUE \n", sizeof ("EFI_R= EAD_DISABLED_CAP =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_READ_ENABLED_CAP) { + strncat (LocalStr, "EFI_READ_ENABLED_CAP =3D TRUE \n", sizeof ("EFI_RE= AD_ENABLED_CAP =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_READ_STATUS) { + strncat (LocalStr, "EFI_READ_STATUS =3D TRUE \n", sizeof ("EFI_READ_ST= ATUS =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_WRITE_DISABLED_CAP) { + strncat (LocalStr, "EFI_WRITE_DISABLED_CAP =3D TRUE \n", sizeof ("EFI_= WRITE_DISABLED_CAP =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_WRITE_ENABLED_CAP) { + strncat (LocalStr, "EFI_WRITE_ENABLED_CAP =3D TRUE \n", sizeof ("EFI_W= RITE_ENABLED_CAP =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_WRITE_STATUS) { + strncat (LocalStr, "EFI_WRITE_STATUS =3D TRUE \n", sizeof ("EFI_WRITE_= STATUS =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_LOCK_CAP) { + strncat (LocalStr, "EFI_LOCK_CAP =3D TRUE \n", sizeof ("EFI_LOCK_CAP = =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_LOCK_STATUS) { + strncat (LocalStr, "EFI_LOCK_STATUS =3D TRUE \n", sizeof ("EFI_LOCK_ST= ATUS =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_STICKY_WRITE) { + strncat (LocalStr, "EFI_STICKY_WRITE =3D TRUE \n", sizeof ("EFI_STICKY= _WRITE =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_MEMORY_MAPPED) { + strncat (LocalStr, "EFI_MEMORY_MAPPED =3D TRUE \n", sizeof ("EFI_MEMOR= Y_MAPPED =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_ERASE_POLARITY) { + strncat (LocalStr, "EFI_ERASE_POLARITY =3D 1 \n", sizeof ("EFI_ERASE_P= OLARITY =3D 1 \n")); + } + + if (Attr & EFI_FVB2_READ_LOCK_CAP) { + strncat (LocalStr, "EFI_READ_LOCK_CAP =3D TRUE \n", sizeof ("EFI_READ_= LOCK_CAP =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_READ_LOCK_STATUS) { + strncat (LocalStr, "EFI_READ_LOCK_STATUS =3D TRUE \n", sizeof ("EFI_RE= AD_LOCK_STATUS =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_WRITE_LOCK_CAP) { + strncat (LocalStr, "EFI_WRITE_LOCK_CAP =3D TRUE \n", sizeof ("EFI_WRIT= E_LOCK_CAP =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_WRITE_LOCK_STATUS) { + strncat (LocalStr, "EFI_WRITE_LOCK_STATUS =3D TRUE \n", sizeof ("EFI_W= RITE_LOCK_STATUS =3D TRUE \n")); + } + + if (Attr & EFI_FVB2_LOCK_STATUS) { + strncat (LocalStr, "EFI_READ_LOCK_STATUS =3D TRUE \n", sizeof ("EFI_RE= AD_LOCK_STATUS =3D TRUE \n")); + } + + // + // Alignment + // + if (Attr & EFI_FVB2_ALIGNMENT_1) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_1 =3D TRUE \n", sizeof ("EFI_FV= B2_ALIGNMENT_1 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_2) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_2 =3D TRUE \n", sizeof ("EFI_FV= B2_ALIGNMENT_2 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_4) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_4 =3D TRUE \n", sizeof ("EFI_FV= B2_ALIGNMENT_4 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_8) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_8 =3D TRUE \n", sizeof ("EFI_FV= B2_ALIGNMENT_8 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_16) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_16 =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_16 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_32) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_32 =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_32 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_64) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_64 =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_64 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_128) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_128 =3D TRUE \n", sizeof ("EFI_= FVB2_ALIGNMENT_128 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_256) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_256 =3D TRUE \n", sizeof ("EFI_= FVB2_ALIGNMENT_256 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_512) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_512 =3D TRUE \n", sizeof ("EFI_= FVB2_ALIGNMENT_512 =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_1K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_1K =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_1K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_2K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_2K =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_2K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_4K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_4K =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_4K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_8K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_8K =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_8K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_16K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_16K =3D TRUE \n", sizeof ("EFI_= FVB2_ALIGNMENT_16K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_32K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_32K =3D TRUE \n", sizeof ("EFI_= FVB2_ALIGNMENT_32K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_64K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_64K =3D TRUE \n", sizeof ("EFI_= FVB2_ALIGNMENT_64K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_128K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_128K =3D TRUE \n", sizeof ("EFI= _FVB2_ALIGNMENT_128K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_256K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_256K =3D TRUE \n", sizeof ("EFI= _FVB2_ALIGNMENT_256K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_512K) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_512K =3D TRUE \n", sizeof ("EFI= _FVB2_ALIGNMENT_512K =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_1M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_1M =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_1M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_2M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_2M =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_2M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_4M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_4M =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_4M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_8M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_8M =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_8M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_16M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_16M =3D TRUE \n", sizeof ("EFI_= FVB2_ALIGNMENT_16M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_32M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_32M =3D TRUE \n", sizeof ("EFI_= FVB2_ALIGNMENT_32M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_64M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_64M =3D TRUE \n", sizeof ("EFI_= FVB2_ALIGNMENT_64M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_128M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_128M =3D TRUE \n", sizeof ("EFI= _FVB2_ALIGNMENT_128M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_256M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_256M =3D TRUE \n", sizeof ("EFI= _FVB2_ALIGNMENT_256M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_512M) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_512M =3D TRUE \n", sizeof ("EFI= _FVB2_ALIGNMENT_512M =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_1G) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_1G =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_1G =3D TRUE \n")); + } else if (Attr & EFI_FVB2_ALIGNMENT_2G) { + strncat (LocalStr, "EFI_FVB2_ALIGNMENT_2G =3D TRUE \n", sizeof ("EFI_F= VB2_ALIGNMENT_2G =3D TRUE \n")); + } + + if (fwrite (LocalStr, 1, (size_t) strlen (LocalStr), InfFile) !=3D (size= _t) strlen (LocalStr)) { + printf ("Error while writing data to %p file.", (void*)InfFile); + free (LocalStr); + return EFI_ABORTED; + } + + free (LocalStr); + + return EFI_SUCCESS; +} + + +/** + This function fill the FV inf files option field. + + @param[in] BlockMap FV header's attribute. + @param[out] InfFile InfFile contain FV header attribute informat= ion. + + @retval EFI_SUCCESS. + @retval EFI_INVLID_PARAMETER + +**/ +EFI_STATUS +LibFvHeaderOptionToStr ( + IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader, + IN FILE* InfFile, + IN BOOLEAN IsRootFv +) +{ + CHAR8 *LocalStr; + CHAR8 *TempStr; + EFI_FV_BLOCK_MAP_ENTRY *BlockMap; + + LocalStr =3D NULL; + TempStr =3D NULL; + + if (FvHeader =3D=3D NULL || InfFile =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // This section will not over 1024 bytes and each line will never over 1= 28 bytes. + // + LocalStr =3D (CHAR8 *) malloc (1024); + TempStr =3D (CHAR8 *) malloc (128); + + if (LocalStr =3D=3D NULL || + TempStr =3D=3D NULL ) { + if (LocalStr !=3D NULL) { + free (LocalStr); + } + if (TempStr !=3D NULL) { + free (TempStr); + } + printf ("Memory allocate error! \n"); + return EFI_OUT_OF_RESOURCES; + } + + BlockMap =3D FvHeader->BlockMap; + memset (LocalStr, '\0', 1024); + memset (TempStr, '\0', 128); + + strncat (LocalStr, "[options] \n", sizeof("[Options] \n")); + + + snprintf (TempStr, 128, "EFI_BLOCK_SIZE =3D 0x%x \n", BlockMap->Length); + strncat (LocalStr, TempStr, strlen(TempStr)); + + if (IsRootFv) { + snprintf (TempStr, 128, "EFI_NUM_BLOCKS =3D 0x%x \n", BlockMap->NumBloc= ks); + strncat (LocalStr, TempStr, strlen(TempStr)); + } + + if (fwrite (LocalStr, 1, (size_t) strlen (LocalStr), InfFile) !=3D (size= _t) strlen (LocalStr)) { + printf ("Error while writing data to %p file.", (void*)InfFile); + free (LocalStr); + free (TempStr); + return EFI_ABORTED; + } + + free (LocalStr); + free (TempStr); + + return EFI_SUCCESS; +} + +/** + This function fill the FV inf files option field. + + @param[in] FfsName Ffs file path/name. + @param[out] InfFile InfFile contain FV header attribute informat= ion + @param[in] FirstIn Is the first time call this function? If yes= , should create [files] section. + + @retval EFI_SUCCESS. + @retval EFI_INVLID_PARAMETER + +**/ +EFI_STATUS +LibAddFfsFileToFvInf ( + IN CHAR8 *FfsName, + IN FILE* InfFile, + IN BOOLEAN FirstIn +) +{ + + CHAR8 *LocalStr; + + LocalStr =3D NULL; + + if (FfsName =3D=3D NULL || InfFile =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + if (strlen(FfsName) =3D=3D 0) { + return EFI_SUCCESS; + } + + LocalStr =3D (CHAR8 *) malloc (_MAX_PATH); + + if (LocalStr =3D=3D NULL) { + printf ("Memory allocate error! \n"); + return EFI_OUT_OF_RESOURCES; + } + + memset (LocalStr, '\0', _MAX_PATH); + + if (FirstIn) { + sprintf (LocalStr, "[files] \nEFI_FILE_NAME =3D %s \n", FfsName); + } else { + sprintf (LocalStr, "EFI_FILE_NAME =3D %s \n", FfsName); + } + + if (fwrite (LocalStr, 1, (size_t) strlen (LocalStr), InfFile) !=3D (size= _t) strlen (LocalStr)) { + printf ("Error while writing data to %p file.", (void*)InfFile); + free (LocalStr); + return EFI_ABORTED; + } + + free (LocalStr); + + return EFI_SUCCESS; +} + + +/** + Convert EFI file to PE or TE section + + @param[in] InputFilePath .efi file, it's optional unless process PE/= TE section. + @param[in] Type PE or TE and UI/Version + @param[in] OutputFilePath .te or .pe file + @param[in] UiString String for generate UI section usage, this = parameter is optional + unless Type is EFI_SECTION_USER_INTERFACE. + @param[in] VerString String for generate Version section usage, = this parameter is optional + unless Type is EFI_SECTION_VERSION. + + @retval EFI_SUCCESS + +**/ +EFI_STATUS +LibCreateFfsSection ( + IN FV_INFORMATION *FvInFd, OPTIONAL + IN CHAR8* InputFilePath, OPTIONAL + IN CHAR8* Sections, OPTIONAL + IN UINT8 Type, + IN CHAR8* OutputFilePath, + IN CHAR8* UiString, OPTIONAL + IN CHAR8* VerString, OPTIONAL + IN CHAR8* GuidToolGuid, OPTIONAL + IN UINT16 GuidHeaderLength, + IN UINT16 GuidAttr, + IN CHAR8* CompressType OPTIONAL + ) +{ + //EFI_STATUS Status; + CHAR8* SystemCommandFormatString; + CHAR8* SystemCommand; + FILE *file; + UINT8 Buffer[4]; + int BitNum; + int Position; + UINT32 AlignmentValue; + // + // Workaround for static code checkers. + // Ensures the size of 'AlignmentStr' can hold all the digits of an + // unsigned 32-bit integer plus the size unit character. + // + char AlignmentStr[16]; + + SystemCommandFormatString =3D NULL; + SystemCommand =3D NULL; + strcpy(AlignmentStr,"1"); + // + // Call GenSec tool to generate FFS section. + // + + // + // -s SectionType. + // + if (Type !=3D 0) { + switch (Type) { + // + // Process compression section + // + case EFI_SECTION_COMPRESSION: + SystemCommandFormatString =3D "GenSec -s %s -c %s \"%s\" -o \"%s\= ""; + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (mSectionTypeName[Type]) + + strlen (CompressType) + + strlen (InputFilePath) + + strlen (OutputFilePath) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + sprintf ( + SystemCommand, + "GenSec -s %s -c %s \"%s\" -o \"%s\"", + mSectionTypeName[Type], + CompressType, + InputFilePath, + OutputFilePath + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + break; + + // + // Process GUID defined section + // + case EFI_SECTION_GUID_DEFINED: + SystemCommandFormatString =3D "GenSec -s %s -g %s \"%s\" -o \"%s\"= -r %s -r %s -l %d"; + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (mSectionTypeName[Type]) + + strlen (GuidToolGuid) + + strlen (InputFilePath) + + strlen (OutputFilePath) + + strlen (mGuidSectionAttr[GuidAttr&0x01]) + + strlen (mGuidSectionAttr[GuidAttr&0x02]) + + 4 + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + sprintf ( + SystemCommand, + "GenSec -s %s -g %s \"%s\" -o \"%s\" -r %s -r %s -l %d", + mSectionTypeName[Type], + GuidToolGuid, + InputFilePath, + OutputFilePath, + mGuidSectionAttr[GuidAttr&0x01], + mGuidSectionAttr[GuidAttr&0x02], + GuidHeaderLength + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + break; + + case EFI_SECTION_FIRMWARE_VOLUME_IMAGE: + + SystemCommandFormatString =3D "GenSec -s %s \"%s\" -o \"%s\""; + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (mSectionTypeName[Type]) + + strlen (InputFilePath) + + strlen (OutputFilePath) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NUL= L); + return EFI_ABORTED; + } + sprintf ( + SystemCommand, + "GenSec -s %s \"%s\" -o \"%s\"", + mSectionTypeName[Type], + InputFilePath, + OutputFilePath + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + break; + + default: + Error ("FMMT", 0, 0003, "Please specify the section type while cal= l GenSec tool.", NULL); + return EFI_UNSUPPORTED; + } + } else { + // + // Create Dummy section. + // + file =3D fopen(InputFilePath, "rb"); + if (file =3D=3D NULL) { + Error(NULL, 0, 0001, "Error opening the file", InputFilePath); + return EFI_INVALID_PARAMETER; + } + // The Section Struct, 3 bits for Size, then 1 bit for Type + if (fread(Buffer, 1, (size_t)(4), file) !=3D (size_t)(4)) { + fclose(file); + return EFI_ABORTED; + } + if (*(Buffer + 3) =3D=3D EFI_SECTION_FIRMWARE_VOLUME_IMAGE) { + // The Section Struct, if size is not 0xFFFF, the length is 4 + Position =3D 4; + // If Size is 0xFFFFFF then ExtendedSize contains the size of the se= ction + if ((*Buffer =3D=3D 0xFF) && (*(Buffer + 1) =3D=3D 0xFF) && (*(Buffe= r + 2) =3D=3D 0xFF)) { + Position =3D 8; + } + //Per EFI_FIRMWARE_VOLUME_HEADER struct, 0x2E bit is EFI_FVB_ATTRIBU= TES_2 attr + fseek(file, 0x2E + Position, SEEK_SET); + BitNum =3D fgetc(file); + AlignmentValue =3D 1 << (BitNum & 0x1F); + if (AlignmentValue >=3D 0x400){ + if (AlignmentValue >=3D 0x10000){ + strcpy(AlignmentStr,"64K"); + } + else{ + sprintf(AlignmentStr, "%d", AlignmentValue/0x400); + strcat(AlignmentStr, "K"); + } + } + else{ + sprintf(AlignmentStr, "%d", AlignmentValue); + } + strcpy(FvInFd->AlignmentStr, AlignmentStr); + } + fclose(file); + SystemCommandFormatString =3D "GenSec \"%s\" -o \"%s\" --sectionalign = %s"; + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (InputFilePath) + + strlen (OutputFilePath) + + 4 + // Alignment maximum length + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + sprintf ( + SystemCommand, + "GenSec \"%s\" -o \"%s\" --sectionalign %s", + InputFilePath, + OutputFilePath, + AlignmentStr + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + + } + + return EFI_SUCCESS; +} + +/** + Encapsulate FFSs to FV + + @param[in] InputFilePath Section file will be read into this FFS fil= e. This option is required. + @param[in] OutputFilePath The created PI firmware file name. This opt= ion is required. + @param[in] BlockSize BlockSize is one HEX or DEC format value re= quired by FV image. + @param[in] FileTakeSize + + @retval EFI_SUCCESS + +**/ +EFI_STATUS +LibEncapsulateFfsToFv ( + IN CHAR8* InfFilePath, + IN CHAR8* InputFFSs, + IN CHAR8* OutputFilePath, + IN CHAR8* FvGuidName, + IN BOOLEAN IsLargeFile + ) +{ + + CHAR8* SystemCommandFormatString; + CHAR8* SystemCommand; + CHAR8* FfsGuid =3D "8c8ce578-8a3d-4f1c-9935-896185c32dd3= "; + + if (IsLargeFile =3D=3D TRUE) { + FfsGuid =3D "5473c07a-3dcb-4dca-bd6f-1e9689e7349a"; + } + + SystemCommandFormatString =3D NULL; + SystemCommand =3D NULL; + + if (OutputFilePath =3D=3D NULL || + InfFilePath =3D=3D NULL ) { + return EFI_INVALID_PARAMETER; + } + + if (InfFilePath !=3D NULL) { + if (FvGuidName =3D=3D NULL) { + SystemCommandFormatString =3D "GenFv -i \"%s\" -g %s -o \"%s\""; + + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (InfFilePath) + + strlen (FfsGuid) + + strlen (OutputFilePath) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + sprintf ( + SystemCommand, + "GenFv -i \"%s\" -g %s -o \"%s\"", + InfFilePath, // -i + FfsGuid, // -g + OutputFilePath // -o + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + + free(SystemCommand); + } else { + // + // Have FvGuidName in it. + // + SystemCommandFormatString =3D "GenFv -i \"%s\" -g %s -o \"%s\" --FvN= ameGuid %s"; + + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (InfFilePath) + + strlen (FfsGuid) + + strlen (OutputFilePath) + + strlen (FvGuidName) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + sprintf ( + SystemCommand, + "GenFv -i \"%s\" -g %s -o \"%s\" --FvNameGuid %s", + InfFilePath, // -i + FfsGuid, // -g + OutputFilePath, // -o + FvGuidName // FvNameGuid + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + + } + } + + return EFI_SUCCESS; +} + + +/** + + Convert a GUID to a string. + + + @param[in] Guid - Pointer to GUID to print. + + + @return The string after convert. + +**/ +CHAR8 * +LibFmmtGuidToStr ( + IN EFI_GUID *Guid +) +{ + CHAR8 * Buffer; + + Buffer =3D NULL; + + if (Guid =3D=3D NULL) { + printf ("The guid is NULL while convert guid to string! \n"); + return NULL; + } + + Buffer =3D (CHAR8 *) malloc (36 + 1); + + if (Buffer =3D=3D NULL) { + printf ("Error while allocate resource! \n"); + return NULL; + } + memset (Buffer, '\0', 36 + 1); + + sprintf ( + Buffer, + "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", + Guid->Data1, + Guid->Data2, + Guid->Data3, + Guid->Data4[0], + Guid->Data4[1], + Guid->Data4[2], + Guid->Data4[3], + Guid->Data4[4], + Guid->Data4[5], + Guid->Data4[6], + Guid->Data4[7] + ); + + return Buffer; +} + + +/** + Encapsulate an FFS section file to an FFS file. + + @param[in] Type Type is one FV file type defined in PI spec= , which is one type of EFI_FV_FILETYPE_RAW, EFI_FV_FILETYPE_FREEFORM, + EFI_FV_FILETYPE_SECURITY_CORE, EFI_FV_FILET= YPE_PEIM, EFI_FV_FILETYPE_PEI_CORE, EFI_FV_FILETYPE_DXE_CORE, + EFI_FV_FILETYPE_DRIVER, EFI_FV_FILETYPE_APP= LICATION, EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER, + EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE. This= option is required. + @param[in] InputFilePath Section file will be read into this FFS fil= e. This option is required. + @param[in] OutputFilePath The created PI firmware file name. This opt= ion is required. + @param[in] FileGuid FileGuid is the unique identifier for this = FFS file. This option is required. + @param[in] Fixed Set fixed attribute in FFS file header to i= ndicate that the file may not be moved from its present location. + @param[in] SectionAlign FileAlign specifies FFS file alignment, whi= ch only support the following alignment: 8,16,128,512,1K,4K,32K,64K. + + @retval EFI_SUCCESS + +**/ +EFI_STATUS +LibEncapSectionFileToFFS ( + IN UINT8 Type, + IN CHAR8* InputFilePath, + IN CHAR8* OutputFilePath, + IN EFI_GUID FileGuid, + IN BOOLEAN Fixed, + IN CHAR8* SectionAlign + ) +{ + CHAR8* SystemCommandFormatString; + CHAR8* SystemCommand; + CHAR8* GuidStr; + + + SystemCommandFormatString =3D NULL; + SystemCommand =3D NULL; + GuidStr =3D NULL; + + GuidStr =3D LibFmmtGuidToStr(&FileGuid); + + if (GuidStr =3D=3D NULL) { + return EFI_ABORTED; + } + + + // + // -t Type + // -i InputFilePath + // -o OutPutFilePath + // -g FileGuid + // -x Fixed + // -n SectionAlign + // + + if (Fixed) { + SystemCommandFormatString =3D "GenFfs -t %s -i \"%s\" -g %s -x -o \"%s= \" -a %s"; + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (mFfsFileType[Type]) + + strlen (InputFilePath) + + strlen (GuidStr) + + strlen (OutputFilePath) + + 4 + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + free (GuidStr); + return EFI_ABORTED; + } + sprintf ( + SystemCommand, + "GenFfs -t %s -i \"%s\" -g %s -x -o \"%s\" -a %s", + mFfsFileType[Type], // -t + InputFilePath, // -i + GuidStr, // -g + OutputFilePath, // -o + SectionAlign + ); + + free (GuidStr); + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + } else { + SystemCommandFormatString =3D "GenFfs -t %s -i \"%s\" -g %s -o \"%s\" = -a %s"; + SystemCommand =3D malloc ( + strlen (SystemCommandFormatString) + + strlen (mFfsFileType[Type]) + + strlen (InputFilePath) + + strlen (GuidStr) + + strlen (OutputFilePath) + + 4 + + 1 + ); + if (SystemCommand =3D=3D NULL) { + free (GuidStr); + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + sprintf ( + SystemCommand, + "GenFfs -t %s -i \"%s\" -g %s -o \"%s\" -a %s", + mFfsFileType[Type], // -t + InputFilePath, // -i + GuidStr, // -g + OutputFilePath, // -o + SectionAlign + ); + + free (GuidStr); + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + } + + + return EFI_SUCCESS; +} + +EFI_STATUS +LibCreateNewFdCopy( + IN CHAR8* OldFd, + IN CHAR8* NewFd +) +{ + + FILE* NewFdFile; + FILE* OldFdFile; + CHAR8 *NewFdDir; + CHAR8 *OldFdDir; + UINT64 FdLength; + UINT32 Count; + BOOLEAN UseNewDirFlag; + CHAR8 *Buffer; + + NewFdFile =3D NULL; + OldFdFile =3D NULL; + NewFdDir =3D NULL; + OldFdDir =3D NULL; + Count =3D 0; + UseNewDirFlag =3D FALSE; + + if (OldFd =3D=3D NULL || + NewFd =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + + NewFdDir =3D getcwd (NULL, _MAX_PATH); + + Count =3D strlen(NewFdDir); + + if (strlen(NewFd) > Count) { + + do { + if (NewFdDir[Count-1] =3D=3D NewFd[Count-1]) { + Count--; + } else { + if (strlen(NewFdDir) + strlen (OS_SEP_STR) + strlen (NewFd) > _MAX= _PATH -1) { + return EFI_ABORTED; + } + strncat (NewFdDir,OS_SEP_STR, _MAX_PATH - strlen (NewFdDir) -1); + strncat (NewFdDir,NewFd, _MAX_PATH - strlen (NewFdDir) -1); + UseNewDirFlag =3D TRUE; + break; + } + + } while (Count !=3D 1); + + }else { + if (strlen(NewFdDir) + strlen (OS_SEP_STR) + strlen (NewFd) > _MAX_PAT= H -1) { + return EFI_ABORTED; + } + strncat (NewFdDir,OS_SEP_STR, _MAX_PATH - strlen (NewFdDir) -1); + strncat (NewFdDir,NewFd, _MAX_PATH - strlen (NewFdDir) -1); + UseNewDirFlag =3D TRUE; + } + + if (UseNewDirFlag) { + NewFdFile =3D fopen (NewFdDir, "wb+"); + if (NewFdFile =3D=3D NULL) { + NewFdFile =3D fopen (NewFd, "wb+"); + } + } else { + NewFdFile =3D fopen (NewFd, "wb+"); + } + // support network path file + if (OldFd[0] =3D=3D '\\' && OldFd[1] =3D=3D '\\') { + OldFdFile =3D fopen (OldFd, "rb"); + } else { + UseNewDirFlag =3D FALSE; + + OldFdDir =3D getcwd (NULL, _MAX_PATH); + + Count =3D strlen(OldFdDir); + + if (strlen(OldFd) > Count) { + + do { + if (OldFdDir[Count-1] =3D=3D OldFd[Count-1]) { + Count--; + } else { + if (strlen(OldFdDir) + strlen (OS_SEP_STR) + strlen (OldFd) > _MAX= _PATH -1) { + if (NewFdFile !=3D NULL) { + fclose(NewFdFile); + } + return EFI_ABORTED; + } + strncat (OldFdDir,OS_SEP_STR, _MAX_PATH - strlen (OldFdDir) -1); + strncat (OldFdDir,OldFd, _MAX_PATH - strlen (OldFdDir) -1); + UseNewDirFlag =3D TRUE; + break; + } + + } while (Count !=3D 1); + + }else { + if (strlen(OldFdDir) + strlen (OS_SEP_STR) + strlen (OldFd) > _MAX_PAT= H -1) { + if (NewFdFile !=3D NULL) { + fclose(NewFdFile); + } + return EFI_ABORTED; + } + strncat (OldFdDir,OS_SEP_STR, _MAX_PATH - strlen (OldFdDir) -1); + strncat (OldFdDir,OldFd, _MAX_PATH - strlen (OldFdDir) -1); + UseNewDirFlag =3D TRUE; + } + + if (UseNewDirFlag) { + OldFdFile =3D fopen (OldFdDir, "rb+"); + if (OldFdFile =3D=3D NULL) { + OldFdFile =3D fopen (OldFd, "rb+"); + } + } else { + OldFdFile =3D fopen (OldFd, "rb+"); + } + } + + if (NewFdFile =3D=3D NULL) { + Error ("FMMT", 0, 0003, "error Open FD file", "cannot Create a new FD = file."); + if (OldFdFile !=3D NULL) { + fclose (OldFdFile); + } + return EFI_ABORTED; + } + + if (OldFdFile =3D=3D NULL) { + Error ("FMMT", 0, 0003, "error Open FD file", "cannot Create a new FD = file."); + if (NewFdFile !=3D NULL) { + fclose (NewFdFile); + } + return EFI_ABORTED; + } + + + fseek(OldFdFile,0,SEEK_SET); + fseek(OldFdFile,0,SEEK_END); + + FdLength =3D ftell(OldFdFile); + + fseek(OldFdFile,0,SEEK_SET); + fseek(NewFdFile,0,SEEK_SET); + + Buffer =3D malloc ((size_t)FdLength); + + if (Buffer =3D=3D NULL) { + fclose(OldFdFile); + fclose(NewFdFile); + return EFI_ABORTED; + } + + if (fread (Buffer, 1, (size_t) FdLength, OldFdFile) !=3D (size_t) FdLeng= th) { + Error ("FMMT", 0, 0003, "error reading FD file %s", OldFd); + free (Buffer); + fclose(OldFdFile); + fclose(NewFdFile); + return EFI_ABORTED; + } + + if (fwrite (Buffer, 1, (size_t) FdLength, NewFdFile) !=3D (size_t) FdLen= gth) { + Error ("FMMT", 0, 0004, "error writing FD file", "cannot Create a new = FD file."); + free (Buffer); + fclose(OldFdFile); + fclose(NewFdFile); + return EFI_ABORTED; + } + free (Buffer); + fclose(OldFdFile); + fclose (NewFdFile); + + return EFI_SUCCESS; +} + + +/** + This function will assemble the filename, directory and extend and retur= n the combined string. + Like FileName =3D file1, Dir =3D c:\temp extend =3D txt, the output stri= ng will be: + c:\temp\file1.txt. + + @param[in] + @param[in] + @param[in] + + @retrun A string contain all the input information. + +**/ +CHAR8 * +LibFilenameStrExtended ( + IN CHAR8 *FileName, + IN CHAR8 *Dir, + IN CHAR8 *Extend +) +{ + CHAR8 *RetStr; + + RetStr =3D NULL; + + if (FileName =3D=3D NULL) { + return NULL; + } + + if (Dir =3D=3D NULL || Extend =3D=3D NULL) { + return FileName; + } + + RetStr =3D (CHAR8 *) malloc (strlen (FileName) + + strlen (Dir) + + strlen (Extend) + + strlen ("%s%s.%s") + + 1); + if (RetStr =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return NULL; + } + + memset (RetStr, '\0', (strlen (FileName) + strlen (Dir) + strlen (Extend= ) + strlen ("%s%s.%s") + 1)); + + sprintf (RetStr, "%s%s.%s", Dir, FileName, Extend); + + return RetStr; +} + +/** + Delete a directory and files in it. + + @param[in] DirName Name of the directory need to be deleted. + + @return EFI_INVALID_PARAMETER + @return EFI_SUCCESS +**/ +EFI_STATUS +LibRmDir ( + IN CHAR8* DirName +) +{ + CHAR8* SystemCommand; + + SystemCommand =3D NULL; + + + if (DirName =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + if (access (DirName, 0) =3D=3D -1){ + return EFI_SUCCESS; + } + + // + // Delete a directory and files in it. + // + + SystemCommand =3D malloc ( + strlen (RMDIR_STR) + + strlen (DirName) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + sprintf ( + SystemCommand, + RMDIR_STR, + DirName + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + + return EFI_SUCCESS; +} + +EFI_STATUS +LibGenExtFile( +CONST EFI_FIRMWARE_VOLUME_EXT_HEADER *ExtPtr, +FILE *InfFile +) +{ + CHAR8 *TempDir; + FILE *ExtFile; + CHAR8 OutputExtFile[_MAX_PATH]; + CHAR8 Line[512]; + size_t Len; + + TempDir =3D NULL; + + TempDir =3D getcwd(NULL, _MAX_PATH); + if (strlen (TempDir) + strlen(OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _MA= X_PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return EFI_ABORTED; + } + strncat (TempDir, OS_SEP_STR, _MAX_PATH - strlen (TempDir) -1); + strncat (TempDir, TEMP_DIR_NAME, _MAX_PATH - strlen (TempDir) -1); + + mkdir(TempDir, S_IRWXU | S_IRWXG | S_IRWXO); + + sprintf( + Line, + "%c%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X%d.ext", + OS_SEP, + (unsigned)ExtPtr->FvName.Data1, + ExtPtr->FvName.Data2, + ExtPtr->FvName.Data3, + ExtPtr->FvName.Data4[0], + ExtPtr->FvName.Data4[1], + ExtPtr->FvName.Data4[2], + ExtPtr->FvName.Data4[3], + ExtPtr->FvName.Data4[4], + ExtPtr->FvName.Data4[5], + ExtPtr->FvName.Data4[6], + ExtPtr->FvName.Data4[7], + ExtPtr->ExtHeaderSize + ); + if (strlen (TempDir) + strlen (Line) > _MAX_PATH - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return EFI_ABORTED; + } + strncpy (OutputExtFile, TempDir, _MAX_PATH - 1); + OutputExtFile[_MAX_PATH - 1] =3D 0; + strncat (OutputExtFile, Line, _MAX_PATH - strlen (OutputExtFile) - 1); + + + ExtFile =3D fopen(OutputExtFile, "wb+"); + if (ExtFile =3D=3D NULL) { + return EFI_ABORTED; + } + + if (fwrite(ExtPtr, 1, ExtPtr->ExtHeaderSize, ExtFile) !=3D ExtPtr->ExtHe= aderSize) { + fclose(ExtFile); + return EFI_ABORTED; + } + + fclose(ExtFile); + + strcpy (Line, "EFI_FV_EXT_HEADER_FILE_NAME =3D "); + if (strlen (Line) + strlen (OutputExtFile) + 1 > sizeof(Line) / sizeof (= CHAR8) - 1) { + Error("FMMT", 0, 1001, "The directory is too long.", ""); + return EFI_ABORTED; + } + strncat (Line, OutputExtFile, sizeof(Line) / sizeof (CHAR8) - strlen (Li= ne) - 1); + strncat (Line, "\n", sizeof(Line) / sizeof (CHAR8) - strlen (Line) - 1); + Len =3D strlen(Line); + if (fwrite(Line, 1, Len, InfFile) !=3D Len) { + return EFI_ABORTED; + } + + return EFI_SUCCESS; +} + +/** + Delete a file. + + @param[in] FileName Name of the file need to be deleted. + + @return EFI_INVALID_PARAMETER + @return EFI_SUCCESS +**/ +EFI_STATUS +LibFmmtDeleteFile( + IN CHAR8 *FileName +) +{ + CHAR8* SystemCommand; + CHAR8 *TemDir; + + SystemCommand =3D NULL; + TemDir =3D NULL; + + + if (FileName =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + // if the FileName is not in TemDir, we don't need to delete. + TemDir =3D getcwd (NULL, _MAX_PATH); + if (*(TemDir + strlen(TemDir) - 1) =3D=3D OS_SEP) { + *(TemDir + strlen(TemDir) - 1) =3D '\0'; + } + if (strlen (TemDir) + strlen (OS_SEP_STR) + strlen (TEMP_DIR_NAME) > _MA= X_PATH - 1) { + Error (NULL, 0, 2000, "Path: The current path is too long.", NULL); + return EFI_ABORTED; + } + strncat (TemDir, OS_SEP_STR, _MAX_PATH - strlen (TemDir) - 1); + strncat (TemDir, TEMP_DIR_NAME, _MAX_PATH - strlen (TemDir) - 1); + if (strstr(FileName, TemDir) =3D=3D NULL) { + return EFI_SUCCESS; + } + + // + // Delete a file + // + + SystemCommand =3D malloc ( + strlen (DEL_STR) + + strlen (FileName) + + 1 + ); + if (SystemCommand =3D=3D NULL) { + Error (NULL, 0, 4001, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + + sprintf ( + SystemCommand, + DEL_STR, + FileName + ); + + if (system (SystemCommand) !=3D EFI_SUCCESS) { + free(SystemCommand); + return EFI_ABORTED; + } + free(SystemCommand); + + return EFI_SUCCESS; + +} + + +/** + + Free the whole Fd data structure. + + @param[in] Fd The pointer point to the Fd data structure. + +**/ +VOID +LibFmmtFreeFd ( + FIRMWARE_DEVICE *Fd + ) +{ + FV_INFORMATION *CurrentFv; + FV_INFORMATION *TempFv; + ENCAP_INFO_DATA *EncapData1; + ENCAP_INFO_DATA *EncapData2; + + CurrentFv =3D NULL; + TempFv =3D NULL; + EncapData1 =3D NULL; + EncapData2 =3D NULL; + + if (Fd =3D=3D NULL) { + return; + } + + CurrentFv =3D Fd->Fv; + + do { + TempFv =3D CurrentFv; + CurrentFv =3D CurrentFv->FvNext; + + free (TempFv->FvHeader); + + if (TempFv->FvExtHeader !=3D NULL) { + free (TempFv->FvExtHeader); + } + if (TempFv->FvUiName) { + free(TempFv->FvUiName); + } + + // + // Free encapsulate data; + // + EncapData1 =3D TempFv->EncapData; + + while (EncapData1 !=3D NULL) { + + EncapData2 =3D EncapData1; + EncapData1 =3D EncapData1->NextNode; + + if (EncapData2->Data !=3D NULL) { + free (EncapData2->Data); + } + if (EncapData2->FvExtHeader !=3D NULL) { + free(EncapData2->FvExtHeader); + } + free (EncapData2); + EncapData2 =3D NULL; + } + + EncapData1 =3D NULL; + + free (TempFv); + TempFv =3D NULL; + + } while (CurrentFv !=3D NULL); + + CurrentFv =3D NULL; + free (Fd); + Fd =3D NULL; + + return; +} + +/** + Generate the compressed section with specific type. + Type could be EFI_STANDARD_COMPRESSION or EFI_NOT_COMPRESSED + + @param[in] InputFileName File name of the raw data. + @param[in] OutPutFileName File name of the sectioned data. + @param[in] CompressionType The compression type. + + @return EFI_INVALID_PARAMETER + @return EFI_ABORTED + @return EFI_OUT_OF_RESOURCES + @return EFI_SUCCESS + +**/ +EFI_STATUS +LibGenCompressedSection ( + CHAR8 *InputFileName, + CHAR8 *OutPutFileName, + UINT8 CompressionType +) +{ + //FILE *UnCompressFile; + //FILE *CompressedFile; + //VOID *UnCompressedBuffer; + //VOID *CompressedBuffer; + //UINT32 UnCompressedSize; + //UINT32 CompressedSize; + //CHAR8 *TempName; + //CHAR8 *TemDir; + //EFI_STATUS Status; + + //UnCompressFile =3D NULL; + //CompressedFile =3D NULL; + //UnCompressedBuffer =3D NULL; + //CompressedBuffer =3D NULL; + //TempName =3D NULL; + //TemDir =3D NULL; + //UnCompressedSize =3D 0; + //CompressedSize =3D 0; + + if ( InputFileName =3D=3D NULL || + OutPutFileName =3D=3D NULL) { + printf ("Error while generate compressed section!\n"); + return EFI_INVALID_PARAMETER; + } + + if (CompressionType =3D=3D EFI_STANDARD_COMPRESSION) { + /* + + UnCompressFile =3D fopen (InputFileName, "rb"); + if (UnCompressFile =3D=3D NULL) { + printf ("Error while open file %s \n", InputFileName); + return EFI_ABORTED; + } + + TemDir =3D _getcwd (NULL, _MAX_PATH); + sprintf(TemDir, "%s\\%s", TemDir, TEMP_DIR_NAME); + + TempName=3D LibFilenameStrExtended (strrchr(CloneString (tmpnam (NULL)= ),'\\'), TemDir, "comp"); + + CompressedFile =3D fopen (TempName, "wb+"); + if (CompressedFile =3D=3D NULL) { + printf ("Error while open file %s \n", TempName); + return EFI_ABORTED; + } + + // + // Get the original file size; + // + fseek(UnCompressFile,0,SEEK_SET); + fseek(UnCompressFile,0,SEEK_END); + + UnCompressedSize =3D ftell(UnCompressFile); + + fseek(UnCompressFile,0,SEEK_SET); + + UnCompressedBuffer =3D malloc (UnCompressedSize); + + if (UnCompressedBuffer =3D=3D NULL) { + printf("Error while allocate memory! \n"); + return EFI_OUT_OF_RESOURCES; + } + + CompressedBuffer =3D malloc (UnCompressedSize); + + if (CompressedBuffer =3D=3D NULL) { + printf("Error while allocate memory! \n"); + return EFI_OUT_OF_RESOURCES; + } + + if (fread (UnCompressedBuffer, 1, (size_t) UnCompressedSize, UnCompres= sFile) =3D=3D (size_t) UnCompressedSize) { + CompressedSize =3D UnCompressedSize; + + Status =3D EfiCompress ( UnCompressedBuffer, + UnCompressedSize, + CompressedBuffer, + &CompressedSize); + + if (EFI_ERROR(Status)) { + printf("Error while do compress operation! \n"); + return EFI_ABORTED; + } + + if (CompressedSize > UnCompressedSize) { + printf("Error while do compress operation! \n"); + return EFI_ABORTED; + } + } else { + printf("Error while reading file %s! \n", InputFileName); + return EFI_ABORTED; + } + + // + // Write the compressed data into output file + // + if (fwrite (CompressedBuffer, 1, (size_t) CompressedSize, CompressedFi= le) !=3D (size_t) CompressedSize) { + Error ("FMMT", 0, 0004, "error writing %s file", OutPutFileName); + fclose(UnCompressFile); + fclose (CompressedFile); + return EFI_ABORTED; + } + + fclose(UnCompressFile); + fclose (CompressedFile); + */ + + // + // Call GenSec tool to generate the compressed section. + // + LibCreateFfsSection(NULL, InputFileName, NULL, EFI_SECTION_COMPRESSION= , OutPutFileName, NULL, NULL, NULL, 0, 0, "PI_STD"); + + } else if (CompressionType =3D=3D EFI_NOT_COMPRESSED) { + + LibCreateFfsSection(NULL, InputFileName, NULL, EFI_SECTION_COMPRESSI= ON, OutPutFileName, NULL, NULL, NULL, 0, 0, "PI_NONE"); + + } else { + printf ("Error while generate compressed section, unknown compression = type! \n"); + return EFI_INVALID_PARAMETER; + } + + + return EFI_SUCCESS; +} + +EFI_STATUS +LibEncapNewFvFile( + IN FV_INFORMATION *FvInFd, + IN CHAR8 *TemDir, + IN ENCAP_INFO_DATA *CurrentEncapData, + IN UINT32 Level_Break, + OUT FFS_INFORMATION **OutputFile +) +{ + EFI_STATUS Status; + UINT32 ParentType; + UINT8 ParentLevel; + UINT32 Type; + UINT8 Level; + CHAR8 *InfFileName; + FILE *InfFile; + ENCAP_INFO_DATA *LocalEncapData; + ENCAP_INFO_DATA *LocalEncapDataTemp; + ENCAP_INFO_DATA *LocalEncapDataNext; + BOOLEAN FfsFoundFlag; + UINT32 Index; + UINT32 OuterIndex; + CHAR8 *ExtractionTool; + BOOLEAN IsLastLevelFfs; + BOOLEAN IsLeafFlagIgnore; + BOOLEAN FirstInFlag; + BOOLEAN OutputFileNameListFlag; + CHAR8 *InputFileName; + CHAR8 *OutputFileName; + FFS_INFORMATION *OutputFileNameList; + FFS_INFORMATION *ChildFileNameList; + FFS_INFORMATION *NewFileNameList; + CHAR8 *FvGuidName; + UINT16 GuidAttributes; + UINT16 GuidDataOffset; + BOOLEAN IsRootFv; + BOOLEAN IsLargeFile; + UINT32 EncapFvStart; + UINT32 EncapFvIndex; + CHAR8 *TmpFileName; + FILE *TmpFile; + FILE *InputFile; + FILE *OutFile; + UINT32 InputFileSize; + UINT32 OutputFileSize; + UINT32 LargeFileSize; + UINT8 *Buffer =3D NULL; + UINT8 SectionHeader[4] =3D { 0x00, 0x00, 0x00, 0x0= 0 }; + UINT32 Id; + UINT32 SubFvId; + UINT32 header; + UINT8 AlignN; + UINT8 AlignV[1] =3D {0xFF}; + AlignN =3D 0; + Id =3D 0; + InputFileSize =3D 0; + EncapFvIndex =3D 0; + Index =3D 0; + OuterIndex =3D 0; + ParentType =3D 0; + ParentLevel =3D 0; + Type =3D 0; + Level =3D 0; + SubFvId =3D 0; + FfsFoundFlag =3D FALSE; + LocalEncapDataTemp =3D NULL; + LocalEncapDataNext =3D NULL; + ExtractionTool =3D NULL; + InputFileName =3D NULL; + OutputFileName =3D NULL; + IsLastLevelFfs =3D TRUE; + IsLeafFlagIgnore =3D FALSE; + FirstInFlag =3D TRUE; + FvGuidName =3D NULL; + OutputFileNameListFlag =3D TRUE; + IsLargeFile =3D FALSE; + OutputFileSize =3D 0; + LargeFileSize =3D 0x1000000; + + + OutputFileNameList =3D (FFS_INFORMATION *)malloc(sizeof(FV_INFORMATION)); + if (OutputFileNameList =3D=3D NULL) { + Error ("FMMT", 0, 0004, "Out of resource, memory allocation failed! \n= ", ""); + return EFI_OUT_OF_RESOURCES; + } + OutputFileNameList->FFSName =3D NULL; + OutputFileNameList->InFvId =3D 0; + OutputFileNameList->IsFFS =3D FALSE; + OutputFileNameList->ParentLevel =3D 0; + OutputFileNameList->Next =3D NULL; + OutputFileNameList->UiNameSize =3D 0; + OutputFileNameList->Depex =3D NULL; + OutputFileNameList->DepexLen =3D 0; + OutputFileNameList->FfsFoundFlag =3D FALSE; + + ChildFileNameList =3D (FFS_INFORMATION *)malloc(sizeof(FV_INFORMATION)); + if (ChildFileNameList =3D=3D NULL) { + Error ("FMMT", 0, 0004, "Out of resource, memory allocation failed! \n= ", ""); + return EFI_OUT_OF_RESOURCES; + } + ChildFileNameList->FFSName =3D NULL; + ChildFileNameList->InFvId =3D 0; + ChildFileNameList->ParentLevel =3D 0; + ChildFileNameList->Next =3D NULL; + ChildFileNameList->IsFFS =3D FALSE; + ChildFileNameList->UiNameSize =3D 0; + ChildFileNameList->Depex =3D NULL; + ChildFileNameList->DepexLen =3D 0; + ChildFileNameList->FfsFoundFlag =3D FALSE; + // + // Encapsulate from the lowest FFS file level. + // + LocalEncapData =3D CurrentEncapData; + if (LocalEncapData =3D=3D NULL) { + LocalEncapData =3D FvInFd->EncapData; + } + Level =3D LocalEncapData->Level; + Type =3D LocalEncapData->Type; + + if (CurrentEncapData =3D=3D NULL) { + LocalEncapData =3D FvInFd->EncapData; + while (LocalEncapData !=3D NULL) { + if (LocalEncapData->Type =3D=3D FMMT_ENCAP_TREE_FFS) { + LocalEncapDataTemp =3D LocalEncapData->RightNode; + while (LocalEncapDataTemp !=3D NULL) { + LocalEncapDataNext =3D LocalEncapDataTemp->NextNode; + if (LocalEncapDataNext !=3D NULL && LocalEncapDataNext->NextNo= de !=3D NULL) { + + LibEncapNewFvFile(FvInFd, TemDir, LocalEncapDataTemp, 1, &= ChildFileNameList); + ChildFileNameList->ParentLevel =3D LocalEncapDataTemp->Lev= el -1; + if (FvInFd->ChildFvFFS =3D=3D NULL) { + FvInFd->ChildFvFFS =3D ChildFileNameList; + } else { + NewFileNameList =3D FvInFd->ChildFvFFS; + while (NewFileNameList->Next !=3D NULL) { + NewFileNameList =3D NewFileNameList->Next; + } + NewFileNameList->Next =3D ChildFileNameList; + } + } + LocalEncapDataTemp =3D LocalEncapDataTemp->RightNode; + } + } + + if (LocalEncapData->Level > Level) { + if (LocalEncapData->Type =3D=3D FMMT_ENCAP_TREE_FFS) { + ParentLevel =3D Level; + ParentType =3D Type; + } + Level =3D LocalEncapData->Level; + Type =3D LocalEncapData->Type; + } + LocalEncapData =3D LocalEncapData->NextNode; + } + } else { + LocalEncapData =3D CurrentEncapData; + while (LocalEncapData !=3D NULL) { + if (LocalEncapData->Level > Level) { + if (LocalEncapData->Type =3D=3D FMMT_ENCAP_TREE_FFS) { + ParentLevel =3D Level; + ParentType =3D Type; + } + Level =3D LocalEncapData->Level; + Type =3D LocalEncapData->Type; + } + LocalEncapData =3D LocalEncapData->NextNode; + } + } + + do { + switch (ParentType) { + case FMMT_ENCAP_TREE_FV: + OutputFileNameListFlag =3D TRUE; + EncapFvStart =3D 0; + for(OuterIndex=3D0;OutputFileNameListFlag;OuterIndex++){ + // + // Generate FV.inf attributes. + // + InfFileName =3D LibFilenameStrExtended (strrchr(GenTempFile (),OS_= SEP), TemDir, "inf"); + FirstInFlag =3D TRUE; + + InfFile =3D fopen (InfFileName, "wt+"); + + if (InfFile =3D=3D NULL) { + Error ("FMMT", 0, 0004, "Could not open inf file %s to store FV = information! \n", ""); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + + if (CurrentEncapData =3D=3D NULL) { + LocalEncapData =3D FvInFd->EncapData; + } else { + LocalEncapData =3D CurrentEncapData; + } + + while (LocalEncapData->NextNode !=3D NULL) { + if (LocalEncapData->Level =3D=3D ParentLevel) { + break; + } + LocalEncapData =3D LocalEncapData->NextNode; + } + + if (((EFI_FIRMWARE_VOLUME_HEADER *)(LocalEncapData->Data))->ExtHea= derOffset !=3D 0) { + // + // FV GUID Name memory allocation + // + FvGuidName =3D (CHAR8 *) malloc (255); + + if (FvGuidName =3D=3D NULL) { + Error ("FMMT", 0, 0004, "Out of resource, memory allocation fa= iled! \n", ""); + fclose (InfFile); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + + memset(FvGuidName, '\0', 255); + + sprintf( + FvGuidName, + "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X\n", + LocalEncapData->FvExtHeader->FvName.Data1, + LocalEncapData->FvExtHeader->FvName.Data2, + LocalEncapData->FvExtHeader->FvName.Data3, + LocalEncapData->FvExtHeader->FvName.Data4[0], + LocalEncapData->FvExtHeader->FvName.Data4[1], + LocalEncapData->FvExtHeader->FvName.Data4[2], + LocalEncapData->FvExtHeader->FvName.Data4[3], + LocalEncapData->FvExtHeader->FvName.Data4[4], + LocalEncapData->FvExtHeader->FvName.Data4[5], + LocalEncapData->FvExtHeader->FvName.Data4[6], + LocalEncapData->FvExtHeader->FvName.Data4[7] + ); + + } else { + FvGuidName =3D NULL; + } + + + if (ParentLevel =3D=3D 1) { + Status =3D LibFvHeaderOptionToStr((EFI_FIRMWARE_VOLUME_HEADER *)= LocalEncapData->Data, InfFile, TRUE); + } else { + Status =3D LibFvHeaderOptionToStr((EFI_FIRMWARE_VOLUME_HEADER *)= LocalEncapData->Data, InfFile, FALSE); + } + + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "gen= erate FV INF file [Options] section failed."); + fclose (InfFile); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + + Status =3D LibFvHeaderAttributeToStr(((EFI_FIRMWARE_VOLUME_HEADER = *)LocalEncapData->Data)->Attributes, InfFile); + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "Gen= erate FV header attribute failed"); + fclose (InfFile); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + if (LocalEncapData->FvExtHeader !=3D NULL) { + Status =3D LibGenExtFile(LocalEncapData->FvExtHeader, InfFile); + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0004, "error while encapsulate FD Image", "Ge= nerate FV EXT header failed"); + fclose (InfFile); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + FvGuidName =3D NULL; + } + + if (CurrentEncapData !=3D NULL) { + for (Index =3D 0; Index <=3D FvInFd->FfsNumbers; Index++) { + if ((memcmp(&FvInFd->FfsAttuibutes[Index].GuidName, &(Curr= entEncapData->FvExtHeader->FvName), sizeof(EFI_GUID)) =3D=3D 0)) { + SubFvId =3D Index; + break; + } + } + } + // + // Found FFSs from Fv structure. + // + FfsFoundFlag =3D FALSE; + IsRootFv =3D FALSE; + for (Index=3D0; Index <=3D FvInFd->FfsNumbers; Index++) { + if (OutputFileNameList !=3D NULL && OutputFileNameList->FFSNam= e !=3D NULL && OutputFileNameList->IsFFS =3D=3D FALSE){ + break; + } + if (OutputFileNameList !=3D NULL && OutputFileNameList->FFSNam= e !=3D NULL && OutputFileNameList->IsFFS =3D=3D TRUE){ + if (Index =3D=3D EncapFvIndex) { + if (FirstInFlag) { + Status =3D LibAddFfsFileToFvInf (OutputFileNam= eList->FFSName, InfFile, TRUE); + FirstInFlag =3D FALSE; + } else { + Status =3D LibAddFfsFileToFvInf (OutputFileNam= eList->FFSName, InfFile, FALSE); + } + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsula= te FD Image", "Generate FV inf file [files] section failed!"); + fclose (InfFile); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + } + } + + NewFileNameList =3D FvInFd->ChildFvFFS; + while (NewFileNameList !=3D NULL && NewFileNameList -> FFSName= !=3D NULL) { + if (NewFileNameList -> ParentLevel =3D=3D ParentLevel && I= ndex =3D=3D NewFileNameList->InFvId && NewFileNameList->FfsFoundFlag=3D=3DT= RUE) { + if (FirstInFlag) { + Status =3D LibAddFfsFileToFvInf (NewFileNameList->= FFSName, InfFile, TRUE); + FirstInFlag =3D FALSE; + } else { + Status =3D LibAddFfsFileToFvInf (NewFileNameList->= FFSName, InfFile, FALSE); + } + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate F= D Image", "Generate FV inf file [files] section failed!"); + fclose (InfFile); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + } + NewFileNameList =3D NewFileNameList->Next; + } + + if (FvInFd->FfsAttuibutes[Index].IsHandle=3D=3DTRUE) { + continue; + } + if (SubFvId > 0 && Index < SubFvId) { + continue; + } + + // + // For the last level FFS, the level below FFSs we should not ca= re the IsLeaf Flag. + // + if (IsLastLevelFfs) { + IsLeafFlagIgnore =3D TRUE; + } else { + IsLeafFlagIgnore =3D FvInFd->FfsAttuibutes[Index].IsLeaf; + } + + if (FvInFd->FfsAttuibutes[Index].Level >=3D ParentLevel + 1 && I= sLeafFlagIgnore) { + if (FirstInFlag) { + if (FvInFd->FfsAttuibutes[Index].Level < 0xFF) { + FfsFoundFlag =3D TRUE; + Status =3D LibAddFfsFileToFvInf (FvInFd->FfsAttuibutes[Index].Ff= sName, InfFile, TRUE); + FirstInFlag =3D FALSE; + FvInFd->FfsAttuibutes[Index].IsHandle=3DTRUE; + EncapFvStart =3D Index; + } + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Imag= e", "Generate FV inf file [files] section failed!"); + fclose (InfFile); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + if (Index =3D=3D 0) { + // Root FV need to include all FFS files. + IsRootFv =3D TRUE; + } + } else { + if (FvInFd->FfsAttuibutes[Index].Level < 0xFF) { + FfsFoundFlag =3D TRUE; + Status =3D LibAddFfsFileToFvInf (FvInFd->FfsAttuibutes[Index].Ff= sName, InfFile, FALSE); + FvInFd->FfsAttuibutes[Index].IsHandle=3DTRUE; + } + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Imag= e", "Generate FV inf file [files] section failed!"); + fclose (InfFile); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + if (Index =3D=3D 0) { + // Root FV need to include all FFS files. + IsRootFv =3D TRUE; + } + } + + + //avoid a FV contain too many ffs files + if ((!IsRootFv) && (FvInFd->FfsAttuibutes[Index].FvLevel <=3D F= vInFd->MulFvLevel) && (FvInFd->FfsAttuibutes[Index+1].FvLevel <=3D FvInFd->= MulFvLevel) && + (FvInFd->FfsAttuibutes[Index].FvLevel !=3D FvInFd->FfsAttui= butes[Index+1].FvLevel) && (ParentLevel !=3D 1) && (FvInFd->FfsAttuibutes[I= ndex].Level !=3D FvInFd->FfsAttuibutes[Index+1].Level) && + FvInFd->FfsAttuibutes[Index].Level !=3D 0xFF && FvInFd->Ffs= Attuibutes[Index+1].Level !=3D 0xFF && FvInFd->FfsAttuibutes[Index+1].Level= !=3D 0x0){ + FvInFd->FfsAttuibutes[Index].Level =3D 0; + break; + }else{ + if (FvInFd->FfsAttuibutes[Index].Level !=3D 0xFF){ + FvInFd->FfsAttuibutes[Index].Level =3D 0; + } + } + + } + } + // The Fv may has multiple level (> 2), when it is in the FvLevel = =3D=3D 2, we set the IsLastLevelFfs Flag + if (Index <=3DFvInFd->FfsNumbers && FvInFd->FfsAttuibutes[Index].Fv= Level <=3D FvInFd->MulFvLevel) { + if (FvInFd->FfsAttuibutes[Index].FvLevel =3D=3D 2) { + IsLastLevelFfs =3D FALSE; + } + } + if (!FfsFoundFlag){ + OutputFileNameListFlag =3D FALSE; + if (OuterIndex > 0){ + fclose (InfFile); + break; + } + } + // + // Create FV + // + fclose (InfFile); + + EncapFvIndex =3D EncapFvStart; + + OutputFileName=3D LibFilenameStrExtended (strrchr(GenTempFile (), = OS_SEP), TemDir, "FV"); + + Status =3D LibEncapsulateFfsToFv (InfFileName, NULL, OutputFileNam= e, FvGuidName, IsLargeFile); + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "Gen= erate FV failed!"); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + + OutputFileNameList->FFSName =3D (char *)malloc(strlen(OutputFileName)+= 1); + if (OutputFileNameList->FFSName =3D=3D NULL) { + Error ("FMMT", 0, 0004, "Out of resource, memory allocation failed! = \n", ""); + return EFI_OUT_OF_RESOURCES; + } + memcpy((char *)OutputFileNameList->FFSName, (char *)OutputFileName, st= rlen(OutputFileName)+1); + if (CurrentEncapData !=3D NULL) { + OutputFileNameList->InFvId =3D EncapFvIndex; + if (EncapFvIndex > 0) { + memcpy(OutputFileNameList->UiName,FvInFd->FfsAttuibutes[EncapF= vIndex - 1].UiName, FvInFd->FfsAttuibutes[EncapFvIndex - 1].UiNameSize); + OutputFileNameList->UiNameSize =3D FvInFd->FfsAttuibutes[Encap= FvIndex - 1].UiNameSize; + OutputFileNameList->Depex =3D FvInFd->FfsAttuibutes[EncapFvInd= ex - 1].Depex; + OutputFileNameList->DepexLen =3D FvInFd->FfsAttuibutes[EncapFv= Index - 1].DepexLen; + OutputFileNameList->FfsFoundFlag =3D FfsFoundFlag; + } + } + } + break; + case FMMT_ENCAP_TREE_FFS: + + while(OutputFileNameList!=3D NULL && OutputFileNameList->FFSName != =3D NULL){ + InputFileName =3D OutputFileNameList->FFSName; + OutputFileName=3D LibFilenameStrExtended (strrchr(GenTempFile ()= , OS_SEP), TemDir, "ffs"); + LocalEncapData =3D CurrentEncapData; + if (LocalEncapData =3D=3D NULL) { + LocalEncapData =3D FvInFd->EncapData; + } + while (LocalEncapData->NextNode !=3D NULL) { + if (LocalEncapData->Level =3D=3D ParentLevel) { + for(;LocalEncapData->NextNode !=3D NULL;) { + if(LocalEncapData->FvExtHeader !=3D NULL) { + break; + } + LocalEncapData =3D LocalEncapData->NextNode; + } + break; + } + LocalEncapData =3D LocalEncapData->NextNode; + } + + if (LocalEncapData->FvExtHeader =3D=3D NULL) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "G= enerate FFS file failed!"); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + + if (OutputFileNameList->UiNameSize > 0) { + TmpFileName =3D LibFilenameStrExtended(strrchr(GenTempFile (= ), OS_SEP), TemDir, "tmp"); + TmpFile =3D fopen(TmpFileName, "wb+"); + if (TmpFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "Could not open tmp file %s to sto= re UI section information! \n", ""); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + header =3D (OutputFileNameList->UiNameSize+4) | (EFI_SECTION_= USER_INTERFACE << 24); + Index =3D 0; + while (header) { + SectionHeader[Index] =3D header % 0x100; + header /=3D 0x100; + Index ++; + } + InputFile =3D fopen(InputFileName, "rb+"); + if (InputFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "Could not open input file %s! \n", = ""); + fclose(TmpFile); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + fseek(InputFile, 0, SEEK_SET); + fseek(InputFile, 0, SEEK_END); + InputFileSize =3D ftell(InputFile); + fseek(InputFile, 0, SEEK_SET); + + Buffer =3D malloc(InputFileSize+OutputFileNameList->UiNameSiz= e+4); + memcpy(Buffer, (CHAR16 *)SectionHeader, 4); + memcpy(Buffer + 4, (CHAR16 *)(OutputFileNameList->UiName), Ou= tputFileNameList->UiNameSize); + if (fread(Buffer+4+OutputFileNameList->UiNameSize, 1, InputFi= leSize, InputFile) !=3D InputFileSize) { + Error("FMMT", 0, 0004, "Could not open sec file %s to add U= I section information! \n", ""); + fclose(TmpFile); + fclose(InputFile); + free(Buffer); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + fwrite(Buffer, 1, InputFileSize + OutputFileNameList->UiNameS= ize + 4, TmpFile); + free(Buffer); + fclose(TmpFile); + fclose(InputFile); + InputFileName =3D TmpFileName; + } + if (OutputFileNameList->DepexLen > 0) { + TmpFileName =3D LibFilenameStrExtended(strrchr(GenTempFile (= ), OS_SEP), TemDir, "tmp"); + TmpFile =3D fopen(TmpFileName, "wb+"); + if (TmpFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "Could not open tmp file %s to st= ore Depex section information! \n", ""); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + InputFile =3D fopen(InputFileName, "rb+"); + if (InputFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "Could not open input file %s! \n",= ""); + fclose(TmpFile); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + fseek(InputFile, 0, SEEK_SET); + fseek(InputFile, 0, SEEK_END); + InputFileSize =3D ftell(InputFile); + fseek(InputFile, 0, SEEK_SET); + // make sure the section is 4 byte align + if (OutputFileNameList->DepexLen % 4 !=3D 0) { + AlignN =3D 4 - OutputFileNameList->DepexLen % 4; + } + Buffer =3D malloc(InputFileSize + OutputFileNameList->DepexL= en + AlignN); + memcpy(Buffer, OutputFileNameList->Depex, OutputFileNameList= ->DepexLen); + if (AlignN !=3D 0) { + for (Index =3D 0; Index < AlignN; Index ++) { + memcpy(Buffer + OutputFileNameList->DepexLen + Index= , AlignV, 1); + } + } + if (fread(Buffer + OutputFileNameList->DepexLen + AlignN, 1,= InputFileSize, InputFile) !=3D InputFileSize) { + Error("FMMT", 0, 0004, "Could not open sec file %s to ad= d Depex section information! \n", ""); + fclose(TmpFile); + fclose(InputFile); + free(Buffer); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + fwrite(Buffer, 1, InputFileSize + OutputFileNameList->DepexL= en + AlignN, TmpFile); + free(Buffer); + fclose(TmpFile); + fclose(InputFile); + InputFileName =3D TmpFileName; + } + for (Id =3D FvInFd->FfsNumbers; Id <=3D FvInFd->FfsNumbers; Id--)= { + if ((memcmp(&FvInFd->FfsAttuibutes[Id].GuidName, &(LocalEncap= Data->FvExtHeader->FvName), sizeof(EFI_GUID)) =3D=3D 0)){ + if (access(FvInFd->FfsAttuibutes[Id].FfsName, 0) !=3D -1)= { + Status =3D LibFmmtDeleteFile(FvInFd->FfsAttuibutes[Id= ].FfsName); + if (EFI_ERROR(Status)) { + Error("FMMT", 0, 0004, "error while encapsulate F= D Image", "Delete the specified file failed!"); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + memset(FvInFd->FfsAttuibutes[Id].FfsName, '\0', _MAX_= PATH); + FvInFd->FfsAttuibutes[Id].Level =3D 0xFF; + break; + } + } + } + if (LocalEncapData->NextNode !=3D NULL) { + LocalEncapDataTemp =3D LocalEncapData->NextNode; + if ((LocalEncapDataTemp->Type =3D=3D FMMT_ENCAP_TREE_GUIDED_S= ECTION) || (LocalEncapDataTemp->Type =3D=3D FMMT_ENCAP_TREE_COMPRESS_SECTIO= N)) { + Status =3D LibEncapSectionFileToFFS(EFI_FV_FILETYPE_FIRMW= ARE_VOLUME_IMAGE, InputFileName, OutputFileName, LocalEncapData->FvExtHeade= r->FvName, FALSE, "1"); + } + else{ + Status =3D LibEncapSectionFileToFFS(EFI_FV_FILETYPE_FIRMW= ARE_VOLUME_IMAGE, InputFileName, OutputFileName, LocalEncapData->FvExtHeade= r->FvName, FALSE, FvInFd->AlignmentStr); + } + } + else{ + Status =3D LibEncapSectionFileToFFS(EFI_FV_FILETYPE_FIRMWARE_= VOLUME_IMAGE, InputFileName, OutputFileName, LocalEncapData->FvExtHeader->F= vName, FALSE, FvInFd->AlignmentStr); + } + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "Gener= ate FFS file failed!"); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + free(LocalEncapData->FvExtHeader); + LocalEncapData->FvExtHeader =3D NULL; + OutputFileNameList->FFSName =3D (char *)malloc(strlen(OutputFileName= )+1); + if (OutputFileNameList->FFSName =3D=3D NULL) { + Error ("FMMT", 0, 0004, "Out of resource, memory allocation fail= ed! \n", ""); + return EFI_OUT_OF_RESOURCES; + } + memcpy((char *)OutputFileNameList->FFSName, (char *)OutputFileName, = strlen(OutputFileName)+1); + OutputFileNameList->IsFFS =3D TRUE; + if (OutputFileNameList->Next =3D=3D NULL){ + break; + } + OutputFileNameList =3D OutputFileNameList->Next; + } + break; + case FMMT_ENCAP_TREE_GUIDED_SECTION: + while(OutputFileNameList!=3D NULL && OutputFileNameList->FFSName != =3D NULL){ + // + // Create the guided section original data, do compress operation. + // + InputFileName =3D OutputFileNameList->FFSName; + OutputFileName=3D LibFilenameStrExtended (strrchr(GenTempFile (), = OS_SEP), TemDir, "compressed"); + + // + // Use the guided section header guid to find out compress applica= tion name. + // + LocalEncapData =3D CurrentEncapData; + if (LocalEncapData =3D=3D NULL) { + LocalEncapData =3D FvInFd->EncapData; + } + while (LocalEncapData->NextNode !=3D NULL) { + if (LocalEncapData->Level =3D=3D ParentLevel) { + break; + } + LocalEncapData =3D LocalEncapData->NextNode; + } + + ExtractionTool =3D + LookupGuidedSectionToolPath ( + mParsedGuidedSectionTools, + (EFI_GUID *)LocalEncapData->Data + ); + GuidDataOffset =3D *(UINT16 *) ((UINT8 *) LocalEncapData->Data + s= izeof (EFI_GUID)); + GuidAttributes =3D *(UINT16 *) ((UINT8 *) LocalEncapData->Data + s= izeof (EFI_GUID) + sizeof (UINT16)); + + Status =3D LibCreateGuidedSectionOriginalData (InputFileName, Extr= actionTool, OutputFileName); + + if (EFI_ERROR (Status) || GuidDataOffset < sizeof (EFI_GUID_DEFINE= D_SECTION)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "Com= press guided data failed!"); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + + GuidDataOffset =3D GuidDataOffset - sizeof (EFI_GUID_DEFINED_SECTI= ON); + InputFileName =3D OutputFileName; + OutputFileName=3D LibFilenameStrExtended (strrchr(GenTempFile (), = OS_SEP), TemDir, "guided"); + + Status =3D LibCreateFfsSection(NULL, InputFileName, NULL, EFI_SECT= ION_GUID_DEFINED, OutputFileName, NULL, NULL, LibFmmtGuidToStr((EFI_GUID *)= LocalEncapData->Data), GuidDataOffset, GuidAttributes, NULL); + OutFile =3D fopen(OutputFileName, "rb+"); + if (OutFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "Could not open the file %s! \n", ""); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + fseek(OutFile, 0, SEEK_SET); + fseek(OutFile, 0, SEEK_END); + OutputFileSize =3D ftell(OutFile); + fclose(OutFile); + if (OutputFileSize > LargeFileSize) { + IsLargeFile =3D TRUE; + } + OutputFileNameList->FFSName =3D (char *)malloc(strlen(OutputFileName)+= 1); + if (OutputFileNameList->FFSName =3D=3D NULL) { + Error ("FMMT", 0, 0004, "Out of resource, memory allocation failed! = \n", ""); + return EFI_OUT_OF_RESOURCES; + } + memcpy((char *)OutputFileNameList->FFSName, (char *)OutputFileName, st= rlen(OutputFileName)+1); + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "Gen= erate guided section failed!"); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + if (OutputFileNameList->Next =3D=3D NULL){ + break; + } + OutputFileNameList =3D OutputFileNameList->Next; + } + break; + case FMMT_ENCAP_TREE_COMPRESS_SECTION: + while(OutputFileNameList!=3D NULL && OutputFileNameList->FFSName != =3D NULL){ + InputFileName =3D OutputFileNameList->FFSName; + + OutputFileName=3D LibFilenameStrExtended (strrchr(GenTempFile ()= , OS_SEP), TemDir, "comsec"); + LocalEncapData =3D CurrentEncapData; + if (LocalEncapData =3D=3D NULL) { + LocalEncapData =3D FvInFd->EncapData; + } + while (LocalEncapData->NextNode !=3D NULL) { + if (LocalEncapData->Level =3D=3D ParentLevel) { + break; + } + LocalEncapData =3D LocalEncapData->NextNode; + } + + Status =3D LibGenCompressedSection (InputFileName, OutputFileNam= e, *(UINT8 *)(LocalEncapData->Data)); + OutputFileNameList->FFSName =3D (char *)malloc(strlen(OutputFileName= )+1); + if (OutputFileNameList->FFSName =3D=3D NULL) { + Error ("FMMT", 0, 0004, "Out of resource, memory allocation failed= ! \n", ""); + return EFI_OUT_OF_RESOURCES; + } + memcpy((char *)OutputFileNameList->FFSName, (char *)OutputFileName, = strlen(OutputFileName)+1); + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "G= enerate compressed section failed!"); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + if (OutputFileNameList->Next =3D=3D NULL){ + break; + } + OutputFileNameList =3D OutputFileNameList->Next; + } + break; + case FMMT_ENCAP_TREE_FV_SECTION: + while(OutputFileNameList!=3D NULL && OutputFileNameList->FFSName != =3D NULL){ + InputFileName =3D OutputFileNameList->FFSName; + OutputFileName=3D LibFilenameStrExtended (strrchr(GenTempFile (), = OS_SEP), TemDir, "sec"); + + Status =3D LibCreateFfsSection(NULL, InputFileName, NULL, EFI_SECT= ION_FIRMWARE_VOLUME_IMAGE, OutputFileName, NULL, NULL, NULL, 0, 0, NULL); + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "Gen= erate FV section failed!"); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + + InputFileName =3D OutputFileName; + OutputFileName=3D LibFilenameStrExtended (strrchr(GenTempFile (), = OS_SEP), TemDir, "sec"); + + // + // Make it alignment. + // + Status =3D LibCreateFfsSection(FvInFd, InputFileName, NULL, 0, Out= putFileName, NULL, NULL, NULL, 0, 0, NULL); + OutFile =3D fopen(OutputFileName, "rb+"); + if (OutFile =3D=3D NULL) { + Error("FMMT", 0, 0004, "Could not open the file %s! \n", ""); + free (OutputFileNameList); + free (ChildFileNameList); + return EFI_ABORTED; + } + fseek(OutFile, 0, SEEK_SET); + fseek(OutFile, 0, SEEK_END); + OutputFileSize =3D ftell(OutFile); + fclose(OutFile); + if (OutputFileSize > LargeFileSize) { + IsLargeFile =3D TRUE; + } + + OutputFileNameList->FFSName =3D (char *)malloc(strlen(OutputFileName)+= 1); + if (OutputFileNameList->FFSName =3D=3D NULL) { + Error ("FMMT", 0, 0004, "Out of resource, memory allocation failed! = \n", ""); + return EFI_OUT_OF_RESOURCES; + } + memcpy((char *)OutputFileNameList->FFSName, (char *)OutputFileName, st= rlen(OutputFileName)+1); + + if (EFI_ERROR (Status)) { + Error ("FMMT", 0, 0004, "error while encapsulate FD Image", "Gen= erate FV section failed!"); + free (OutputFileNameList); + free (ChildFileNameList); + return Status; + } + if (OutputFileNameList->Next =3D=3D NULL){ + break; + } + OutputFileNameList =3D OutputFileNameList->Next; + } + break; + default: + for (Id =3D FvInFd->FfsNumbers; Id <=3D FvInFd->FfsNumbers; Id--) { + if ((memcmp(&FvInFd->FfsAttuibutes[Id].GuidName, &(CurrentEnca= pData->FvExtHeader->FvName), sizeof(EFI_GUID)) =3D=3D 0)){ + FvInFd->FfsAttuibutes[Id].IsHandle =3D TRUE; + memcpy(OutputFileNameList->UiName, FvInFd->FfsAttuibutes[I= d].UiName, FvInFd->FfsAttuibutes[Id].UiNameSize); + OutputFileNameList->UiNameSize =3D FvInFd->FfsAttuibutes[I= d].UiNameSize; + OutputFileNameList->FFSName =3D FvInFd->FfsAttuibutes[Id].= FfsName; + OutputFileNameList->Depex =3D FvInFd->FfsAttuibutes[Id].De= pex; + OutputFileNameList->DepexLen =3D FvInFd->FfsAttuibutes[Id]= .DepexLen; + OutputFileNameList->FfsFoundFlag =3D TRUE; + OutputFileNameList->IsFFS =3D TRUE; + OutputFileNameList->InFvId =3D Id; + *OutputFile =3D OutputFileNameList; + return EFI_SUCCESS; + } + } + } + + if (CurrentEncapData =3D=3D NULL) { + LocalEncapData =3D FvInFd->EncapData; + } else { + if (OutputFileNameList !=3D NULL && OutputFileNameList->FFSName != =3D NULL && OutputFileNameList->IsFFS =3D=3D TRUE) { + *OutputFile =3D OutputFileNameList; + return EFI_SUCCESS; + } + LocalEncapData =3D CurrentEncapData; + } + ParentLevel -=3D 1; + + while (LocalEncapData->NextNode !=3D NULL) { + if (LocalEncapData->Level =3D=3D ParentLevel) { + LocalEncapDataTemp =3D LocalEncapData->NextNode; + if ((LocalEncapDataTemp !=3D NULL) && (LocalEncapDataTemp->Level = =3D=3D ParentLevel)) { + ParentType =3D LocalEncapDataTemp->Type; + break; + } + ParentType =3D LocalEncapData->Type; + break; + } + LocalEncapData =3D LocalEncapData->NextNode; + } + } while (ParentLevel !=3D Level_Break); + + *OutputFile =3D OutputFileNameList; + return EFI_SUCCESS; + +} + +EFI_STATUS +LibFindFvInEncapData ( + ENCAP_INFO_DATA *EncapData, + UINT8 *Index +) +{ + ENCAP_INFO_DATA *LocalEncapData; + LocalEncapData =3D EncapData; + if (LocalEncapData =3D=3D NULL) { + Error("FMMT", 0, 0005, "error while find FV in Encapulate buffer", "In= valid parameters."); + return EFI_INVALID_PARAMETER; + } + while (LocalEncapData !=3D NULL) { + if (LocalEncapData->RightNode !=3D NULL) { + LibFindFvInEncapData (LocalEncapData->RightNode, Index); + } + if (LocalEncapData->Type =3D=3D FMMT_ENCAP_TREE_FV) { + (*Index)++; + } + LocalEncapData =3D LocalEncapData->NextNode; + } + return EFI_SUCCESS; +} + +EFI_STATUS +LibLocateFvViaFvId ( + IN FIRMWARE_DEVICE *FdData, + IN CHAR8 *FvId, + IN OUT FV_INFORMATION **FvInFd +) +{ + UINT8 FvIndex1; + UINT8 FvIndex2; + BOOLEAN FvFoundFlag; + CHAR8* FvGuidName; + ENCAP_INFO_DATA *LocalEncapData; + ENCAP_INFO_DATA *LocalEncapDataRight; + ENCAP_INFO_DATA *LocalEncapDataNext; + FvIndex1 =3D 0; + FvIndex2 =3D 0; + FvFoundFlag =3D FALSE; + FvGuidName =3D NULL; + LocalEncapDataNext =3D NULL; + LocalEncapDataRight =3D NULL; + + if (FdData =3D=3D NULL || FvId =3D=3D NULL || FvInFd =3D=3D NULL || FdDa= ta->Fv =3D=3D NULL) { + Error ("FMMT", 0, 0005, "error while find FV in FD", "Invalid paramete= rs."); + return EFI_INVALID_PARAMETER; + } + + *FvInFd =3D FdData->Fv; + + if (strlen(FvId) < 3) { + Error ("FMMT", 0, 0005, "error while find FV in FD", "Invalid FvId, pl= ease double check the FvId. You can use view operate to get the FvId inform= ation!"); + return EFI_ABORTED; + } + + FvGuidName =3D (CHAR8 *) malloc (255); + if (FvGuidName =3D=3D NULL) { + Error ("FMMT", 0, 0005, "Resource: Memory can't be allocated", NULL); + return EFI_ABORTED; + } + memset(FvGuidName, '\0', 255); + LocalEncapData =3D NULL; + + if (strlen(FvId) =3D=3D 36) { + while (FvInFd !=3D NULL) { + if (((*FvInFd)->FvExtHeader) !=3D NULL) { + sprintf( + FvGuidName, + "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", + (*FvInFd)->FvExtHeader->FvName.Data1, + (*FvInFd)->FvExtHeader->FvName.Data2, + (*FvInFd)->FvExtHeader->FvName.Data3, + (*FvInFd)->FvExtHeader->FvName.Data4[0], + (*FvInFd)->FvExtHeader->FvName.Data4[1], + (*FvInFd)->FvExtHeader->FvName.Data4[2], + (*FvInFd)->FvExtHeader->FvName.Data4[3], + (*FvInFd)->FvExtHeader->FvName.Data4[4], + (*FvInFd)->FvExtHeader->FvName.Data4[5], + (*FvInFd)->FvExtHeader->FvName.Data4[6], + (*FvInFd)->FvExtHeader->FvName.Data4[7]); + if (strcmp(FvGuidName, FvId) =3D=3D 0) { + FvId =3D (*FvInFd)->FvName; + break; + } + } + if ((*FvInFd)->MulFvLevel > 1) { + LocalEncapData =3D (*FvInFd) -> EncapData; + LocalEncapData =3D LocalEncapData->NextNode; + while (LocalEncapData !=3D NULL) { + if (LocalEncapData->RightNode !=3D NULL) { + LocalEncapDataRight =3D LocalEncapData->RightNode; + while (LocalEncapDataRight !=3DNULL) { + if (LocalEncapDataRight->NextNode !=3D NULL) { + LocalEncapDataNext =3D LocalEncapDataRight->NextNode; + while (LocalEncapDataNext !=3D NULL) { + if (LocalEncapDataNext->Type =3D=3D FMMT_ENCAP_TREE_FV) { + if (LocalEncapDataNext->FvExtHeader !=3D NULL) { + sprintf( + FvGuidName, + "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02= X", + LocalEncapDataNext->FvExtHeader->FvName.Data1, + LocalEncapDataNext->FvExtHeader->FvName.Data2, + LocalEncapDataNext->FvExtHeader->FvName.Data3, + LocalEncapDataNext->FvExtHeader->FvName.Data4[0], + LocalEncapDataNext->FvExtHeader->FvName.Data4[1], + LocalEncapDataNext->FvExtHeader->FvName.Data4[2], + LocalEncapDataNext->FvExtHeader->FvName.Data4[3], + LocalEncapDataNext->FvExtHeader->FvName.Data4[4], + LocalEncapDataNext->FvExtHeader->FvName.Data4[5], + LocalEncapDataNext->FvExtHeader->FvName.Data4[6], + LocalEncapDataNext->FvExtHeader->FvName.Data4[7]= ); + if (strcmp(FvGuidName, FvId) =3D=3D 0) + { + sprintf(FvId, "%s%d", "FV", LocalEncapDataNext= ->FvId - 1); + break; + } + + } + } + LocalEncapDataNext =3D LocalEncapDataNext->NextNode; + } + } + LocalEncapDataRight =3D LocalEncapDataRight->RightNode; + } + } + if (LocalEncapData->Type =3D=3D FMMT_ENCAP_TREE_FV) { + if (LocalEncapData->FvExtHeader !=3D NULL) { + sprintf( + FvGuidName, + "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", + LocalEncapData->FvExtHeader->FvName.Data1, + LocalEncapData->FvExtHeader->FvName.Data2, + LocalEncapData->FvExtHeader->FvName.Data3, + LocalEncapData->FvExtHeader->FvName.Data4[0], + LocalEncapData->FvExtHeader->FvName.Data4[1], + LocalEncapData->FvExtHeader->FvName.Data4[2], + LocalEncapData->FvExtHeader->FvName.Data4[3], + LocalEncapData->FvExtHeader->FvName.Data4[4], + LocalEncapData->FvExtHeader->FvName.Data4[5], + LocalEncapData->FvExtHeader->FvName.Data4[6], + LocalEncapData->FvExtHeader->FvName.Data4[7]); + + if (strcmp(FvGuidName, FvId) =3D=3D 0) { + sprintf(FvId, "%s%d", "FV", LocalEncapData->FvId - 1); + break; + } + } + } + LocalEncapData =3D LocalEncapData->NextNode; + } + } + if ((*FvInFd)->FvNext =3D=3D 0) { + break; + } + *FvInFd =3D (*FvInFd)->FvNext; + } + } + *FvInFd =3D FdData->Fv; + FvIndex1 =3D (UINT8) atoi (FvId + 2); + + while (FvInFd !=3D NULL) { + if (((*FvInFd)->FvName) !=3D NULL) { + FvIndex2 =3D (UINT8) atoi ((*FvInFd)->FvName + 2); + LocalEncapData =3D (*FvInFd)->EncapData; + LibFindFvInEncapData (LocalEncapData, &FvIndex2); + + if ((FvIndex2 - 1 >=3D FvIndex1)) { + FvFoundFlag =3D TRUE; + break; + } + if ((*FvInFd)->FvNext =3D=3D 0) { + break; + } + } + *FvInFd =3D (*FvInFd)->FvNext; + } + if (FvGuidName !=3D NULL) { + free (FvGuidName); + } + // + // The specified FV id has issue, can not find the FV in FD. + // + if (!FvFoundFlag) { + Error ("FMMT", 0, 0005, "error while find FV in FD", "Invalid FvId, pl= ease double check the FvId. You can use view operate to get the FvId inform= ation!"); + return EFI_ABORTED; + } + + return EFI_SUCCESS; + +} + +#define BUILD_IN_TOOL_COUNT 4 + +EFI_HANDLE +LibPreDefinedGuidedTools ( + VOID +) +{ + EFI_GUID Guid; + STRING_LIST *Tool; + GUID_SEC_TOOL_ENTRY *FirstGuidTool; + GUID_SEC_TOOL_ENTRY *LastGuidTool; + GUID_SEC_TOOL_ENTRY *NewGuidTool; + UINT8 Index; + EFI_STATUS Status; + + CHAR8 PreDefinedGuidedTool[BUILD_IN_TOOL_COUNT][255] =3D { + "a31280ad-481e-41b6-95e8-127f4c984779 TIANO TianoCompress", + "ee4e5898-3914-4259-9d6e-dc7bd79403cf LZMA LzmaCompress", + "fc1bcdb0-7d31-49aa-936a-a4600d9dd083 CRC32 GenCrc32", + "3d532050-5cda-4fd0-879e-0f7f630d5afb BROTLI BrotliCompress" + }; + + Tool =3D NULL; + FirstGuidTool =3D NULL; + LastGuidTool =3D NULL; + NewGuidTool =3D NULL; + Index =3D 0; + + for (Index =3D 0; Index < BUILD_IN_TOOL_COUNT; Index++) { + Tool =3D SplitStringByWhitespace (PreDefinedGuidedTool[Index]); + if ((Tool !=3D NULL) && + (Tool->Count =3D=3D 3) + ) { + Status =3D StringToGuid (Tool->Strings[0], &Guid); + if (!EFI_ERROR (Status)) { + NewGuidTool =3D malloc (sizeof (GUID_SEC_TOOL_ENTRY)); + if (NewGuidTool !=3D NULL) { + memcpy (&(NewGuidTool->Guid), &Guid, sizeof (Guid)); + NewGuidTool->Name =3D CloneString(Tool->Strings[1]); + NewGuidTool->Path =3D CloneString(Tool->Strings[2]); + NewGuidTool->Next =3D NULL; + } else { + printf ("Error while allocate resource! \n"); + FreeStringList (Tool); + return NULL; + } + if (FirstGuidTool =3D=3D NULL) { + FirstGuidTool =3D NewGuidTool; + } else { + LastGuidTool->Next =3D NewGuidTool; + } + LastGuidTool =3D NewGuidTool; + } + } else { + fprintf (stdout, "Error"); + } + if (Tool !=3D NULL) { + FreeStringList (Tool); + Tool =3D NULL; + } + } + return FirstGuidTool; +} diff --git a/Platform/Intel/Tools/FMMT/GNUmakefile b/Platform/Intel/Tools/F= MMT/GNUmakefile new file mode 100644 index 0000000000..911d747451 --- /dev/null +++ b/Platform/Intel/Tools/FMMT/GNUmakefile @@ -0,0 +1,16 @@ +## @file +# GNU/Linux makefile for 'FMMT' module build. +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +MAKEROOT ?=3D $(EDK_TOOLS_PATH)/Source/C + +APPNAME =3D FMMT + +LIBS =3D -lCommon + +OBJECTS =3D FmmtLib.o Rebase.o FirmwareModuleManagement.o + +include $(MAKEROOT)/Makefiles/app.makefile + diff --git a/Platform/Intel/Tools/FMMT/Makefile b/Platform/Intel/Tools/FMMT= /Makefile new file mode 100644 index 0000000000..1a96e0e27f --- /dev/null +++ b/Platform/Intel/Tools/FMMT/Makefile @@ -0,0 +1,17 @@ +## @file +# Windows makefile for 'FMMT' module build. +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +!INCLUDE $(EDK_TOOLS_PATH)\Source\C\Makefiles\ms.common + +APPNAME =3D FMMT + +LIBS =3D $(LIB_PATH)\Common.lib + +OBJECTS =3D FirmwareModuleManagement.obj FmmtLib.obj Rebase.obj + +!INCLUDE $(EDK_TOOLS_PATH)\Source\C\Makefiles\ms.app + diff --git a/Platform/Intel/Tools/FMMT/Rebase.c b/Platform/Intel/Tools/FMMT= /Rebase.c new file mode 100644 index 0000000000..d32217d18c --- /dev/null +++ b/Platform/Intel/Tools/FMMT/Rebase.c @@ -0,0 +1,846 @@ +/** @file + + Library to rebase PE image. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "Rebase.h" +#include +#include +#ifdef __GNUC__ +#include +#else +#include +#include +#endif +#include +#include +#include +#include +#include "EfiUtilityMsgs.h" + +static +EFI_STATUS +FfsRebaseImageRead( +IN VOID *FileHandle, +IN UINTN FileOffset, +IN OUT UINT32 *ReadSize, +OUT VOID *Buffer +); + +EFI_STATUS +RebaseFfs( +IN OUT UINT64 BaseAddress, +IN CHAR8 *FileName, +IN OUT EFI_FFS_FILE_HEADER *FfsFile, +IN UINTN XipOffset +) +/*++ + +Routine Description: + +This function determines if a file is XIP and should be rebased. It will +rebase any PE32 sections found in the file using the base address. + +Arguments: + +FvInfo A pointer to FV_INFO struture. +FileName Ffs File PathName +FfsFile A pointer to Ffs file image. +XipOffset The offset address to use for rebasing the XIP file imag= e. + +Returns: + +EFI_SUCCESS The image was properly rebased. +EFI_INVALID_PARAMETER An input parameter is invalid. +EFI_ABORTED An error occurred while rebasing the input file im= age. +EFI_OUT_OF_RESOURCES Could not allocate a required resource. +EFI_NOT_FOUND No compressed sections could be found. + +--*/ +{ + EFI_STATUS Status; + PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; + PE_COFF_LOADER_IMAGE_CONTEXT OrigImageContext; + EFI_PHYSICAL_ADDRESS XipBase; + EFI_PHYSICAL_ADDRESS NewPe32BaseAddress; + UINTN Index; + EFI_FILE_SECTION_POINTER CurrentPe32Section; + EFI_FFS_FILE_STATE SavedState; + EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; + EFI_TE_IMAGE_HEADER *TEImageHeader; + UINT8 *MemoryImagePointer; + EFI_IMAGE_SECTION_HEADER *SectionHeader; + CHAR8 PeFileName[MAX_LONG_FILE_PATH]; + CHAR8 *Cptr; + FILE *PeFile; + UINT8 *PeFileBuffer; + UINT32 PeFileSize; + CHAR8 *PdbPointer; + UINT32 FfsHeaderSize; + UINT32 CurSecHdrSize; + CHAR8 *LongFilePathName; + + Index =3D 0; + MemoryImagePointer =3D NULL; + TEImageHeader =3D NULL; + ImgHdr =3D NULL; + SectionHeader =3D NULL; + Cptr =3D NULL; + PeFile =3D NULL; + PeFileBuffer =3D NULL; + + // + // Don't need to relocate image when BaseAddress is zero and no ForceReb= ase Flag specified. + // + if (BaseAddress =3D=3D 0) { + return EFI_SUCCESS; + } + + XipBase =3D BaseAddress + XipOffset; + + // + // We only process files potentially containing PE32 sections. + // + switch (FfsFile->Type) { + case EFI_FV_FILETYPE_SECURITY_CORE: + case EFI_FV_FILETYPE_PEI_CORE: + case EFI_FV_FILETYPE_PEIM: + case EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER: + case EFI_FV_FILETYPE_DRIVER: + case EFI_FV_FILETYPE_DXE_CORE: + break; + case EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE: + // + // Rebase the inside FvImage. + // + GetChildFvFromFfs (BaseAddress, FfsFile, XipOffset); + + // + // Search PE/TE section in FV sectin. + // + break; + default: + return EFI_SUCCESS; + } + + FfsHeaderSize =3D GetFfsHeaderLength(FfsFile); + // + // Rebase each PE32 section + // + Status =3D EFI_SUCCESS; + for (Index =3D 1;; Index++) { + // + // Init Value + // + NewPe32BaseAddress =3D 0; + + // + // Find Pe Image + // + Status =3D GetSectionByType(FfsFile, EFI_SECTION_PE32, Index, &Current= Pe32Section); + if (EFI_ERROR(Status)) { + break; + } + CurSecHdrSize =3D GetSectionHeaderLength(CurrentPe32Section.CommonHead= er); + + // + // Initialize context + // + memset(&ImageContext, 0, sizeof (ImageContext)); + ImageContext.Handle =3D (VOID *)((UINTN)CurrentPe32Section.Pe32Section= + CurSecHdrSize); + ImageContext.ImageRead =3D (PE_COFF_LOADER_READ_FILE)FfsRebaseImageRea= d; + Status =3D PeCoffLoaderGetImageInfo(&ImageContext); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid PeImage", "The input file is %s and th= e return status is %x", FileName, (int)Status); + return Status; + } + + //if ((ImageContext.Machine =3D=3D EFI_IMAGE_MACHINE_ARMT) || + // (ImageContext.Machine =3D=3D EFI_IMAGE_MACHINE_AARCH64)) { + // mArm =3D TRUE; + //} + + // + // Keep Image Context for PE image in FV + // + memcpy(&OrigImageContext, &ImageContext, sizeof (ImageContext)); + + // + // Get File PdbPointer + // + PdbPointer =3D PeCoffLoaderGetPdbPointer(ImageContext.Handle); + if (PdbPointer =3D=3D NULL) { + PdbPointer =3D FileName; + } + + // + // Get PeHeader pointer + // + ImgHdr =3D (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((UINTN)CurrentPe32Secti= on.Pe32Section + CurSecHdrSize + ImageContext.PeCoffHeaderOffset); + + // + // Calculate the PE32 base address, based on file type + // + switch (FfsFile->Type) { + case EFI_FV_FILETYPE_SECURITY_CORE: + case EFI_FV_FILETYPE_PEI_CORE: + case EFI_FV_FILETYPE_PEIM: + case EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER: + // + // Check if section-alignment and file-alignment match or not + // + if ((ImgHdr->Pe32.OptionalHeader.SectionAlignment !=3D ImgHdr->Pe32.= OptionalHeader.FileAlignment)) { + // + // Xip module has the same section alignment and file alignment. + // + Error(NULL, 0, 3000, "Invalid", "Section-Alignment and File-Alignm= ent do not match : %s.", FileName); + return EFI_ABORTED; + } + // + // PeImage has no reloc section. It will try to get reloc data from = the original EFI image. + // + if (ImageContext.RelocationsStripped) { + // + // Construct the original efi file Name + // + if (strlen (FileName) > MAX_LONG_FILE_PATH - 1) { + Error(NULL, 0, 3000, "Invalid", "The file name for %s is too lon= g.", FileName); + return EFI_ABORTED; + } + strncpy(PeFileName, FileName, MAX_LONG_FILE_PATH - 1); + PeFileName[MAX_LONG_FILE_PATH - 1] =3D 0; + Cptr =3D PeFileName + strlen(PeFileName); + while (*Cptr !=3D '.') { + Cptr--; + } + if (*Cptr !=3D '.') { + Error(NULL, 0, 3000, "Invalid", "The file %s has no .reloc secti= on.", FileName); + return EFI_ABORTED; + } + else { + *(Cptr + 1) =3D 'e'; + *(Cptr + 2) =3D 'f'; + *(Cptr + 3) =3D 'i'; + *(Cptr + 4) =3D '\0'; + } + LongFilePathName =3D LongFilePath(PeFileName); + if (LongFilePathName =3D=3D NULL) { + Error(NULL, 0, 3000, "Invalid", "Fail to get long file path for = file %s.", FileName); + return EFI_ABORTED; + } + PeFile =3D fopen(LongFilePathName, "rb"); + if (PeFile =3D=3D NULL) { + Warning(NULL, 0, 0, "Invalid", "The file %s has no .reloc sectio= n.", FileName); + //Error (NULL, 0, 3000, "Invalid", "The file %s has no .reloc se= ction.", FileName); + //return EFI_ABORTED; + break; + } + // + // Get the file size + // + PeFileSize =3D _filelength(fileno(PeFile)); + PeFileBuffer =3D (UINT8 *)malloc(PeFileSize); + if (PeFileBuffer =3D=3D NULL) { + Error(NULL, 0, 4001, "Resource", "memory cannot be allocated on = rebase of %s", FileName); + fclose(PeFile); + return EFI_OUT_OF_RESOURCES; + } + // + // Read Pe File + // + fread(PeFileBuffer, sizeof (UINT8), PeFileSize, PeFile); + // + // close file + // + fclose(PeFile); + // + // Handle pointer to the original efi image. + // + ImageContext.Handle =3D PeFileBuffer; + Status =3D PeCoffLoaderGetImageInfo(&ImageContext); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid PeImage", "The input file is %s an= d the return status is %x", FileName, (int)Status); + return Status; + } + ImageContext.RelocationsStripped =3D FALSE; + } + + NewPe32BaseAddress =3D XipBase + (UINTN)CurrentPe32Section.Pe32Secti= on + CurSecHdrSize - (UINTN)FfsFile; + break; + + case EFI_FV_FILETYPE_DRIVER: + case EFI_FV_FILETYPE_DXE_CORE: + // + // Check if section-alignment and file-alignment match or not + // + if ((ImgHdr->Pe32.OptionalHeader.SectionAlignment !=3D ImgHdr->Pe32.= OptionalHeader.FileAlignment)) { + // + // Xip module has the same section alignment and file alignment. + // + Error(NULL, 0, 3000, "Invalid", "Section-Alignment and File-Alignm= ent do not match : %s.", FileName); + return EFI_ABORTED; + } + NewPe32BaseAddress =3D XipBase + (UINTN)CurrentPe32Section.Pe32Secti= on + CurSecHdrSize - (UINTN)FfsFile; + break; + + default: + // + // Not supported file type + // + return EFI_SUCCESS; + } + + // + // Relocation doesn't exist + // + if (ImageContext.RelocationsStripped) { + Warning(NULL, 0, 0, "Invalid", "The file %s has no .reloc section.",= FileName); + continue; + } + + // + // Relocation exist and rebase + // + // + // Load and Relocate Image Data + // + MemoryImagePointer =3D (UINT8 *)malloc((UINTN)ImageContext.ImageSize += ImageContext.SectionAlignment); + if (MemoryImagePointer =3D=3D NULL) { + Error(NULL, 0, 4001, "Resource", "memory cannot be allocated on reba= se of %s", FileName); + return EFI_OUT_OF_RESOURCES; + } + memset((VOID *)MemoryImagePointer, 0, (UINTN)ImageContext.ImageSize + = ImageContext.SectionAlignment); + ImageContext.ImageAddress =3D ((UINTN)MemoryImagePointer + ImageContex= t.SectionAlignment - 1) & (~((UINTN)ImageContext.SectionAlignment - 1)); + + Status =3D PeCoffLoaderLoadImage(&ImageContext); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid", "LocateImage() call failed on rebase= of %s", FileName); + free((VOID *)MemoryImagePointer); + return Status; + } + + ImageContext.DestinationAddress =3D NewPe32BaseAddress; + Status =3D PeCoffLoaderRelocateImage(&ImageContext); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid", "RelocateImage() call failed on reba= se of %s", FileName); + free((VOID *)MemoryImagePointer); + return Status; + } + + // + // Copy Relocated data to raw image file. + // + SectionHeader =3D (EFI_IMAGE_SECTION_HEADER *)( + (UINTN)ImgHdr + + sizeof (UINT32)+ + sizeof (EFI_IMAGE_FILE_HEADER)+ + ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader + ); + + for (Index =3D 0; Index < ImgHdr->Pe32.FileHeader.NumberOfSections; In= dex++, SectionHeader++) { + CopyMem( + (UINT8 *)CurrentPe32Section.Pe32Section + CurSecHdrSize + SectionH= eader->PointerToRawData, + (VOID*)(UINTN)(ImageContext.ImageAddress + SectionHeader->VirtualA= ddress), + SectionHeader->SizeOfRawData + ); + } + + free((VOID *)MemoryImagePointer); + MemoryImagePointer =3D NULL; + if (PeFileBuffer !=3D NULL) { + free(PeFileBuffer); + PeFileBuffer =3D NULL; + } + + // + // Update Image Base Address + // + if (ImgHdr->Pe32.OptionalHeader.Magic =3D=3D EFI_IMAGE_NT_OPTIONAL_HDR= 32_MAGIC) { + ImgHdr->Pe32.OptionalHeader.ImageBase =3D (UINT32)NewPe32BaseAddress; + } + else if (ImgHdr->Pe32Plus.OptionalHeader.Magic =3D=3D EFI_IMAGE_NT_OPT= IONAL_HDR64_MAGIC) { + ImgHdr->Pe32Plus.OptionalHeader.ImageBase =3D NewPe32BaseAddress; + } + else { + Error(NULL, 0, 3000, "Invalid", "unknown PE magic signature %X in PE= 32 image %s", + ImgHdr->Pe32.OptionalHeader.Magic, + FileName + ); + return EFI_ABORTED; + } + + // + // Now update file checksum + // + if (FfsFile->Attributes & FFS_ATTRIB_CHECKSUM) { + SavedState =3D FfsFile->State; + FfsFile->IntegrityCheck.Checksum.File =3D 0; + FfsFile->State =3D 0; + FfsFile->IntegrityCheck.Checksum.File =3D CalculateChecksum8( + (UINT8 *)((UINT8 *)FfsFile + FfsHeaderSize), + GetFfsFileLength(FfsFile) - FfsHeaderSize + ); + FfsFile->State =3D SavedState; + } + + } + + if (FfsFile->Type !=3D EFI_FV_FILETYPE_SECURITY_CORE && + FfsFile->Type !=3D EFI_FV_FILETYPE_PEI_CORE && + FfsFile->Type !=3D EFI_FV_FILETYPE_PEIM && + FfsFile->Type !=3D EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER && + FfsFile->Type !=3D EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE + ) { + // + // Only Peim code may have a TE section + // + return EFI_SUCCESS; + } + + // + // Now process TE sections + // + for (Index =3D 1;; Index++) { + NewPe32BaseAddress =3D 0; + + // + // Find Te Image + // + Status =3D GetSectionByType(FfsFile, EFI_SECTION_TE, Index, &CurrentPe= 32Section); + if (EFI_ERROR(Status)) { + break; + } + + CurSecHdrSize =3D GetSectionHeaderLength(CurrentPe32Section.CommonHead= er); + + // + // Calculate the TE base address, the FFS file base plus the offset of= the TE section less the size stripped off + // by GenTEImage + // + TEImageHeader =3D (EFI_TE_IMAGE_HEADER *)((UINT8 *)CurrentPe32Section.= Pe32Section + CurSecHdrSize); + + // + // Initialize context, load image info. + // + memset(&ImageContext, 0, sizeof (ImageContext)); + ImageContext.Handle =3D (VOID *)TEImageHeader; + ImageContext.ImageRead =3D (PE_COFF_LOADER_READ_FILE)FfsRebaseImageRea= d; + Status =3D PeCoffLoaderGetImageInfo(&ImageContext); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid TeImage", "The input file is %s and th= e return status is %x", FileName, (int)Status); + return Status; + } + + //if ((ImageContext.Machine =3D=3D EFI_IMAGE_MACHINE_ARMT) || + // (ImageContext.Machine =3D=3D EFI_IMAGE_MACHINE_AARCH64)) { + // mArm =3D TRUE; + //} + + // + // Keep Image Context for TE image in FV + // + memcpy(&OrigImageContext, &ImageContext, sizeof (ImageContext)); + + // + // Get File PdbPointer + // + PdbPointer =3D PeCoffLoaderGetPdbPointer(ImageContext.Handle); + if (PdbPointer =3D=3D NULL) { + PdbPointer =3D FileName; + } + // + // Set new rebased address. + // + NewPe32BaseAddress =3D XipBase + (UINTN)TEImageHeader + sizeof (EFI_TE= _IMAGE_HEADER) \ + - TEImageHeader->StrippedSize - (UINTN)FfsFile; + + // + // if reloc is stripped, try to get the original efi image to get relo= c info. + // + if (ImageContext.RelocationsStripped) { + // + // Construct the original efi file name + // + if (strlen (FileName) > MAX_LONG_FILE_PATH - 1) { + Error(NULL, 0, 3000, "Invalid", "The file name for %s is too long.= ", FileName); + return EFI_ABORTED; + } + strncpy(PeFileName, FileName, MAX_LONG_FILE_PATH - 1); + PeFileName[MAX_LONG_FILE_PATH - 1] =3D 0; + Cptr =3D PeFileName + strlen(PeFileName); + while (*Cptr !=3D '.') { + Cptr--; + } + + if (*Cptr !=3D '.') { + Error(NULL, 0, 3000, "Invalid", "The file %s has no .reloc section= .", FileName); + return EFI_ABORTED; + } + else { + *(Cptr + 1) =3D 'e'; + *(Cptr + 2) =3D 'f'; + *(Cptr + 3) =3D 'i'; + *(Cptr + 4) =3D '\0'; + } + + LongFilePathName =3D LongFilePath(PeFileName); + if (LongFilePathName =3D=3D NULL) { + Error(NULL, 0, 3000, "Invalid", "Fail to get long file path for fi= le %s.", FileName); + return EFI_ABORTED; + } + PeFile =3D fopen(LongFilePathName, "rb"); + if (PeFile =3D=3D NULL) { + Warning(NULL, 0, 0, "Invalid", "The file %s has no .reloc section.= ", FileName); + //Error (NULL, 0, 3000, "Invalid", "The file %s has no .reloc sect= ion.", FileName); + //return EFI_ABORTED; + } + else { + // + // Get the file size + // + PeFileSize =3D _filelength(fileno(PeFile)); + PeFileBuffer =3D (UINT8 *)malloc(PeFileSize); + if (PeFileBuffer =3D=3D NULL) { + Error(NULL, 0, 4001, "Resource", "memory cannot be allocated on = rebase of %s", FileName); + fclose(PeFile); + return EFI_OUT_OF_RESOURCES; + } + // + // Read Pe File + // + fread(PeFileBuffer, sizeof (UINT8), PeFileSize, PeFile); + // + // close file + // + fclose(PeFile); + // + // Append reloc section into TeImage + // + ImageContext.Handle =3D PeFileBuffer; + Status =3D PeCoffLoaderGetImageInfo(&ImageContext); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid TeImage", "The input file is %s an= d the return status is %x", FileName, (int)Status); + return Status; + } + ImageContext.RelocationsStripped =3D FALSE; + } + } + // + // Relocation doesn't exist + // + if (ImageContext.RelocationsStripped) { + Warning(NULL, 0, 0, "Invalid", "The file %s has no .reloc section.",= FileName); + continue; + } + + // + // Relocation exist and rebase + // + // + // Load and Relocate Image Data + // + MemoryImagePointer =3D (UINT8 *)malloc((UINTN)ImageContext.ImageSize += ImageContext.SectionAlignment); + if (MemoryImagePointer =3D=3D NULL) { + Error(NULL, 0, 4001, "Resource", "memory cannot be allocated on reba= se of %s", FileName); + return EFI_OUT_OF_RESOURCES; + } + memset((VOID *)MemoryImagePointer, 0, (UINTN)ImageContext.ImageSize + = ImageContext.SectionAlignment); + ImageContext.ImageAddress =3D ((UINTN)MemoryImagePointer + ImageContex= t.SectionAlignment - 1) & (~((UINTN)ImageContext.SectionAlignment - 1)); + + Status =3D PeCoffLoaderLoadImage(&ImageContext); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid", "LocateImage() call failed on rebase= of %s", FileName); + free((VOID *)MemoryImagePointer); + return Status; + } + // + // Reloacate TeImage + // + ImageContext.DestinationAddress =3D NewPe32BaseAddress; + Status =3D PeCoffLoaderRelocateImage(&ImageContext); + if (EFI_ERROR(Status)) { + Error(NULL, 0, 3000, "Invalid", "RelocateImage() call failed on reba= se of TE image %s", FileName); + free((VOID *)MemoryImagePointer); + return Status; + } + + // + // Copy the relocated image into raw image file. + // + SectionHeader =3D (EFI_IMAGE_SECTION_HEADER *)(TEImageHeader + 1); + for (Index =3D 0; Index < TEImageHeader->NumberOfSections; Index++, Se= ctionHeader++) { + if (!ImageContext.IsTeImage) { + CopyMem( + (UINT8 *)TEImageHeader + sizeof (EFI_TE_IMAGE_HEADER)-TEImageHea= der->StrippedSize + SectionHeader->PointerToRawData, + (VOID*)(UINTN)(ImageContext.ImageAddress + SectionHeader->Virtua= lAddress), + SectionHeader->SizeOfRawData + ); + } + else { + CopyMem( + (UINT8 *)TEImageHeader + sizeof (EFI_TE_IMAGE_HEADER)-TEImageHea= der->StrippedSize + SectionHeader->PointerToRawData, + (VOID*)(UINTN)(ImageContext.ImageAddress + sizeof (EFI_TE_IMAGE_= HEADER)-TEImageHeader->StrippedSize + SectionHeader->VirtualAddress), + SectionHeader->SizeOfRawData + ); + } + } + + // + // Free the allocated memory resource + // + free((VOID *)MemoryImagePointer); + MemoryImagePointer =3D NULL; + if (PeFileBuffer !=3D NULL) { + free(PeFileBuffer); + PeFileBuffer =3D NULL; + } + + // + // Update Image Base Address + // + TEImageHeader->ImageBase =3D NewPe32BaseAddress; + + // + // Now update file checksum + // + if (FfsFile->Attributes & FFS_ATTRIB_CHECKSUM) { + SavedState =3D FfsFile->State; + FfsFile->IntegrityCheck.Checksum.File =3D 0; + FfsFile->State =3D 0; + FfsFile->IntegrityCheck.Checksum.File =3D CalculateChecksum8( + (UINT8 *)((UINT8 *)FfsFile + FfsHeaderSize), + GetFfsFileLength(FfsFile) - FfsHeaderSize + ); + FfsFile->State =3D SavedState; + } + } + + return EFI_SUCCESS; +} + +EFI_STATUS +FfsRebaseImageRead( +IN VOID *FileHandle, +IN UINTN FileOffset, +IN OUT UINT32 *ReadSize, +OUT VOID *Buffer +) +/*++ + +Routine Description: + +Support routine for the PE/COFF Loader that reads a buffer from a PE/COFF = file + +Arguments: + +FileHandle - The handle to the PE/COFF file + +FileOffset - The offset, in bytes, into the file to read + +ReadSize - The number of bytes to read from the file starting at FileOff= set + +Buffer - A pointer to the buffer to read the data into. + +Returns: + +EFI_SUCCESS - ReadSize bytes of data were read into Buffer from the PE/COF= F file starting at FileOffset + +--*/ +{ + CHAR8 *Destination8; + CHAR8 *Source8; + UINT32 Length; + + Destination8 =3D Buffer; + Source8 =3D (CHAR8 *)((UINTN)FileHandle + FileOffset); + Length =3D *ReadSize; + while (Length--) { + *(Destination8++) =3D *(Source8++); + } + + return EFI_SUCCESS; +} + +EFI_STATUS +GetChildFvFromFfs ( + IN UINT64 BaseAddress, + IN EFI_FFS_FILE_HEADER *FfsFile, + IN UINTN XipOffset + ) +/*++ + +Routine Description: + + This function gets all child FvImages in the input FfsFile, and records + their base address to the parent image. + +Arguments: + FvInfo A pointer to FV_INFO struture. + FfsFile A pointer to Ffs file image that may contain FvImage. + XipOffset The offset address to the parent FvImage base. + +Returns: + + EFI_SUCCESS Base address of child Fv image is recorded. +--*/ +{ + EFI_STATUS Status; + UINTN Index; + EFI_FILE_SECTION_POINTER SubFvSection; + EFI_FIRMWARE_VOLUME_HEADER *SubFvImageHeader; + EFI_PHYSICAL_ADDRESS SubFvBaseAddress; + EFI_FIRMWARE_VOLUME_HEADER *OrigFvHeader; + UINT32 OrigFvLength; + EFI_PHYSICAL_ADDRESS OrigFvBaseAddress; + EFI_FFS_FILE_HEADER *CurrentFile; + + // + // Initialize FV library, saving previous values + // + OrigFvHeader =3D NULL; + GetFvHeader (&OrigFvHeader, &OrigFvLength); + OrigFvBaseAddress =3D BaseAddress; + for (Index =3D 1;; Index++) { + // + // Find FV section + // + Status =3D GetSectionByType (FfsFile, EFI_SECTION_FIRMWARE_VOLUME_IMAG= E, Index, &SubFvSection); + if (EFI_ERROR (Status)) { + break; + } + SubFvImageHeader =3D (EFI_FIRMWARE_VOLUME_HEADER *) ((UINT8 *) SubFvSe= ction.FVImageSection + GetSectionHeaderLength(SubFvSection.FVImageSection)); + + // + // Rebase on Flash + // + SubFvBaseAddress =3D OrigFvBaseAddress + (UINTN) SubFvImageHeader - (U= INTN) FfsFile + XipOffset; + //mFvBaseAddress[mFvBaseAddressNumber ++ ] =3D SubFvBaseAddress; + BaseAddress =3D SubFvBaseAddress; + InitializeFvLib(SubFvImageHeader, (UINT32) SubFvImageHeader->FvLength); + + Status =3D GetNextFile (NULL, &CurrentFile); + if (EFI_ERROR (Status)) { + Error (NULL, 0, 0003, "error parsing FV image", "FFS file can't be f= ound"); + continue; + } + while (CurrentFile) { + RebaseFfs (BaseAddress, "", CurrentFile, (UINTN) CurrentFile - (UINT= N) SubFvImageHeader); + Status =3D GetNextFile (CurrentFile, &CurrentFile); + if (EFI_ERROR (Status)) { + break; + } + } + } + + BaseAddress =3D OrigFvBaseAddress; + if (OrigFvHeader !=3D NULL) { + InitializeFvLib(OrigFvHeader, OrigFvLength); + } + + return EFI_SUCCESS; +} + +EFI_STATUS +GetPe32Info ( + IN UINT8 *Pe32, + OUT UINT32 *EntryPoint, + OUT UINT32 *BaseOfCode, + OUT UINT16 *MachineType + ) +/*++ + +Routine Description: + + Retrieves the PE32 entry point offset and machine type from PE image or = TeImage. + See EfiImage.h for machine types. The entry point offset is from the be= ginning + of the PE32 buffer passed in. + +Arguments: + + Pe32 Beginning of the PE32. + EntryPoint Offset from the beginning of the PE32 to the image entry p= oint. + BaseOfCode Base address of code. + MachineType Magic number for the machine type. + +Returns: + + EFI_SUCCESS Function completed successfully. + EFI_ABORTED Error encountered. + EFI_INVALID_PARAMETER A required parameter was NULL. + EFI_UNSUPPORTED The operation is unsupported. + +--*/ +{ + EFI_IMAGE_DOS_HEADER *DosHeader; + EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; + EFI_TE_IMAGE_HEADER *TeHeader; + + // + // Verify input parameters + // + if (Pe32 =3D=3D NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // First check whether it is one TE Image. + // + TeHeader =3D (EFI_TE_IMAGE_HEADER *) Pe32; + if (TeHeader->Signature =3D=3D EFI_TE_IMAGE_HEADER_SIGNATURE) { + // + // By TeImage Header to get output + // + *EntryPoint =3D TeHeader->AddressOfEntryPoint + sizeof (EFI_TE_IMAGE= _HEADER) - TeHeader->StrippedSize; + *BaseOfCode =3D TeHeader->BaseOfCode + sizeof (EFI_TE_IMAGE_HEADER) = - TeHeader->StrippedSize; + *MachineType =3D TeHeader->Machine; + } else { + + // + // Then check whether + // First is the DOS header + // + DosHeader =3D (EFI_IMAGE_DOS_HEADER *) Pe32; + + // + // Verify DOS header is expected + // + if (DosHeader->e_magic !=3D EFI_IMAGE_DOS_SIGNATURE) { + Error (NULL, 0, 3000, "Invalid", "Unknown magic number in the DOS he= ader, 0x%04X.", DosHeader->e_magic); + return EFI_UNSUPPORTED; + } + // + // Immediately following is the NT header. + // + ImgHdr =3D (EFI_IMAGE_OPTIONAL_HEADER_UNION *) ((UINTN) Pe32 + DosHead= er->e_lfanew); + + // + // Verify NT header is expected + // + if (ImgHdr->Pe32.Signature !=3D EFI_IMAGE_NT_SIGNATURE) { + Error (NULL, 0, 3000, "Invalid", "Unrecognized image signature 0x%08= X.", (unsigned) ImgHdr->Pe32.Signature); + return EFI_UNSUPPORTED; + } + // + // Get output + // + *EntryPoint =3D ImgHdr->Pe32.OptionalHeader.AddressOfEntryPoint; + *BaseOfCode =3D ImgHdr->Pe32.OptionalHeader.BaseOfCode; + *MachineType =3D ImgHdr->Pe32.FileHeader.Machine; + } + + // + // Verify machine type is supported + // + if ((*MachineType !=3D EFI_IMAGE_MACHINE_IA32) && (*MachineType !=3D EFI= _IMAGE_MACHINE_X64) && (*MachineType !=3D EFI_IMAGE_MACHINE_EBC) && + (*MachineType !=3D EFI_IMAGE_MACHINE_ARMT) && (*MachineType !=3D EFI= _IMAGE_MACHINE_AARCH64)) { + Error (NULL, 0, 3000, "Invalid", "Unrecognized machine type in the PE3= 2 file."); + return EFI_UNSUPPORTED; + } + + return EFI_SUCCESS; +} + diff --git a/Platform/Intel/Tools/FMMT/Rebase.h b/Platform/Intel/Tools/FMMT= /Rebase.h new file mode 100644 index 0000000000..57604a357f --- /dev/null +++ b/Platform/Intel/Tools/FMMT/Rebase.h @@ -0,0 +1,31 @@ +/** @file Rebase.h + + Library to rebase PE image. + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _FMMT_REBASE_H +#define _FMMT_REBASE_H + +#include +#include + +EFI_STATUS +RebaseFfs( +IN OUT UINT64 BaseAddress, +IN CHAR8 *FileName, +IN OUT EFI_FFS_FILE_HEADER *FfsFile, +IN UINTN XipOffset +); + +EFI_STATUS +GetChildFvFromFfs ( + IN UINT64 BaseAddress, + IN EFI_FFS_FILE_HEADER *FfsFile, + IN UINTN XipOffset +); + +#endif --=20 2.18.0.windows.1 -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- Groups.io Links: You receive all messages sent to this group. View/Reply Online (#42669): https://edk2.groups.io/g/devel/message/42669 Mute This Topic: https://groups.io/mt/32154334/1787277 Group Owner: devel+owner@edk2.groups.io Unsubscribe: https://edk2.groups.io/g/devel/unsub [importer@patchew.org] -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-